@stateward/core 1.2.2 → 1.3.1

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 (75) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/fingerprints.d.ts +3 -1
  4. package/dist/backend/fingerprints.js +198 -9
  5. package/dist/backend/program-record.d.ts +7 -0
  6. package/dist/backend/program-size.d.ts +32 -0
  7. package/dist/backend/program-size.js +166 -0
  8. package/dist/backend/typescript6.d.ts +62 -32
  9. package/dist/backend/typescript6.js +1615 -164
  10. package/dist/baseline.d.ts +1 -1
  11. package/dist/baseline.js +14 -10
  12. package/dist/cache.d.ts +92 -4
  13. package/dist/cache.js +257 -68
  14. package/dist/checker.d.ts +28 -3
  15. package/dist/checker.js +42 -8
  16. package/dist/class-id.d.ts +34 -0
  17. package/dist/class-id.js +93 -0
  18. package/dist/code-text.d.ts +8 -0
  19. package/dist/code-text.js +66 -0
  20. package/dist/config-file.js +7 -5
  21. package/dist/config.d.ts +10 -2
  22. package/dist/config.js +490 -48
  23. package/dist/define.d.ts +8 -2
  24. package/dist/disk-cache.d.ts +34 -2
  25. package/dist/disk-cache.js +82 -15
  26. package/dist/engine.d.ts +64 -3
  27. package/dist/engine.js +474 -59
  28. package/dist/fact-lines.d.ts +31 -0
  29. package/dist/fact-lines.js +197 -0
  30. package/dist/facts-versions.d.ts +27 -0
  31. package/dist/facts-versions.js +99 -0
  32. package/dist/fixes.js +4 -1
  33. package/dist/ignores.d.ts +11 -0
  34. package/dist/ignores.js +74 -27
  35. package/dist/implementation.d.ts +0 -6
  36. package/dist/implementation.js +0 -17
  37. package/dist/index.d.ts +9 -9
  38. package/dist/index.js +12 -7
  39. package/dist/internal.d.ts +13 -6
  40. package/dist/internal.js +7 -3
  41. package/dist/journal.d.ts +40 -0
  42. package/dist/journal.js +197 -0
  43. package/dist/lazy.d.ts +8 -1
  44. package/dist/lazy.js +27 -2
  45. package/dist/ledger.d.ts +2 -2
  46. package/dist/ledger.js +2 -2
  47. package/dist/memory-plan.d.ts +121 -0
  48. package/dist/memory-plan.js +174 -0
  49. package/dist/off-by-default.d.ts +13 -0
  50. package/dist/off-by-default.js +15 -0
  51. package/dist/options.d.ts +21 -5
  52. package/dist/options.js +22 -7
  53. package/dist/package-facts.d.ts +211 -17
  54. package/dist/package-facts.js +520 -38
  55. package/dist/plan.d.ts +1 -1
  56. package/dist/plan.js +7 -2
  57. package/dist/release.d.ts +12 -21
  58. package/dist/release.js +26 -38
  59. package/dist/renamed.d.ts +22 -3
  60. package/dist/renamed.js +50 -16
  61. package/dist/rollout.js +7 -4
  62. package/dist/severity.d.ts +1 -1
  63. package/dist/severity.js +17 -3
  64. package/dist/test-runner.d.ts +18 -0
  65. package/dist/test-runner.js +483 -0
  66. package/dist/testing.d.ts +3 -3
  67. package/dist/testing.js +5 -5
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +60 -38
  70. package/dist/types.d.ts +704 -20
  71. package/dist/unread.d.ts +90 -0
  72. package/dist/unread.js +405 -0
  73. package/dist/vocabulary.d.ts +1 -1
  74. package/dist/vocabulary.js +1 -1
  75. package/package.json +4 -2
@@ -1,12 +1,17 @@
1
1
  import path from "node:path";
2
2
  import picomatch from "picomatch";
3
3
  import ts from "typescript";
4
+ import { codeOnOneLine } from "../code-text.js";
4
5
  import { computeFingerprints, declarationTextHash, packageDependencies, packageEntries, packageManifests, packageNames, } from "./fingerprints.js";
5
6
  import { markedComments } from "./comments.js";
6
7
  import { recordInputs, recordingHost, replays } from "./program-record.js";
8
+ import { programSize } from "./program-size.js";
7
9
  import { declarationAtPath, declarationPath } from "./qualified-ids.js";
8
10
  import { displayPath } from "../display-path.js";
9
11
  import { expandTsconfigs } from "../tsconfigs.js";
12
+ import { testRunnerFiles } from "../test-runner.js";
13
+ import { checkFactKeys, factGrainOf, factKeysDigest, pathOf, readFactKeyChecks, } from "../package-facts.js";
14
+ import { declaredPackageOf } from "../class-id.js";
10
15
  /** The tsconfig could not be read or is invalid. */
11
16
  export class TsconfigError extends Error {
12
17
  /** The one change that fixes it, shown on a `= fix:` line. */
@@ -493,6 +498,64 @@ function unresolvedImportsOf(program, file) {
493
498
  }
494
499
  return found;
495
500
  }
501
+ /**
502
+ * The package modules one file imports, as TypeScript reads its imports (not its text): import
503
+ * and export declarations, `import x = require(…)`, `import(…)`, `require(…)`, `import("…")`
504
+ * types, and the JSX runtime a file with JSX uses by the project's `jsx` option. Relative and
505
+ * absolute paths are left out: they name the project's own files.
506
+ */
507
+ export function importedModules(sourceFile, options) {
508
+ const found = new Set();
509
+ const add = (specifier) => {
510
+ if (specifier === undefined || !ts.isStringLiteralLike(specifier))
511
+ return;
512
+ const name = specifier.text;
513
+ if (name === "" || name.startsWith(".") || path.isAbsolute(name))
514
+ return;
515
+ found.add(name);
516
+ };
517
+ const seen = { jsx: false };
518
+ const visit = (node) => {
519
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
520
+ add(node.moduleSpecifier);
521
+ }
522
+ else if (ts.isExternalModuleReference(node)) {
523
+ add(node.expression);
524
+ }
525
+ else if (ts.isImportTypeNode(node)) {
526
+ const argument = node.argument;
527
+ if (ts.isLiteralTypeNode(argument))
528
+ add(argument.literal);
529
+ }
530
+ else if (ts.isCallExpression(node)) {
531
+ const [first] = node.arguments;
532
+ const dynamic = node.expression.kind === ts.SyntaxKind.ImportKeyword;
533
+ const required = ts.isIdentifier(node.expression) && node.expression.text === "require";
534
+ if (dynamic || required)
535
+ add(first);
536
+ }
537
+ else if (ts.isJsxElement(node) ||
538
+ ts.isJsxSelfClosingElement(node) ||
539
+ ts.isJsxFragment(node)) {
540
+ seen.jsx = true;
541
+ }
542
+ ts.forEachChild(node, visit);
543
+ };
544
+ visit(sourceFile);
545
+ if (seen.jsx) {
546
+ if (options.jsx === ts.JsxEmit.ReactJSX || options.jsx === ts.JsxEmit.ReactJSXDev) {
547
+ found.add(`${options.jsxImportSource ?? "react"}/jsx-runtime`);
548
+ }
549
+ else if (options.jsx === ts.JsxEmit.React && options.jsxFactory === undefined) {
550
+ found.add("react");
551
+ }
552
+ }
553
+ return [...found].sort();
554
+ }
555
+ /** Whether `imported` (as `importedModules` gives them) names `module` or one of its subpaths. */
556
+ export function importsModuleIn(imported, module) {
557
+ return imported.some((name) => name === module || name.startsWith(`${module}/`));
558
+ }
496
559
  /** Whether a project with these options checks with `strictNullChecks` (TypeScript 6: on unless turned off). */
497
560
  export function checksNulls(options) {
498
561
  return options.strictNullChecks ?? options.strict ?? true;
@@ -581,12 +644,28 @@ function readTsconfig(given) {
581
644
  * dominates a check of a small project, so one parse serves every later check.
582
645
  */
583
646
  const libraryCache = new Map();
647
+ /**
648
+ * Drops the parsed library files no program in `live` holds. After a program is let go (a check
649
+ * that builds one project at a time), its libraries would otherwise stay parsed and bound for the
650
+ * rest of the run, so the projects' libraries add up instead of the largest one counting.
651
+ */
652
+ function keepLibrariesOf(live) {
653
+ const used = new Set();
654
+ for (const program of live)
655
+ for (const sourceFile of program.getSourceFiles())
656
+ used.add(sourceFile);
657
+ for (const [key, cached] of libraryCache) {
658
+ if (!used.has(cached.sourceFile))
659
+ libraryCache.delete(key);
660
+ }
661
+ }
662
+ /** The library files parsed and kept for later programs (tests). */
663
+ export function cachedLibraryFiles() {
664
+ return [...libraryCache.values()].map((cached) => cached.sourceFile.fileName);
665
+ }
584
666
  const DEFAULT_LIB_DIRECTORY = toTypeScriptPath(path.dirname(ts.getDefaultLibFilePath({})));
585
667
  function isLibraryFile(fileName) {
586
- return isTypeScriptLib(fileName) || fileName.includes("/node_modules/");
587
- }
588
- function isTypeScriptLib(fileName) {
589
- return fileName.startsWith(DEFAULT_LIB_DIRECTORY);
668
+ return fileName.startsWith(DEFAULT_LIB_DIRECTORY) || fileName.includes("/node_modules/");
590
669
  }
591
670
  /**
592
671
  * What decides whether a cached source file still fits: how it is parsed. The options object
@@ -618,13 +697,7 @@ export function hostWithOverlays(options, overlays, cache,
618
697
  /** Serve a file that is not in `overlays` from `cache` without reading it from disk. */
619
698
  trustCache = false,
620
699
  /** Parse the JSDoc of TypeScript files too: a rule that is on reads it (`RuleMeta.needsJsDoc`). */
621
- jsDoc = false,
622
- /**
623
- * The files kept in the process-wide `libraryCache` rather than in `cache`. A package's own
624
- * JavaScript (`openPackageSource`) goes in `cache`, so it is freed with the package's program:
625
- * kept for the process, the packages a first run reads held over 500 MB on a large app.
626
- */
627
- shared = isLibraryFile) {
700
+ jsDoc = false) {
628
701
  const base = ts.createCompilerHost(options, true);
629
702
  return {
630
703
  ...base,
@@ -641,7 +714,7 @@ shared = isLibraryFile) {
641
714
  ? { ...requested, jsDocParsingMode: ts.JSDocParsingMode.ParseForTypeErrors }
642
715
  : requested;
643
716
  const optionsKey = parseKey(languageVersionOrOptions, options);
644
- const store = shared(fileName) ? libraryCache : cache;
717
+ const store = library ? libraryCache : cache;
645
718
  // By parse settings and name: two projects (a Vite app and its node config) read the same
646
719
  // library file with different settings, and one entry per name made each evict the other,
647
720
  // so every program parsed TypeScript's lib files and @types/react again.
@@ -693,7 +766,9 @@ function matcher(patterns) {
693
766
  return picomatch([...patterns], { dot: true });
694
767
  }
695
768
  /** The files of `parsed` that stateward checks and no earlier project has claimed. */
696
- function ownFileNames(parsed, config, cwd, claimed) {
769
+ function ownFileNames(parsed, config, cwd, claimed,
770
+ /** Whether a file is a test by the project's test-runner config (`test-runner.ts`). */
771
+ isTest) {
697
772
  const included = matcher(config.include);
698
773
  const excluded = matcher(config.exclude);
699
774
  const own = [];
@@ -702,7 +777,7 @@ function ownFileNames(parsed, config, cwd, claimed) {
702
777
  continue;
703
778
  const relative = path.relative(cwd, file).split(path.sep).join("/");
704
779
  const generated = file.endsWith(".d.ts") || file.includes("/node_modules/");
705
- if (!generated && included(relative) && !excluded(relative))
780
+ if (!generated && included(relative) && !excluded(relative) && !isTest(file))
706
781
  own.push(file);
707
782
  }
708
783
  return own;
@@ -724,6 +799,207 @@ function isArrayLike(checker, type) {
724
799
  return false;
725
800
  return (checker.getTypeOfSymbol(length).flags & ts.TypeFlags.NumberLike) !== 0;
726
801
  }
802
+ /** `TypeQueries.instanceClassesOf`: the classes an awaited type holds, through unions, arrays and wrappers. */
803
+ function instanceClassesOfType(checker, start, depth) {
804
+ const classes = [];
805
+ let any = false;
806
+ const seen = new Set();
807
+ const visit = (type, path, left, whole = true) => {
808
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
809
+ any = true;
810
+ return;
811
+ }
812
+ if (seen.has(type))
813
+ return;
814
+ seen.add(type);
815
+ const awaited = checker.getAwaitedType(type);
816
+ if (awaited !== undefined && awaited !== type) {
817
+ visit(awaited, path, left, whole);
818
+ return;
819
+ }
820
+ if (type.isUnionOrIntersection()) {
821
+ // A class in an intersection (`User & { orders: Order[] }`) is part of the value's type.
822
+ const part = whole && !type.isIntersection();
823
+ for (const member of type.types)
824
+ visit(member, path, left, part);
825
+ return;
826
+ }
827
+ if (!(type.flags & ts.TypeFlags.Object))
828
+ return;
829
+ if (checker.isArrayType(type) || checker.isTupleType(type)) {
830
+ if (!isTypeReference(type))
831
+ return;
832
+ for (const element of checker.getTypeArguments(type))
833
+ visit(element, `${path}[]`, left);
834
+ return;
835
+ }
836
+ const symbol = type.getSymbol();
837
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
838
+ if (symbol !== undefined && declaration !== undefined) {
839
+ // The instance side only: `typeof User` (the constructor) has the same symbol.
840
+ const instance = isTypeReference(type) ? type.target : type;
841
+ if (instance === checker.getDeclaredTypeOfSymbol(symbol)) {
842
+ classes.push({ name: symbol.getName(), declaration, path, whole });
843
+ }
844
+ return;
845
+ }
846
+ if (left <= 0 || type.getCallSignatures().length > 0)
847
+ return;
848
+ for (const property of checker.getPropertiesOfType(type)) {
849
+ const name = property.getName();
850
+ visit(checker.getTypeOfSymbol(property), path === "" ? name : `${path}.${name}`, left - 1);
851
+ }
852
+ };
853
+ visit(start, "", depth);
854
+ return { classes, any };
855
+ }
856
+ /** How many base types `genericBaseOf` reads above the type itself. */
857
+ const GENERIC_BASE_DEPTH = 8;
858
+ /**
859
+ * `TypeQueries.genericBaseOf`: the nearest generic base of a package, with its type arguments,
860
+ * through `this` and type parameters (their constraint) and the members of an intersection. A
861
+ * base written with the subclass's own type parameter (`class Base<T> extends Repository<T>`) is
862
+ * given the argument the value's type gives that parameter (`Base<User>` gives `User`).
863
+ */
864
+ function genericBaseOfType(checker, start, inPackage, names) {
865
+ const members = start.isUnion()
866
+ ? start.types.filter((one) => !(one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
867
+ : [start];
868
+ const [only] = members;
869
+ if (only === undefined || members.length > 1)
870
+ return undefined;
871
+ const argumentOf = (type) => {
872
+ const symbol = type.getSymbol();
873
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
874
+ const instance = isTypeReference(type) ? type.target : type;
875
+ return symbol !== undefined &&
876
+ declaration !== undefined &&
877
+ instance === checker.getDeclaredTypeOfSymbol(symbol)
878
+ ? { kind: "class", name: symbol.getName(), declaration }
879
+ : { kind: "other", text: stableTypeText(checker, type) };
880
+ };
881
+ const seen = new Set();
882
+ let level = [{ type: only, given: new Map() }];
883
+ for (let depth = 0; depth <= GENERIC_BASE_DEPTH && level.length > 0; depth++) {
884
+ const next = [];
885
+ for (const { type, given } of level) {
886
+ if (seen.has(type))
887
+ continue;
888
+ seen.add(type);
889
+ // `this` in a class's method, or a type parameter: read its constraint (the class itself).
890
+ if (type.flags & ts.TypeFlags.TypeParameter) {
891
+ const constraint = checker.getBaseConstraintOfType(type);
892
+ if (constraint !== undefined && constraint !== type)
893
+ next.push({ type: constraint, given });
894
+ continue;
895
+ }
896
+ // `getRepository(User).extend({ … })` gives `Repository<User> & { … }`: read each member.
897
+ if (type.isIntersection()) {
898
+ for (const member of type.types)
899
+ next.push({ type: member, given });
900
+ continue;
901
+ }
902
+ const written = isTypeReference(type) ? checker.getTypeArguments(type) : [];
903
+ const actual = written.map((one) => given.get(one) ?? one);
904
+ const symbol = type.getSymbol();
905
+ if (symbol !== undefined && names.has(symbol.getName()) && inPackage(symbol)) {
906
+ return { name: symbol.getName(), typeArguments: actual.map(argumentOf) };
907
+ }
908
+ const target = isTypeReference(type) ? type.target : type;
909
+ if (!target.isClassOrInterface())
910
+ continue;
911
+ const parameters = target.typeParameters ?? [];
912
+ const passed = new Map();
913
+ parameters.forEach((parameter, index) => {
914
+ const argument = actual[index];
915
+ if (argument !== undefined)
916
+ passed.set(parameter, argument);
917
+ });
918
+ for (const base of checker.getBaseTypes(target))
919
+ next.push({ type: base, given: passed });
920
+ }
921
+ level = next;
922
+ }
923
+ return undefined;
924
+ }
925
+ /**
926
+ * `TypeQueries.isOrExtends`: whether a type, or one of its base types up to `GENERIC_BASE_DEPTH`
927
+ * levels, is declared by one of `classes`. A class's own type (`typeof Store`) is read as its
928
+ * instances, `this` and a type parameter as their constraint, an intersection as its members.
929
+ */
930
+ function isOrExtendsType(checker, start, classes) {
931
+ const members = start.isUnion()
932
+ ? start.types.filter((one) => !(one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
933
+ : [start];
934
+ const [only] = members;
935
+ if (only === undefined || members.length > 1)
936
+ return false;
937
+ const seen = new Set();
938
+ let level = [only];
939
+ for (let depth = 0; depth <= GENERIC_BASE_DEPTH && level.length > 0; depth++) {
940
+ const next = [];
941
+ for (const type of level) {
942
+ if (seen.has(type))
943
+ continue;
944
+ seen.add(type);
945
+ if (type.flags & ts.TypeFlags.TypeParameter) {
946
+ const constraint = checker.getBaseConstraintOfType(type);
947
+ if (constraint !== undefined && constraint !== type)
948
+ next.push(constraint);
949
+ continue;
950
+ }
951
+ if (type.isIntersection()) {
952
+ next.push(...type.types);
953
+ continue;
954
+ }
955
+ const symbol = type.getSymbol();
956
+ if ((symbol?.declarations ?? []).some((declaration) => classes.has(declaration))) {
957
+ return true;
958
+ }
959
+ const target = isTypeReference(type) ? type.target : type;
960
+ if (target.isClassOrInterface()) {
961
+ next.push(...checker.getBaseTypes(target));
962
+ continue;
963
+ }
964
+ // A class read as a value (`Store.create()`): its static side, read as its instances.
965
+ if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Class) {
966
+ const instance = checker.getDeclaredTypeOfSymbol(symbol);
967
+ if (instance !== type)
968
+ next.push(instance);
969
+ }
970
+ }
971
+ level = next;
972
+ }
973
+ return false;
974
+ }
975
+ /** Whether a written type names a type parameter anywhere in it (`T`, `T[]`, `Promise<T>`, `T["id"]`). */
976
+ function holdsTypeParameter(checker, node) {
977
+ let found = false;
978
+ const visit = (current) => {
979
+ if (found)
980
+ return;
981
+ if (ts.isTypeReferenceNode(current) &&
982
+ checker.getTypeFromTypeNode(current).flags & ts.TypeFlags.TypeParameter) {
983
+ found = true;
984
+ return;
985
+ }
986
+ ts.forEachChild(current, visit);
987
+ };
988
+ visit(node);
989
+ return found;
990
+ }
991
+ /**
992
+ * Whether a declaration is in the global scope: in a `declare global` block, or in a file that is
993
+ * not a module (TypeScript's lib, a script `.d.ts`).
994
+ */
995
+ function isGlobalDeclaration(declaration) {
996
+ for (let node = declaration.parent;; node = node.parent) {
997
+ if (ts.isSourceFile(node))
998
+ return !ts.isExternalModule(node);
999
+ if (ts.isModuleDeclaration(node))
1000
+ return (node.flags & ts.NodeFlags.GlobalAugmentation) !== 0;
1001
+ }
1002
+ }
727
1003
  function compareLabels(a, b) {
728
1004
  if (a.label < b.label)
729
1005
  return -1;
@@ -773,6 +1049,22 @@ function isAnonymousObject(type) {
773
1049
  typeof type.objectFlags === "number" &&
774
1050
  (type.objectFlags & ts.ObjectFlags.Anonymous) !== 0);
775
1051
  }
1052
+ /** Which of TypeScript's own types `type` is, from its flags (`TypeQueries.builtinTypeOf`). */
1053
+ function builtinOf(type) {
1054
+ if ((type.flags & ts.TypeFlags.Any) !== 0)
1055
+ return "any";
1056
+ if ((type.flags & ts.TypeFlags.Unknown) !== 0)
1057
+ return "unknown";
1058
+ if ((type.flags & ts.TypeFlags.Never) !== 0)
1059
+ return "never";
1060
+ if ((type.flags & ts.TypeFlags.Void) !== 0)
1061
+ return "void";
1062
+ if ((type.flags & ts.TypeFlags.Undefined) !== 0)
1063
+ return "undefined";
1064
+ if ((type.flags & ts.TypeFlags.Null) !== 0)
1065
+ return "null";
1066
+ return undefined;
1067
+ }
776
1068
  function widened(checker, type) {
777
1069
  return type.isTypeParameter() ? checker.getBaseConstraintOfType(type) : type;
778
1070
  }
@@ -815,6 +1107,26 @@ function isPromiseType(checker, type) {
815
1107
  const awaited = checker.getAwaitedType(type);
816
1108
  return awaited !== undefined && awaited !== type;
817
1109
  }
1110
+ /** A type that stands for another one not known where it is declared (`T`, `T[K]`, `T extends U ? X : Y`). */
1111
+ const STANDS_FOR_ANOTHER = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.InstantiableNonPrimitive;
1112
+ /**
1113
+ * Whether a value of the type can be a promise: a promise-like type, `any`, `unknown`, a type
1114
+ * parameter or a type built on one, a type the global `Promise` is assignable to (`object`,
1115
+ * `{}`), or a union or an intersection with such a member.
1116
+ */
1117
+ function mayBePromiseType(checker, type) {
1118
+ if (type.flags & STANDS_FOR_ANOTHER)
1119
+ return true;
1120
+ if (type.isUnion())
1121
+ return type.types.some((part) => mayBePromiseType(checker, part));
1122
+ if (type.isIntersection())
1123
+ return type.types.some((part) => mayBePromiseType(checker, part));
1124
+ if (isPromiseType(checker, type))
1125
+ return true;
1126
+ const promise = checker.resolveName("Promise", undefined, ts.SymbolFlags.Type, false);
1127
+ return (promise !== undefined &&
1128
+ checker.isTypeAssignableTo(checker.getDeclaredTypeOfSymbol(promise), type));
1129
+ }
818
1130
  const NULLISH = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
819
1131
  /** The property a stated guarantee is written in by 1.1.0 (`__guarantee?: "owned"`). */
820
1132
  const GUARANTEE_PROPERTY = "__guarantee";
@@ -879,7 +1191,7 @@ function definesMarker(type) {
879
1191
  /**
880
1192
  * The declarations of a file whose written type states a guarantee, in source order
881
1193
  * (`TypeQueries.statedDeclarationsIn`). A function's return type is not one: what it states
882
- * (`Release<…>`) reaches the code through each call, which a rule reads there.
1194
+ * (`Owned<…>`) reaches the code through each call, which a rule reads there.
883
1195
  */
884
1196
  function statedDeclarationsOf(checker, sourceFile) {
885
1197
  const found = [];
@@ -1100,20 +1412,21 @@ function guaranteesOfType(checker, found) {
1100
1412
  return [...new Set(shared ?? [])].sort();
1101
1413
  }
1102
1414
  /**
1103
- * The literals of the `"__guarantee:<name>"` property of `type` (its first member that states it),
1104
- * without the `undefined` the optional property adds; undefined when no member states it.
1415
+ * The literals of the optional property `property` of `type` (its first member that states it),
1416
+ * without the `undefined` the optional property adds; undefined when no member states it. A
1417
+ * guarantee's is `"__guarantee:<name>"`.
1105
1418
  */
1106
- function guaranteeValuesOfType(checker, found, name) {
1419
+ function markerValuesOfType(checker, found, property) {
1107
1420
  const type = widened(checker, found);
1108
1421
  if (type === undefined)
1109
1422
  return undefined;
1110
1423
  for (const member of type.isUnion() ? type.types : [type]) {
1111
1424
  if (member.flags & NULLISH)
1112
1425
  continue;
1113
- const property = checker.getPropertyOfType(member, `${GUARANTEE_PREFIX}${name}`);
1114
- if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
1426
+ const marker = checker.getPropertyOfType(member, property);
1427
+ if (marker === undefined || !(marker.flags & ts.SymbolFlags.Optional))
1115
1428
  continue;
1116
- const value = checker.getTypeOfSymbol(property);
1429
+ const value = checker.getTypeOfSymbol(marker);
1117
1430
  const literals = [];
1118
1431
  for (const part of value.isUnion() ? value.types : [value]) {
1119
1432
  if (part.flags & ts.TypeFlags.Undefined)
@@ -1499,6 +1812,147 @@ function signalParameter(checker, call) {
1499
1812
  }
1500
1813
  return undefined;
1501
1814
  }
1815
+ /** As `TypeQueries.parameterTakesUnknown`. */
1816
+ function takesUnknown(checker, call, index) {
1817
+ if (call.arguments.slice(0, index + 1).some(ts.isSpreadElement))
1818
+ return false;
1819
+ const declaration = checker.getResolvedSignature(call)?.getDeclaration();
1820
+ if (declaration === undefined || ts.isJSDocSignature(declaration))
1821
+ return false;
1822
+ const parameter = declaration.parameters[index];
1823
+ if (parameter === undefined || parameter.dotDotDotToken !== undefined)
1824
+ return false;
1825
+ // The declared type, before the call's type arguments replace a type parameter.
1826
+ const type = checker.getTypeAtLocation(parameter);
1827
+ if (type.flags & ts.TypeFlags.Unknown)
1828
+ return true;
1829
+ if (!type.isTypeParameter())
1830
+ return false;
1831
+ // Only the function's own type parameter: a class's (`Map<K, V>.set`) is fixed by the instance.
1832
+ const owner = type.getSymbol()?.declarations?.[0]?.parent;
1833
+ if (owner !== declaration)
1834
+ return false;
1835
+ const constraint = type.getConstraint();
1836
+ return constraint === undefined || (constraint.flags & ts.TypeFlags.Unknown) !== 0;
1837
+ }
1838
+ /** Whether a declaration is, or is written inside, a type, interface or class with type parameters. */
1839
+ function insideGeneric(declaration) {
1840
+ for (let at = declaration; !ts.isSourceFile(at); at = at.parent) {
1841
+ if ((ts.isTypeAliasDeclaration(at) || ts.isInterfaceDeclaration(at) || ts.isClassLike(at)) &&
1842
+ (at.typeParameters ?? []).length > 0) {
1843
+ return true;
1844
+ }
1845
+ }
1846
+ return false;
1847
+ }
1848
+ /** How deep `typeShape` follows nested object types before it gives up. */
1849
+ const SHAPE_DEPTH = 8;
1850
+ /** As `TypeQueries.typeShapeOf`, for a type; `inside` holds the object types being read. */
1851
+ function typeShape(isPlatformFile, checker, type, inside) {
1852
+ if (inside.length > SHAPE_DEPTH)
1853
+ return undefined;
1854
+ if (type.flags & ts.TypeFlags.EnumLike)
1855
+ return undefined;
1856
+ if (type.isUnion()) {
1857
+ const members = [];
1858
+ let booleans = 0;
1859
+ for (const member of type.types) {
1860
+ if (member.flags & ts.TypeFlags.BooleanLiteral) {
1861
+ booleans += 1;
1862
+ continue;
1863
+ }
1864
+ const shape = typeShape(isPlatformFile, checker, member, inside);
1865
+ if (shape === undefined)
1866
+ return undefined;
1867
+ members.push(shape);
1868
+ }
1869
+ // `boolean` is `true | false` to the checker; a check tests it with `typeof`.
1870
+ if (booleans === 2)
1871
+ members.push({ kind: "primitive", name: "boolean" });
1872
+ else if (booleans === 1) {
1873
+ const literal = type.types.find((member) => member.flags & ts.TypeFlags.BooleanLiteral);
1874
+ const shape = literal === undefined ? undefined : typeShape(isPlatformFile, checker, literal, inside);
1875
+ if (shape === undefined)
1876
+ return undefined;
1877
+ members.push(shape);
1878
+ }
1879
+ return members.length === 1 && members[0] !== undefined
1880
+ ? members[0]
1881
+ : { kind: "union", members };
1882
+ }
1883
+ if (type.flags & ts.TypeFlags.Boolean)
1884
+ return { kind: "primitive", name: "boolean" };
1885
+ const literal = literalOf(checker, type);
1886
+ if (literal !== undefined && !(type.flags & ts.TypeFlags.Intersection)) {
1887
+ return { kind: "literal", literal };
1888
+ }
1889
+ if (type.flags & ts.TypeFlags.String)
1890
+ return { kind: "primitive", name: "string" };
1891
+ if (type.flags & ts.TypeFlags.Number)
1892
+ return { kind: "primitive", name: "number" };
1893
+ if (type.flags & ts.TypeFlags.BigInt)
1894
+ return { kind: "primitive", name: "bigint" };
1895
+ if (!(type.flags & ts.TypeFlags.Object) || type.isIntersection())
1896
+ return undefined;
1897
+ if (checker.isArrayType(type) && isTypeReference(type)) {
1898
+ const [element] = checker.getTypeArguments(type);
1899
+ const shape = element === undefined
1900
+ ? undefined
1901
+ : typeShape(isPlatformFile, checker, element, [...inside, type]);
1902
+ return shape === undefined ? undefined : { kind: "array", element: shape };
1903
+ }
1904
+ if (checker.isTupleType(type))
1905
+ return undefined;
1906
+ if (isTypeReference(type) && checker.getTypeArguments(type).length > 0)
1907
+ return undefined;
1908
+ if ((type.aliasTypeArguments ?? []).length > 0)
1909
+ return undefined;
1910
+ if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) {
1911
+ return undefined;
1912
+ }
1913
+ if (checker.getIndexInfosOfType(type).length > 0)
1914
+ return undefined;
1915
+ const symbol = type.getSymbol();
1916
+ const declarations = symbol?.declarations ?? [];
1917
+ if (declarations.some((one) => isPlatformFile(one.getSourceFile()))) {
1918
+ return undefined;
1919
+ }
1920
+ const named = type.aliasSymbol?.getName() ?? symbol?.getName();
1921
+ const name = named === undefined || named.startsWith("__") ? undefined : named;
1922
+ // The type's identity: two types of one name (`billing.Address`, `shipping.Address`) differ.
1923
+ const first = declarations[0];
1924
+ const id = first === undefined
1925
+ ? stableTypeText(checker, type, "whole")
1926
+ : `${first.getSourceFile().fileName}:${String(first.pos)}`;
1927
+ if (inside.includes(type)) {
1928
+ return name === undefined ? undefined : { kind: "recursive", id, name };
1929
+ }
1930
+ const hidden = declarations.some((one) => ts.isClassLike(one) &&
1931
+ one.members.some((member) => (member.name !== undefined && ts.isPrivateIdentifier(member.name)) ||
1932
+ (ts.getCombinedModifierFlags(member) &
1933
+ (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) !==
1934
+ 0));
1935
+ if (hidden || declarations.some(insideGeneric))
1936
+ return undefined;
1937
+ const properties = [];
1938
+ for (const property of checker.getPropertiesOfType(type)) {
1939
+ if (property.flags & (ts.SymbolFlags.Method | ts.SymbolFlags.Accessor))
1940
+ return undefined;
1941
+ const shape = typeShape(isPlatformFile, checker, checker.getTypeOfSymbol(property), [
1942
+ ...inside,
1943
+ type,
1944
+ ]);
1945
+ if (shape === undefined)
1946
+ return undefined;
1947
+ properties.push({
1948
+ name: property.getName(),
1949
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
1950
+ shape,
1951
+ });
1952
+ }
1953
+ const text = name ?? stableTypeText(checker, type, "whole");
1954
+ return { kind: "object", id, name, text: text.replace(/\s+/g, " ").trim(), properties };
1955
+ }
1502
1956
  function withoutNullish(type) {
1503
1957
  const nothing = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
1504
1958
  return (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & nothing));
@@ -1682,7 +2136,7 @@ function tagText(tag, sourceFile) {
1682
2136
  return text.length <= REFERENCE_TEXT_MAX ? text : `${text.slice(0, REFERENCE_TEXT_MAX - 1)}…`;
1683
2137
  }
1684
2138
  function shortText(node, sourceFile) {
1685
- const text = node.getText(sourceFile).replace(/\s+/g, " ").trim();
2139
+ const text = codeOnOneLine(node.getText(sourceFile));
1686
2140
  return text.length <= REFERENCE_TEXT_MAX ? text : `${text.slice(0, REFERENCE_TEXT_MAX - 1)}…`;
1687
2141
  }
1688
2142
  function isWrapperExpression(node) {
@@ -1881,7 +2335,7 @@ function createLedgerScan(program, typeChecker, isOwn, refOfSymbol) {
1881
2335
  const checker = typeChecker();
1882
2336
  return guaranteesOfType(checker, checker.getTypeFromTypeNode(type)).filter((one) => wanted.has(one));
1883
2337
  };
1884
- /** A rest parameter states a trait by its elements: `...stops: Release<…>[]`. */
2338
+ /** A rest parameter states a trait by its elements: `...stops: Owned<…>[]`. */
1885
2339
  const restTraits = (type, wanted) => {
1886
2340
  const checker = typeChecker();
1887
2341
  const element = checker.getIndexTypeOfType(checker.getTypeFromTypeNode(type), ts.IndexKind.Number);
@@ -3473,10 +3927,24 @@ function onlyPrimitives(checker, found, depth) {
3473
3927
  * TS2366, TS2355, TS2534 and TS7030 (`TypeQueries.reportsReachableEnd`).
3474
3928
  */
3475
3929
  const REACHABLE_END_CODES = new Set([2366, 2355, 2534, 7030]);
3476
- /** A file of the platform: TypeScript's own lib, or Node's types. */
3477
- function isPlatformSourceFile(program, file) {
3478
- return (program.isSourceFileDefaultLibrary(file) ||
3479
- /[\\/]node_modules[\\/]@types[\\/]node[\\/]/.test(file.fileName));
3930
+ /**
3931
+ * The platform's packages every project has: Node's types. TypeScript's own lib is the platform
3932
+ * too; the config's `platform` adds more (`bun-types`, `@cloudflare/workers-types`).
3933
+ */
3934
+ export const PLATFORM_PACKAGES = ["@types/node"];
3935
+ /** `@types/node` as a path pattern: `/node_modules/@types/node/`, either slash. */
3936
+ function packagePathPattern(name) {
3937
+ const escaped = name.split("/").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3938
+ return `[\\\\/]node_modules[\\\\/]${escaped.join("[\\\\/]")}[\\\\/]`;
3939
+ }
3940
+ /**
3941
+ * The test of whether a file is of the platform: TypeScript's own lib, or a file of one of the
3942
+ * platform's packages (`PLATFORM_PACKAGES` and the config's `platform`).
3943
+ */
3944
+ function platformFiles(program, extra) {
3945
+ const names = [...new Set([...PLATFORM_PACKAGES, ...extra])];
3946
+ const pattern = new RegExp(names.map(packagePathPattern).join("|"));
3947
+ return (file) => program.isSourceFileDefaultLibrary(file) || pattern.test(file.fileName);
3480
3948
  }
3481
3949
  /** Properties of the platform's types that are plain data on the closed list, as `<type>.<name>`. */
3482
3950
  const PLATFORM_PROPERTIES = new Set([
@@ -3511,13 +3979,309 @@ function isNumberType(type) {
3511
3979
  return type.types.some(isNumberType);
3512
3980
  return (type.flags & ts.TypeFlags.NumberLike) !== 0;
3513
3981
  }
3982
+ const OBJECT = { kind: "global", name: "Object" };
3983
+ const UNDEFINED = { kind: "undefined" };
3984
+ /** The type nodes whose constructor is fixed by their kind (`number` is `Number`). */
3985
+ const KEYWORD_METADATA = new Map([
3986
+ [ts.SyntaxKind.VoidKeyword, UNDEFINED],
3987
+ [ts.SyntaxKind.UndefinedKeyword, UNDEFINED],
3988
+ [ts.SyntaxKind.NeverKeyword, UNDEFINED],
3989
+ [ts.SyntaxKind.FunctionType, { kind: "global", name: "Function" }],
3990
+ [ts.SyntaxKind.ConstructorType, { kind: "global", name: "Function" }],
3991
+ [ts.SyntaxKind.ArrayType, { kind: "global", name: "Array" }],
3992
+ [ts.SyntaxKind.TupleType, { kind: "global", name: "Array" }],
3993
+ [ts.SyntaxKind.BooleanKeyword, { kind: "global", name: "Boolean" }],
3994
+ [ts.SyntaxKind.TemplateLiteralType, { kind: "global", name: "String" }],
3995
+ [ts.SyntaxKind.StringKeyword, { kind: "global", name: "String" }],
3996
+ [ts.SyntaxKind.NumberKeyword, { kind: "global", name: "Number" }],
3997
+ [ts.SyntaxKind.BigIntKeyword, { kind: "global", name: "BigInt" }],
3998
+ [ts.SyntaxKind.SymbolKeyword, { kind: "global", name: "Symbol" }],
3999
+ ]);
4000
+ function global(name) {
4001
+ return { kind: "global", name };
4002
+ }
4003
+ function sameMetadata(a, b) {
4004
+ switch (a.kind) {
4005
+ case "global":
4006
+ return b.kind === "global" && a.name === b.name;
4007
+ case "undefined":
4008
+ return b.kind === "undefined";
4009
+ case "class":
4010
+ return b.kind === "class" && a.name === b.name;
4011
+ case "unresolved":
4012
+ return b.kind === "unresolved" && a.name === b.name;
4013
+ default: {
4014
+ const unreachable = a;
4015
+ return unreachable;
4016
+ }
4017
+ }
4018
+ }
4019
+ /** The compiler's `serializeTypeNode`, giving the constructor instead of an expression. */
4020
+ function serializedTypeNode(context, given) {
4021
+ if (given === undefined)
4022
+ return OBJECT;
4023
+ let node = given;
4024
+ while (ts.isParenthesizedTypeNode(node))
4025
+ node = node.type;
4026
+ const keyword = KEYWORD_METADATA.get(node.kind);
4027
+ if (keyword !== undefined)
4028
+ return keyword;
4029
+ if (ts.isTypePredicateNode(node)) {
4030
+ return node.assertsModifier === undefined ? global("Boolean") : UNDEFINED;
4031
+ }
4032
+ if (ts.isLiteralTypeNode(node))
4033
+ return serializedLiteral(node.literal);
4034
+ if (ts.isTypeReferenceNode(node))
4035
+ return serializedReference(context, node.typeName);
4036
+ if (ts.isUnionTypeNode(node))
4037
+ return serializedMembers(context, node.types, false);
4038
+ if (ts.isIntersectionTypeNode(node))
4039
+ return serializedMembers(context, node.types, true);
4040
+ if (ts.isConditionalTypeNode(node)) {
4041
+ return serializedMembers(context, [node.trueType, node.falseType], false);
4042
+ }
4043
+ if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
4044
+ return serializedTypeNode(context, node.type);
4045
+ }
4046
+ return OBJECT;
4047
+ }
4048
+ function serializedLiteral(literal) {
4049
+ if (ts.isPrefixUnaryExpression(literal)) {
4050
+ return ts.isBigIntLiteral(literal.operand) ? global("BigInt") : global("Number");
4051
+ }
4052
+ if (ts.isStringLiteral(literal) || ts.isNoSubstitutionTemplateLiteral(literal)) {
4053
+ return global("String");
4054
+ }
4055
+ if (ts.isNumericLiteral(literal))
4056
+ return global("Number");
4057
+ if (ts.isBigIntLiteral(literal))
4058
+ return global("BigInt");
4059
+ if (literal.kind === ts.SyntaxKind.TrueKeyword || literal.kind === ts.SyntaxKind.FalseKeyword) {
4060
+ return global("Boolean");
4061
+ }
4062
+ return UNDEFINED;
4063
+ }
4064
+ /** The compiler's `serializeUnionOrIntersectionConstituents`. */
4065
+ function serializedMembers(context, types, isIntersection) {
4066
+ let serialized;
4067
+ for (const written of types) {
4068
+ let member = written;
4069
+ while (ts.isParenthesizedTypeNode(member))
4070
+ member = member.type;
4071
+ if (member.kind === ts.SyntaxKind.NeverKeyword) {
4072
+ if (isIntersection)
4073
+ return UNDEFINED;
4074
+ continue;
4075
+ }
4076
+ if (member.kind === ts.SyntaxKind.UnknownKeyword) {
4077
+ if (!isIntersection)
4078
+ return OBJECT;
4079
+ continue;
4080
+ }
4081
+ if (member.kind === ts.SyntaxKind.AnyKeyword)
4082
+ return OBJECT;
4083
+ const nullish = member.kind === ts.SyntaxKind.UndefinedKeyword ||
4084
+ (ts.isLiteralTypeNode(member) && member.literal.kind === ts.SyntaxKind.NullKeyword);
4085
+ if (nullish && !context.keepsNullish)
4086
+ continue;
4087
+ const one = serializedTypeNode(context, member);
4088
+ if (one.kind === "global" && one.name === "Object")
4089
+ return one;
4090
+ if (serialized === undefined)
4091
+ serialized = one;
4092
+ else if (!sameMetadata(serialized, one))
4093
+ return OBJECT;
4094
+ }
4095
+ return serialized ?? UNDEFINED;
4096
+ }
4097
+ /** An import or export that brings only a type (`import type`, `import { type X }`). */
4098
+ function isTypeOnlyAlias(symbol) {
4099
+ const declarations = symbol.declarations ?? [];
4100
+ return declarations.length > 0 && declarations.every(ts.isTypeOnlyImportOrExportDeclaration);
4101
+ }
4102
+ /** The compiler's `getTypeReferenceSerializationKind` and `serializeTypeReferenceNode`. */
4103
+ function serializedReference(context, typeName) {
4104
+ const { checker } = context;
4105
+ const name = typeName.getText();
4106
+ const resolve = (symbol) => symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias
4107
+ ? checker.getAliasedSymbol(symbol)
4108
+ : symbol;
4109
+ // The name as a value (what the emitted code would reach at run time) and as a type.
4110
+ const written = ts.isIdentifier(typeName)
4111
+ ? checker.resolveName(typeName.text, typeName, ts.SymbolFlags.Value, false)
4112
+ : checker.getSymbolAtLocation(typeName);
4113
+ const valueSymbol = written !== undefined && written.flags & (ts.SymbolFlags.Value | ts.SymbolFlags.Alias)
4114
+ ? written
4115
+ : undefined;
4116
+ const typeSymbol = resolve(checker.getSymbolAtLocation(typeName));
4117
+ const value = resolve(valueSymbol);
4118
+ const isTypeOnly = valueSymbol !== undefined && isTypeOnlyAlias(valueSymbol);
4119
+ if (value !== undefined && value === typeSymbol) {
4120
+ const promise = checker.resolveName("Promise", undefined, ts.SymbolFlags.Value, false);
4121
+ if (promise !== undefined && value === promise)
4122
+ return global("Promise");
4123
+ const constructorType = checker.getTypeOfSymbol(value);
4124
+ if (constructorType.getConstructSignatures().length > 0) {
4125
+ return isTypeOnly
4126
+ ? global("Function")
4127
+ : { kind: "class", name, symbol: context.refOf(value) };
4128
+ }
4129
+ }
4130
+ // A name that does not resolve gives no symbol, or the checker's unknown symbol (no declarations).
4131
+ if (typeSymbol === undefined || (typeSymbol.declarations ?? []).length === 0) {
4132
+ return isTypeOnly ? OBJECT : { kind: "unresolved", name };
4133
+ }
4134
+ const type = checker.getDeclaredTypeOfSymbol(typeSymbol);
4135
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
4136
+ return OBJECT;
4137
+ const isKind = (flags, target) => (type.flags & flags) !== 0 || checker.isTypeAssignableTo(type, target);
4138
+ if (isKind(ts.TypeFlags.Void, checker.getVoidType()) ||
4139
+ isKind(ts.TypeFlags.Undefined, checker.getUndefinedType()) ||
4140
+ isKind(ts.TypeFlags.Null, checker.getNullType()) ||
4141
+ isKind(ts.TypeFlags.Never, checker.getNeverType())) {
4142
+ return UNDEFINED;
4143
+ }
4144
+ if (isKind(ts.TypeFlags.BooleanLike, checker.getBooleanType()))
4145
+ return global("Boolean");
4146
+ if (isKind(ts.TypeFlags.NumberLike, checker.getNumberType()))
4147
+ return global("Number");
4148
+ if (isKind(ts.TypeFlags.BigIntLike, checker.getBigIntType()))
4149
+ return global("BigInt");
4150
+ if (isKind(ts.TypeFlags.StringLike, checker.getStringType()))
4151
+ return global("String");
4152
+ if (checker.isTupleType(type))
4153
+ return global("Array");
4154
+ if (isKind(ts.TypeFlags.ESSymbolLike, checker.getESSymbolType()))
4155
+ return global("Symbol");
4156
+ if (type.flags & ts.TypeFlags.Object && type.getCallSignatures().length > 0) {
4157
+ return global("Function");
4158
+ }
4159
+ if (checker.isArrayType(type))
4160
+ return global("Array");
4161
+ return OBJECT;
4162
+ }
4163
+ /** The type node TypeScript serializes for a parameter: a rest parameter's element type. */
4164
+ function metadataTypeNode(node) {
4165
+ if (!ts.isParameter(node) || node.dotDotDotToken === undefined)
4166
+ return node.type;
4167
+ const type = node.type;
4168
+ if (type === undefined)
4169
+ return undefined;
4170
+ if (ts.isArrayTypeNode(type))
4171
+ return type.elementType;
4172
+ if (ts.isTypeReferenceNode(type) && type.typeArguments?.length === 1) {
4173
+ return type.typeArguments[0];
4174
+ }
4175
+ return undefined;
4176
+ }
4177
+ function decoratorMetadata(options, context, node) {
4178
+ if (options.experimentalDecorators !== true || options.emitDecoratorMetadata !== true) {
4179
+ return { kind: "not-emitted" };
4180
+ }
4181
+ const typeNode = metadataTypeNode(node);
4182
+ return {
4183
+ kind: "emitted",
4184
+ type: serializedTypeNode({ ...context, keepsNullish: checksNulls(options) }, typeNode),
4185
+ withoutNullish: serializedTypeNode({ ...context, keepsNullish: false }, typeNode),
4186
+ };
4187
+ }
4188
+ /**
4189
+ * The first declaration of `symbol`. A symbol the checker made (a property of a union of object
4190
+ * types) lists its declarations in the order of the union's members, which follows what the
4191
+ * checker created first (see `stableTypeText`): its first by place (file, then offset) instead.
4192
+ */
4193
+ function placedFirst(symbol) {
4194
+ const all = symbol.declarations ?? [];
4195
+ if ((symbol.flags & ts.SymbolFlags.Transient) === 0 || all.length < 2)
4196
+ return all[0];
4197
+ return all.reduce((first, one) => {
4198
+ const a = first.getSourceFile().fileName;
4199
+ const b = one.getSourceFile().fileName;
4200
+ return b < a || (b === a && one.pos < first.pos) ? one : first;
4201
+ });
4202
+ }
4203
+ /** `typeToString`'s own limit: printed text this long or longer ends in "...". */
4204
+ const TYPE_TEXT_LIMIT = 320;
4205
+ /** The file a printed type node is printed against: it has no text of its own to read. */
4206
+ const PRINTED_TYPE_FILE = ts.createSourceFile("type.ts", "", ts.ScriptTarget.Latest);
4207
+ const typePrinter = ts.createPrinter({ removeComments: true });
4208
+ /** Where a union member goes: `null`, then `undefined`, after every other member. */
4209
+ function nullishRank(node) {
4210
+ if (ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.NullKeyword)
4211
+ return 1;
4212
+ return node.kind === ts.SyntaxKind.UndefinedKeyword ? 2 : 0;
4213
+ }
4214
+ function printedType(node) {
4215
+ return typePrinter.printNode(ts.EmitHint.Unspecified, node, PRINTED_TYPE_FILE);
4216
+ }
4217
+ /** Every union in `node`, at any depth, with its members in `stableTypeText`'s order. */
4218
+ function withSortedUnions(node) {
4219
+ const sorting = (context) => {
4220
+ const visit = (child) => {
4221
+ const inner = ts.visitEachChild(child, visit, context);
4222
+ if (!ts.isUnionTypeNode(inner))
4223
+ return inner;
4224
+ const keyed = inner.types.map((member) => ({
4225
+ member,
4226
+ rank: nullishRank(member),
4227
+ text: printedType(member),
4228
+ }));
4229
+ keyed.sort((a, b) => a.rank - b.rank || (a.text < b.text ? -1 : a.text > b.text ? 1 : 0));
4230
+ return context.factory.updateUnionTypeNode(inner, context.factory.createNodeArray(keyed.map(({ member }) => member)));
4231
+ };
4232
+ return visit;
4233
+ };
4234
+ const result = ts.transform(node, [sorting]);
4235
+ const [sorted] = result.transformed;
4236
+ result.dispose();
4237
+ return sorted ?? node;
4238
+ }
4239
+ /**
4240
+ * A type as `typeToString` prints it, except that the members of every union are in a fixed
4241
+ * order: by their own printed text, with `null` and `undefined` last. TypeScript prints a union's
4242
+ * members in the order their types were created, which follows what the checker was asked before:
4243
+ * the same code printed `J | I` after another file mentioned `J` first, and `I | J` with a new
4244
+ * checker. Text that rules show must be the same for the same code (SW5).
4245
+ *
4246
+ * The type is built whole and cut at the end: TypeScript's own shortening drops members past a
4247
+ * length, and which ones depends on that same order.
4248
+ */
4249
+ function stableTypeText(checker, type,
4250
+ /** `whole`: never cut (`TypeFormatFlags.NoTruncation`), for text a fix writes into the code. */
4251
+ length = "cut") {
4252
+ const node = checker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.AllowUniqueESSymbolType |
4253
+ ts.NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope |
4254
+ ts.NodeBuilderFlags.IgnoreErrors |
4255
+ ts.NodeBuilderFlags.NoTruncation);
4256
+ if (node === undefined)
4257
+ return checker.typeToString(type);
4258
+ const text = printedType(withSortedUnions(node));
4259
+ return length === "cut" && text.length >= TYPE_TEXT_LIMIT
4260
+ ? `${text.slice(0, TYPE_TEXT_LIMIT - 3)}...`
4261
+ : text;
4262
+ }
3514
4263
  export function createTypeQueries(program, own,
3515
4264
  /** The project folder qualified ids are relative to. */
3516
- root, packageOf, isEntry, dependenciesOf) {
4265
+ root, packageOf, isEntry, dependenciesOf,
4266
+ /** Packages the config adds to the platform (`Config.platform`). */
4267
+ platform = []) {
4268
+ const isPlatformFile = platformFiles(program, platform);
4269
+ // Module names resolve as from the project's tsconfig (a file there need not exist).
4270
+ const { configFilePath } = program.getCompilerOptions();
4271
+ const resolveFrom = path.join(typeof configFilePath === "string" ? path.dirname(configFilePath) : root, "__stateward_types__.ts");
3517
4272
  // The only place in the codebase that reaches the type checker. Created on the first question:
3518
4273
  // a run whose results all come from the cache never builds one.
3519
4274
  let created;
3520
4275
  const typeChecker = () => (created ??= program.getTypeChecker());
4276
+ const factNames = createFactNames(typeChecker, program, packageOf, resolveFrom, own);
4277
+ const factModuleOf = createFactModules({
4278
+ checker: typeChecker,
4279
+ program,
4280
+ names: factNames,
4281
+ own,
4282
+ isPlatformFile,
4283
+ packageOf,
4284
+ });
3521
4285
  const declarations = new Map();
3522
4286
  const declaredTraits = new Map();
3523
4287
  let anyMarker;
@@ -3533,7 +4297,7 @@ root, packageOf, isEntry, dependenciesOf) {
3533
4297
  const refsByNode = new WeakMap();
3534
4298
  const refsBySymbol = new WeakMap();
3535
4299
  const refOfSymbol = (symbol) => {
3536
- const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
4300
+ const declaration = symbol.valueDeclaration ?? placedFirst(symbol);
3537
4301
  if (declaration === undefined)
3538
4302
  return undefined;
3539
4303
  const id = `${idFileName(declaration.getSourceFile().fileName)}#${declarationPath(declaration)}`;
@@ -3567,7 +4331,7 @@ root, packageOf, isEntry, dependenciesOf) {
3567
4331
  const declarations = symbol?.declarations ?? [];
3568
4332
  if (symbol !== undefined &&
3569
4333
  declarations.length > 0 &&
3570
- declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile()))) {
4334
+ declarations.every((one) => isPlatformFile(one.getSourceFile()))) {
3571
4335
  found.add(symbol);
3572
4336
  }
3573
4337
  }
@@ -3607,7 +4371,7 @@ root, packageOf, isEntry, dependenciesOf) {
3607
4371
  const declarations = symbol?.declarations ?? [];
3608
4372
  if (symbol === undefined ||
3609
4373
  declarations.length === 0 ||
3610
- !declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile())) ||
4374
+ !declarations.every((one) => isPlatformFile(one.getSourceFile())) ||
3611
4375
  platformExtended().has(symbol)) {
3612
4376
  return undefined;
3613
4377
  }
@@ -3633,7 +4397,7 @@ root, packageOf, isEntry, dependenciesOf) {
3633
4397
  }
3634
4398
  if (declarations.some((one) => ts.isGetAccessor(one) || ts.isSetAccessor(one)))
3635
4399
  return false;
3636
- if (declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile()))) {
4400
+ if (declarations.every((one) => isPlatformFile(one.getSourceFile()))) {
3637
4401
  const owner = platformNameOf(receiver);
3638
4402
  return (owner !== undefined &&
3639
4403
  (PLATFORM_CONSTANTS.has(owner) || PLATFORM_PROPERTIES.has(`${owner}.${property.getName()}`)));
@@ -3695,6 +4459,23 @@ root, packageOf, isEntry, dependenciesOf) {
3695
4459
  },
3696
4460
  isOwnFile: (file) => own.has(toTypeScriptPath(file)),
3697
4461
  packageOf: (file) => packageOf(toTypeScriptPath(file)),
4462
+ factTarget: (module, name) => factNames.target(module, name),
4463
+ factNames: (module) => factNames.names(module),
4464
+ factNameOf: (module, declaration) => factNames.nameOf(module, declaration),
4465
+ factModuleOf,
4466
+ exportedClassOf(module, name) {
4467
+ const exported = factNames
4468
+ .modulesNamed(module)
4469
+ .flatMap((moduleSymbol) => typeChecker().getExportsOfModule(moduleSymbol))
4470
+ .find((one) => one.getName() === name);
4471
+ if (exported === undefined)
4472
+ return undefined;
4473
+ const target = exported.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(exported) : exported;
4474
+ const node = target.declarations?.find(ts.isClassLike);
4475
+ if (node === undefined)
4476
+ return undefined;
4477
+ return { file: node.getSourceFile().fileName, node };
4478
+ },
3698
4479
  literalsOf(node) {
3699
4480
  const found = typeChecker().getTypeAtLocation(node);
3700
4481
  const type = found.isTypeParameter() ? typeChecker().getBaseConstraintOfType(found) : found;
@@ -3792,16 +4573,15 @@ root, packageOf, isEntry, dependenciesOf) {
3792
4573
  (checker.isTypeAssignableTo(left, right) && checker.isTypeAssignableTo(right, left)));
3793
4574
  },
3794
4575
  typeTextOf(node) {
3795
- return typeChecker()
3796
- .typeToString(typeChecker().getTypeAtLocation(node))
3797
- .replace(/\s+/g, " ")
3798
- .trim();
4576
+ const checker = typeChecker();
4577
+ return stableTypeText(checker, checker.getTypeAtLocation(node)).replace(/\s+/g, " ").trim();
3799
4578
  },
3800
4579
  contextualTypeTextOf(node) {
3801
- const type = typeChecker().getContextualType(node);
4580
+ const checker = typeChecker();
4581
+ const type = checker.getContextualType(node);
3802
4582
  return type === undefined
3803
4583
  ? undefined
3804
- : typeChecker().typeToString(type).replace(/\s+/g, " ").trim();
4584
+ : stableTypeText(checker, type).replace(/\s+/g, " ").trim();
3805
4585
  },
3806
4586
  expectsPromiseReturn(node) {
3807
4587
  const checker = typeChecker();
@@ -3821,6 +4601,16 @@ root, packageOf, isEntry, dependenciesOf) {
3821
4601
  }));
3822
4602
  }));
3823
4603
  },
4604
+ expectsCallableReturn(node) {
4605
+ const checker = typeChecker();
4606
+ const type = checker.getContextualType(node);
4607
+ if (type === undefined)
4608
+ return false;
4609
+ return (type.isUnion() ? type.types : [type]).some((member) => member.getCallSignatures().some((signature) => {
4610
+ const returned = checker.getReturnTypeOfSignature(signature);
4611
+ return (returned.isUnion() ? returned.types : [returned]).some((part) => part.getCallSignatures().length > 0);
4612
+ }));
4613
+ },
3824
4614
  canBeUndefined(node) {
3825
4615
  const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
3826
4616
  // An unconstrained type parameter can be anything, undefined included.
@@ -3833,6 +4623,14 @@ root, packageOf, isEntry, dependenciesOf) {
3833
4623
  const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Null;
3834
4624
  return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0);
3835
4625
  },
4626
+ canBeFalse(node) {
4627
+ const checker = typeChecker();
4628
+ const type = widened(checker, checker.getTypeAtLocation(node));
4629
+ if (type === undefined)
4630
+ return true;
4631
+ const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown;
4632
+ return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0 || member === checker.getFalseType());
4633
+ },
3836
4634
  parameterIsNever(call, argumentIndex) {
3837
4635
  const declaration = typeChecker().getResolvedSignature(call)?.declaration;
3838
4636
  if (declaration === undefined || !("parameters" in declaration))
@@ -3883,17 +4681,24 @@ root, packageOf, isEntry, dependenciesOf) {
3883
4681
  const type = checker.getContextualType(node);
3884
4682
  return type === undefined ? [] : guaranteesOfType(checker, type);
3885
4683
  },
4684
+ markerValuesOf(node, property) {
4685
+ return markerValuesOfType(typeChecker(), typeChecker().getTypeAtLocation(node), property);
4686
+ },
3886
4687
  guaranteeValuesOf(target, name, contextual = false) {
3887
4688
  const checker = typeChecker();
3888
4689
  if ("kind" in target) {
3889
4690
  const type = contextual && ts.isExpression(target)
3890
4691
  ? checker.getContextualType(target)
3891
4692
  : checker.getTypeAtLocation(target);
3892
- return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
4693
+ return type === undefined
4694
+ ? undefined
4695
+ : markerValuesOfType(checker, type, `${GUARANTEE_PREFIX}${name}`);
3893
4696
  }
3894
4697
  const declaration = declarations.get(target.id);
3895
4698
  const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
3896
- return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
4699
+ return type === undefined
4700
+ ? undefined
4701
+ : markerValuesOfType(checker, type, `${GUARANTEE_PREFIX}${name}`);
3897
4702
  },
3898
4703
  heldAliasesOf(node, contextual = false) {
3899
4704
  const checker = typeChecker();
@@ -4097,6 +4902,43 @@ root, packageOf, isEntry, dependenciesOf) {
4097
4902
  return false;
4098
4903
  return typeChecker().isTypeAssignableTo(rest, typeChecker().getNonNullableType(typeChecker().getTypeAtLocation(to)));
4099
4904
  },
4905
+ valueAssignableTo(output, orUndefined, target) {
4906
+ const checker = typeChecker();
4907
+ const to = checker.getTypeAtLocation(target);
4908
+ if (orUndefined && !checker.isTypeAssignableTo(checker.getUndefinedType(), to))
4909
+ return false;
4910
+ if (output === "array") {
4911
+ const members = to.isUnion() ? to.types : [to];
4912
+ const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.NonPrimitive;
4913
+ return members.some((one) => (one.flags & open) !== 0 || checker.isArrayLikeType(one));
4914
+ }
4915
+ // An output that still holds a type parameter (`T[]`, `Promise<T>`) says nothing certain
4916
+ // about the value until its arguments are known.
4917
+ if (typeof output !== "string" && holdsTypeParameter(checker, output))
4918
+ return undefined;
4919
+ const declared = typeof output === "string" ? undefined : checker.getTypeFromTypeNode(output);
4920
+ const from = declared !== undefined
4921
+ ? (checker.getAwaitedType(declared) ?? declared)
4922
+ : output === "string"
4923
+ ? checker.getStringType()
4924
+ : output === "number"
4925
+ ? checker.getNumberType()
4926
+ : checker.getBooleanType();
4927
+ if (from.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
4928
+ return undefined;
4929
+ if (checker.isTypeAssignableTo(from, to))
4930
+ return true;
4931
+ // A brand (`string & { __brand: "Uuid" }`) adds no runtime value: the developer states that
4932
+ // the value was checked, so the type it brands counts.
4933
+ return (to.isUnion() ? to.types : [to]).some((member) => {
4934
+ if (!member.isIntersection())
4935
+ return false;
4936
+ const plain = member.types.filter((one) => (one.flags & ts.TypeFlags.Object) === 0);
4937
+ return (plain.length > 0 &&
4938
+ plain.length < member.types.length &&
4939
+ plain.every((one) => checker.isTypeAssignableTo(from, one)));
4940
+ });
4941
+ },
4100
4942
  parameterIsReadonly(call, argumentIndex) {
4101
4943
  // After a spread argument the indexes no longer line up with the parameters.
4102
4944
  if (call.arguments.slice(0, argumentIndex + 1).some(ts.isSpreadElement))
@@ -4185,6 +5027,27 @@ root, packageOf, isEntry, dependenciesOf) {
4185
5027
  arrayElementsOf(node) {
4186
5028
  return arrayElements(typeChecker().getTypeAtLocation(node));
4187
5029
  },
5030
+ arrayCanBeEmpty(node) {
5031
+ const checker = typeChecker();
5032
+ const members = definedMembers(checker, checker.getTypeAtLocation(node));
5033
+ if (members === undefined)
5034
+ return undefined;
5035
+ let empty = false;
5036
+ for (const member of members) {
5037
+ if (checker.isTupleType(member) && isTypeReference(member)) {
5038
+ const target = member.target;
5039
+ const required = "minLength" in target && typeof target.minLength === "number" ? target.minLength : 0;
5040
+ if (required === 0)
5041
+ empty = true;
5042
+ continue;
5043
+ }
5044
+ const name = platformNameOfType(member);
5045
+ if (name !== "Array" && name !== "ReadonlyArray")
5046
+ return undefined;
5047
+ empty = true;
5048
+ }
5049
+ return empty;
5050
+ },
4188
5051
  readIsPlain(node) {
4189
5052
  const checker = typeChecker();
4190
5053
  if (ts.isBindingElement(node)) {
@@ -4259,8 +5122,25 @@ root, packageOf, isEntry, dependenciesOf) {
4259
5122
  return false;
4260
5123
  const symbol = found.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(found) : found;
4261
5124
  const declarations = symbol.declarations ?? [];
4262
- return (declarations.length > 0 &&
4263
- declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile())));
5125
+ return (declarations.length > 0 && declarations.every((one) => isPlatformFile(one.getSourceFile())));
5126
+ },
5127
+ globalPackagesOf(node) {
5128
+ const found = typeChecker().getSymbolAtLocation(node);
5129
+ if (found === undefined || found.flags & ts.SymbolFlags.Alias)
5130
+ return [];
5131
+ const declarations = found.declarations ?? [];
5132
+ if (!declarations.every(isGlobalDeclaration))
5133
+ return [];
5134
+ const packages = new Set();
5135
+ for (const one of declarations) {
5136
+ const file = one.getSourceFile();
5137
+ if (isPlatformFile(file))
5138
+ continue;
5139
+ const name = packageOf(toTypeScriptPath(file.fileName));
5140
+ if (name !== undefined)
5141
+ packages.add(name);
5142
+ }
5143
+ return [...packages].sort();
4264
5144
  },
4265
5145
  isPlainClass(node) {
4266
5146
  const checker = typeChecker();
@@ -4310,7 +5190,7 @@ root, packageOf, isEntry, dependenciesOf) {
4310
5190
  return undefined;
4311
5191
  return {
4312
5192
  keyKind: stringInfo === undefined ? "number" : "string",
4313
- valueText: typeChecker().typeToString(info.type, undefined, ts.TypeFormatFlags.NoTruncation),
5193
+ valueText: stableTypeText(typeChecker(), info.type, "whole"),
4314
5194
  valueCanBeUndefined: includesUndefined(info.type),
4315
5195
  };
4316
5196
  },
@@ -4353,6 +5233,59 @@ root, packageOf, isEntry, dependenciesOf) {
4353
5233
  const to = body.getStart(sourceFile);
4354
5234
  return starts.some((start) => start >= from && start < to);
4355
5235
  },
5236
+ genericBaseOf(node, pkg, names) {
5237
+ const checker = typeChecker();
5238
+ const inPackage = (symbol) => (symbol.declarations ?? []).some((declaration) => packageOf(toTypeScriptPath(declaration.getSourceFile().fileName)) === pkg);
5239
+ return genericBaseOfType(checker, checker.getTypeAtLocation(node), inPackage, names);
5240
+ },
5241
+ isOrExtends(node, classes) {
5242
+ return isOrExtendsType(typeChecker(), typeChecker().getTypeAtLocation(node), classes);
5243
+ },
5244
+ instanceClassesOf(node, depth) {
5245
+ return instanceClassesOfType(typeChecker(), typeChecker().getTypeAtLocation(node), depth);
5246
+ },
5247
+ propertyTypesOf(node) {
5248
+ const checker = typeChecker();
5249
+ const type = widened(checker, checker.getTypeAtLocation(node));
5250
+ if (type === undefined || !(type.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection))) {
5251
+ return undefined;
5252
+ }
5253
+ return checker
5254
+ .getPropertiesOfType(type)
5255
+ .map((property) => {
5256
+ const own = checker.getTypeOfSymbol(property);
5257
+ const members = own.isUnion() ? own.types : [own];
5258
+ return {
5259
+ name: property.getName(),
5260
+ text: stableTypeText(checker, own).replace(/\s+/g, " ").trim(),
5261
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
5262
+ open: (own.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0,
5263
+ platform: platformNameOf(own) ?? null,
5264
+ nullish: members.some((one) => (one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0),
5265
+ };
5266
+ })
5267
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
5268
+ },
5269
+ parameterTakesUnknown(call, argumentIndex) {
5270
+ return takesUnknown(typeChecker(), call, argumentIndex);
5271
+ },
5272
+ typeShapeOf(node, from) {
5273
+ const checker = typeChecker();
5274
+ const type = from === "type"
5275
+ ? ts.isTypeNode(node)
5276
+ ? checker.getTypeFromTypeNode(node)
5277
+ : checker.getTypeAtLocation(node)
5278
+ : ts.isExpression(node)
5279
+ ? checker.getContextualType(node)
5280
+ : undefined;
5281
+ return type === undefined ? undefined : typeShape(isPlatformFile, checker, type, []);
5282
+ },
5283
+ metadataTypeOf(node) {
5284
+ return decoratorMetadata(program.getCompilerOptions(), {
5285
+ checker: typeChecker(),
5286
+ refOf: (symbol) => refOfSymbol(symbol),
5287
+ }, node);
5288
+ },
4356
5289
  narrowedBy(reference, test) {
4357
5290
  return narrowedMembers(program, typeChecker(), reference, test);
4358
5291
  },
@@ -4365,14 +5298,45 @@ root, packageOf, isEntry, dependenciesOf) {
4365
5298
  isErrorType(node) {
4366
5299
  return isErrorTypeOf(typeChecker().getTypeAtLocation(node));
4367
5300
  },
5301
+ hasNoType(node) {
5302
+ return (typeChecker().getTypeAtLocation(node).flags & ts.TypeFlags.Any) !== 0;
5303
+ },
5304
+ isOpenType(node) {
5305
+ const checker = typeChecker();
5306
+ const type = ts.isTypeNode(node)
5307
+ ? checker.getTypeFromTypeNode(node)
5308
+ : checker.getTypeAtLocation(node);
5309
+ return (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
5310
+ },
5311
+ builtinTypeOf(node, read) {
5312
+ const checker = typeChecker();
5313
+ const type = ts.isTypeNode(node)
5314
+ ? checker.getTypeFromTypeNode(node)
5315
+ : checker.getTypeAtLocation(node);
5316
+ return builtinOf(read === "awaited" ? (checker.getAwaitedType(type) ?? type) : type);
5317
+ },
4368
5318
  isPromiseLike(node) {
4369
5319
  return isPromiseType(typeChecker(), typeChecker().getTypeAtLocation(node));
4370
5320
  },
5321
+ methodReturnsPromiseLike(node, name) {
5322
+ const checker = typeChecker();
5323
+ const property = checker.getTypeAtLocation(node).getProperty(name);
5324
+ if (property === undefined)
5325
+ return false;
5326
+ const signatures = checker.getTypeOfSymbol(property).getCallSignatures();
5327
+ return (signatures.length > 0 &&
5328
+ signatures.every((signature) => isPromiseType(checker, checker.getReturnTypeOfSignature(signature))));
5329
+ },
4371
5330
  returnsPromiseLike(fn) {
4372
5331
  const signature = typeChecker().getSignatureFromDeclaration(fn);
4373
5332
  return (signature !== undefined &&
4374
5333
  isPromiseType(typeChecker(), typeChecker().getReturnTypeOfSignature(signature)));
4375
5334
  },
5335
+ mayReturnPromise(fn) {
5336
+ const signature = typeChecker().getSignatureFromDeclaration(fn);
5337
+ return (signature === undefined ||
5338
+ mayBePromiseType(typeChecker(), typeChecker().getReturnTypeOfSignature(signature)));
5339
+ },
4376
5340
  hasDefinedProperty(node, name) {
4377
5341
  const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
4378
5342
  if (type === undefined)
@@ -4471,10 +5435,12 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4471
5435
  /** The last program of each project, what it was built from, and its unit. */
4472
5436
  const previous = new Map();
4473
5437
  const caches = new Map();
5438
+ /** A program was let go since the last build: the next build drops the libraries only it held. */
5439
+ let released = false;
4474
5440
  /** What the last `open` found: the projects, their own files, and every own file of all of them. */
4475
5441
  let last;
4476
5442
  /** The program of one project, built now, as a unit; recorded for the next run when it can be. */
4477
- const buildUnit = ({ tsconfigPath, parsed, own, shared }, claimed, overlays, trustCache) => {
5443
+ const buildUnit = ({ tsconfigPath, parsed, own, shared, unreadTestConfigs }, claimed, overlays, trustCache) => {
4478
5444
  const sources = caches.get(tsconfigPath) ?? new Map();
4479
5445
  caches.set(tsconfigPath, sources);
4480
5446
  const oldProgram = previous.get(tsconfigPath);
@@ -4493,12 +5459,16 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4493
5459
  const packageOf = packageNames(host);
4494
5460
  const isEntry = packageEntries(host);
4495
5461
  const dependenciesOf = packageDependencies(host);
4496
- const program = ts.createProgram({
5462
+ let program = ts.createProgram({
4497
5463
  rootNames: parsed.fileNames,
4498
5464
  options: parsed.options,
4499
5465
  host,
4500
5466
  ...(oldProgram === undefined ? {} : { oldProgram: oldProgram.program }),
4501
5467
  });
5468
+ if (released) {
5469
+ released = false;
5470
+ keepLibrariesOf([program, ...[...previous.values()].map((kept) => kept.program)]);
5471
+ }
4502
5472
  const inputs = programInputs(parsed, claimed);
4503
5473
  // Nothing changed (the full pass right after a fast pass on the same text): keep the old
4504
5474
  // program, its type checker and what that checker already computed, instead of a second
@@ -4510,6 +5480,24 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4510
5480
  let fingerprints;
4511
5481
  /** The text hashes of read files asked for, kept in the record so a replayed program answers them. */
4512
5482
  const readPrints = {};
5483
+ /** What the config's facts keys resolve to, by digest, kept in the record the same way. */
5484
+ const factChecks = {};
5485
+ let imports;
5486
+ /** The package modules the own files import (`importedModules`), sorted. */
5487
+ const importsOf = () => {
5488
+ if (imports !== undefined)
5489
+ return imports;
5490
+ const all = new Set();
5491
+ for (const file of files) {
5492
+ const sourceFile = program.getSourceFile(file);
5493
+ if (sourceFile === undefined)
5494
+ continue;
5495
+ for (const name of importedModules(sourceFile, parsed.options))
5496
+ all.add(name);
5497
+ }
5498
+ imports = [...all].sort();
5499
+ return imports;
5500
+ };
4513
5501
  const fingerprintsOf = () => {
4514
5502
  if (fingerprints !== undefined)
4515
5503
  return fingerprints;
@@ -4522,6 +5510,8 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4522
5510
  files,
4523
5511
  fingerprints: Object.fromEntries(files.map((file) => [file, known.get(file) ?? ""])),
4524
5512
  reads: readPrints,
5513
+ imports: importsOf(),
5514
+ facts: factChecks,
4525
5515
  });
4526
5516
  cache.changed = true;
4527
5517
  }
@@ -4529,7 +5519,14 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4529
5519
  };
4530
5520
  /** What each file's rules were handed, by file: read ids, with the file each one is in. */
4531
5521
  const reads = new Map();
4532
- const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf);
5522
+ const queriesOf = (built) => createTypeQueries(built, claimed, cwd, packageOf, isEntry, dependenciesOf, config.platform);
5523
+ let types = queriesOf(program);
5524
+ /** Whether something may have asked `types` a question (creating the checker) since it started. */
5525
+ let asked = false;
5526
+ const askedTypes = () => {
5527
+ asked = true;
5528
+ return types;
5529
+ };
4533
5530
  const idFileName = idFileNames(cwd);
4534
5531
  const fileId = (fileName) => `${idFileName(fileName)}#`;
4535
5532
  /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
@@ -4552,15 +5549,18 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4552
5549
  files,
4553
5550
  listedElsewhere: (file) => shared.has(file),
4554
5551
  sourceFile: (file) => program.getSourceFile(file),
4555
- types,
5552
+ get types() {
5553
+ return askedTypes();
5554
+ },
4556
5555
  fingerprint: (file) => fingerprintsOf().get(file),
4557
5556
  typesFor: (file) => {
4558
5557
  const read = reads.get(file) ?? new Map();
4559
5558
  reads.set(file, read);
5559
+ const fileTypes = askedTypes();
4560
5560
  return {
4561
- ...types,
5561
+ ...fileTypes,
4562
5562
  declarationOf(symbol) {
4563
- const found = types.declarationOf(symbol);
5563
+ const found = fileTypes.declarationOf(symbol);
4564
5564
  if (found !== undefined && found.file !== file) {
4565
5565
  read.set(readId(symbol, found), found.file);
4566
5566
  }
@@ -4594,10 +5594,37 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4594
5594
  syntaxError: (file) => firstSyntaxError(program, file),
4595
5595
  unresolvedImports: (file) => unresolvedImportsOf(program, file),
4596
5596
  strictNullChecks: checksNulls(parsed.options),
5597
+ unreadTestConfigs,
4597
5598
  typesResolve: typesResolver(tsconfigPath, parsed.options),
5599
+ factKeys: (facts) => {
5600
+ const checks = checkFactKeys(facts, askedTypes());
5601
+ factChecks[factKeysDigest(facts)] = JSON.stringify(checks);
5602
+ return checks;
5603
+ },
5604
+ importsModule: (module) => importsModuleIn(importsOf(), module),
4598
5605
  bind: () => {
5606
+ asked = true;
4599
5607
  program.getTypeChecker();
4600
5608
  },
5609
+ renewChecker: () => {
5610
+ if (!asked)
5611
+ return;
5612
+ asked = false;
5613
+ // Served from the parsed files kept for this project (trusted, so nothing is read from
5614
+ // disk again): every file is the same object, so TypeScript reuses the whole structure
5615
+ // and binds nothing again. Only the checker is new.
5616
+ program = ts.createProgram({
5617
+ rootNames: parsed.fileNames,
5618
+ options: parsed.options,
5619
+ host: hostWithOverlays(parsed.options, overlays, sources, true, jsDoc),
5620
+ oldProgram: program,
5621
+ });
5622
+ types = queriesOf(program);
5623
+ // The next `open` builds on the newest program; the old one, and its checker, can go.
5624
+ const kept = previous.get(tsconfigPath);
5625
+ if (kept?.unit === unit)
5626
+ previous.set(tsconfigPath, { ...kept, program });
5627
+ },
4601
5628
  ignoreComments: (file) => {
4602
5629
  const sourceFile = program.getSourceFile(file);
4603
5630
  return sourceFile === undefined
@@ -4633,32 +5660,65 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4633
5660
  syntaxError: (file) => real().syntaxError(file),
4634
5661
  unresolvedImports: (file) => real().unresolvedImports(file),
4635
5662
  strictNullChecks: checksNulls(project.parsed.options),
5663
+ unreadTestConfigs: project.unreadTestConfigs,
4636
5664
  typesResolve: typesResolver(project.tsconfigPath, project.parsed.options),
5665
+ factKeys: (facts) => {
5666
+ const digest = factKeysDigest(facts);
5667
+ const kept = record.facts[digest];
5668
+ const known = kept === undefined ? undefined : readFactKeyChecks(kept);
5669
+ if (known !== undefined)
5670
+ return known;
5671
+ const checks = real().factKeys(facts);
5672
+ record.facts[digest] = JSON.stringify(checks);
5673
+ if (cache !== undefined)
5674
+ cache.changed = true;
5675
+ return checks;
5676
+ },
5677
+ importsModule: (module) => importsModuleIn(record.imports, module),
4637
5678
  bind: () => {
4638
5679
  real().bind();
4639
5680
  },
5681
+ renewChecker: () => {
5682
+ built?.renewChecker();
5683
+ },
4640
5684
  ignoreComments: (file) => real().ignoreComments(file),
4641
5685
  tryEdits: (candidates) => real().tryEdits(candidates),
4642
5686
  };
4643
5687
  };
4644
- const build = (projects, claimed, overlays, trustCache) => {
5688
+ const unitOf = (project, claimed, overlays, trustCache) => {
5689
+ const record = cache?.programs.get(project.tsconfigPath);
5690
+ const replayable = record !== undefined &&
5691
+ !previous.has(project.tsconfigPath) &&
5692
+ !trustCache &&
5693
+ record.inputs ===
5694
+ recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
5695
+ replays(record.queries, replayHost(project.parsed.options, overlays));
5696
+ return replayable
5697
+ ? recordedUnit(project, claimed, record, overlays)
5698
+ : buildUnit(project, claimed, overlays, trustCache);
5699
+ };
5700
+ const pendingUnits = (projects, claimed, overlays, trustCache) => {
4645
5701
  const normalized = new Map([...overlays].map(([file, text]) => [toTypeScriptPath(file), text]));
4646
5702
  return projects
4647
5703
  .filter((project) => project.own.length > 0)
4648
5704
  .map((project) => {
4649
- const record = cache?.programs.get(project.tsconfigPath);
4650
- const replayable = record !== undefined &&
4651
- !previous.has(project.tsconfigPath) &&
4652
- !trustCache &&
4653
- record.inputs ===
4654
- recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
4655
- replays(record.queries, replayHost(project.parsed.options, normalized));
4656
- return replayable
4657
- ? recordedUnit(project, claimed, record, normalized)
4658
- : buildUnit(project, claimed, normalized, trustCache);
5705
+ let unit;
5706
+ let size;
5707
+ return {
5708
+ tsconfig: project.tsconfigPath,
5709
+ size: () => (size ??= programSize(project.parsed, project.own, normalized)),
5710
+ open: () => (unit ??= unitOf(project, claimed, normalized, trustCache)),
5711
+ release: () => {
5712
+ unit = undefined;
5713
+ previous.delete(project.tsconfigPath);
5714
+ caches.delete(project.tsconfigPath);
5715
+ released = true;
5716
+ },
5717
+ };
4659
5718
  });
4660
5719
  };
4661
- const open = (overlays) => {
5720
+ const build = (projects, claimed, overlays, trustCache) => pendingUnits(projects, claimed, overlays, trustCache).map((pending) => pending.open());
5721
+ const pending = (overlays) => {
4662
5722
  const entries = config.tsconfig.map((entry) => path.resolve(cwd, entry));
4663
5723
  const named = entries.map((entry) => displayPath(cwd, entry)).join("`, `");
4664
5724
  const { files: roots, unmatched } = expandTsconfigs(entries);
@@ -4673,34 +5733,32 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4673
5733
  const collected = collectConfigs(roots);
4674
5734
  const shared = collected.length > 1 ? listedTwice(collected) : new Set();
4675
5735
  const projects = collected.map(({ path: tsconfigPath, parsed }) => {
4676
- const own = ownFileNames(parsed, config, cwd, claimed);
5736
+ // The test runner's own test files join the default `exclude`, unless the config replaced it.
5737
+ const tests = config.replacesDefaultExclude
5738
+ ? { matches: () => false, unread: [] }
5739
+ : testRunnerFiles([path.dirname(tsconfigPath), config.configDir]);
5740
+ const own = ownFileNames(parsed, config, cwd, claimed, tests.matches);
4677
5741
  for (const file of own)
4678
5742
  claimed.add(file);
4679
- return { tsconfigPath, parsed, own, shared };
5743
+ return { tsconfigPath, parsed, own, shared, unreadTestConfigs: tests.unread };
4680
5744
  });
4681
5745
  if (claimed.size === 0)
4682
5746
  throw new NothingToCheckError(named);
4683
5747
  last = { projects, claimed };
4684
- return build(projects, claimed, overlays, false);
5748
+ return pendingUnits(projects, claimed, overlays, false);
4685
5749
  };
5750
+ const open = (overlays) => pending(overlays).map((unit) => unit.open());
4686
5751
  return {
4687
5752
  open,
5753
+ pending,
4688
5754
  release: () => {
4689
5755
  previous.clear();
4690
5756
  caches.clear();
5757
+ released = true;
4691
5758
  },
4692
5759
  reopen: (overlays) => last === undefined ? open(overlays) : build(last.projects, last.claimed, overlays, true),
4693
5760
  };
4694
5761
  }
4695
- // ---- package sources ----------------------------------------
4696
- function isSymbol(value) {
4697
- return typeof value === "object" && value !== null && "flags" in value && "escapedName" in value;
4698
- }
4699
- /**
4700
- * The module symbol of a file: the checker answers for an ES module; a CommonJS file (`exports.x
4701
- * = …`) has one only on the file itself, which TypeScript keeps without a public type, so it is
4702
- * read through reflection and checked at run time.
4703
- */
4704
5762
  /** The type alias a module exports under `name`, aliases resolved; undefined when it exports none. */
4705
5763
  function exportedAlias(checker, sourceFile, name) {
4706
5764
  const module = moduleSymbolOf(checker, sourceFile);
@@ -4747,6 +5805,28 @@ function relativeSpecifier(program, importer, file) {
4747
5805
  }
4748
5806
  }
4749
5807
  }
5808
+ // ---- facts keys ---------------------------------------------------------------------------------
5809
+ /**
5810
+ * The names a `facts` key is written in, resolved by the type checker (0041): a module as the
5811
+ * project would import it, then a dotted path through its exports and their members
5812
+ * (`"typeorm": { "Repository.find": … }`). A key names the declarations of the symbol it resolves
5813
+ * to, so it does not depend on how the module's declarations are written: two module names that
5814
+ * resolve to one symbol (an alias module that re-exports another) name the same declarations.
5815
+ */
5816
+ /** How deep `names` lists a module's paths (`Repository.find` is two). */
5817
+ const LISTED_DEPTH = 2;
5818
+ /** At most this many paths are listed per module. */
5819
+ const MAX_LISTED = 50_000;
5820
+ /** How many `export =` a module is followed through. */
5821
+ const MAX_EXPORT_EQUALS = 4;
5822
+ function isSymbol(value) {
5823
+ return typeof value === "object" && value !== null && "flags" in value && "escapedName" in value;
5824
+ }
5825
+ /**
5826
+ * The module symbol of a file: the checker answers for an ES module; a CommonJS file (`exports.x
5827
+ * = …`) has one only on the file itself, which TypeScript keeps without a public type, so it is
5828
+ * read through reflection and checked at run time.
5829
+ */
4750
5830
  function moduleSymbolOf(checker, sourceFile) {
4751
5831
  const found = checker.getSymbolAtLocation(sourceFile);
4752
5832
  if (found !== undefined)
@@ -4754,105 +5834,476 @@ function moduleSymbolOf(checker, sourceFile) {
4754
5834
  const own = Reflect.get(sourceFile, "symbol");
4755
5835
  return isSymbol(own) ? own : undefined;
4756
5836
  }
4757
- const PACKAGE_JAVASCRIPT = /\.(?:js|mjs|cjs)$/;
4758
- const PACKAGE_OPTIONS = {
4759
- allowJs: true,
4760
- checkJs: false,
4761
- noEmit: true,
4762
- target: ts.ScriptTarget.ES2022,
4763
- module: ts.ModuleKind.Preserve,
4764
- moduleResolution: ts.ModuleResolutionKind.Bundler,
4765
- lib: ["lib.es2022.d.ts"],
4766
- types: [],
4767
- skipLibCheck: true,
4768
- };
4769
- function isRelativeSpecifier(specifier) {
4770
- return specifier.startsWith("./") || specifier.startsWith("../");
4771
- }
4772
- /**
4773
- * Opens the package at `root` from `entry` (a JavaScript file in it). Its files are parsed with
4774
- * the library files' cache, so a later package or project shares TypeScript's lib files.
4775
- */
4776
- export function openPackageSource(root, entry) {
4777
- const packageRoot = toTypeScriptPath(root);
4778
- const inPackage = (file) => file.startsWith(`${packageRoot}/`) &&
4779
- !file.slice(packageRoot.length).includes("/node_modules/");
4780
- const base = hostWithOverlays(PACKAGE_OPTIONS, new Map(), new Map(), false, false, isTypeScriptLib);
4781
- const host = {
4782
- ...base,
4783
- // Relative specifiers inside the package only: another package is not followed (its calls
4784
- // stay unknown), and nothing here is an "external library" TypeScript would skip.
4785
- resolveModuleNameLiterals: (literals, containingFile) => literals.map((literal) => {
4786
- if (!isRelativeSpecifier(literal.text))
4787
- return { resolvedModule: undefined };
4788
- const found = ts.resolveModuleName(literal.text, containingFile, PACKAGE_OPTIONS, base);
4789
- const resolved = found.resolvedModule;
4790
- if (resolved === undefined ||
4791
- !PACKAGE_JAVASCRIPT.test(resolved.resolvedFileName) ||
4792
- !inPackage(toTypeScriptPath(resolved.resolvedFileName))) {
4793
- return { resolvedModule: undefined };
5837
+ function createFactNames(checker, program,
5838
+ /** The package of a file (`TypeQueries.packageOf`). */
5839
+ packageOf,
5840
+ /** A file in the project's folder that module names are resolved from (it need not exist). */
5841
+ resolveFrom,
5842
+ /** The project's own files. */
5843
+ own) {
5844
+ let ambient;
5845
+ let imported;
5846
+ const modules = new Map();
5847
+ const children = new Map();
5848
+ const targets = new Map();
5849
+ const listed = new Map();
5850
+ const resolved = (symbol) => symbol.flags & ts.SymbolFlags.Alias ? checker().getAliasedSymbol(symbol) : symbol;
5851
+ /** Whether a value can be called: a function, a class, or a value whose type has a signature. */
5852
+ const isCallable = (symbol) => (symbol.flags & (ts.SymbolFlags.Function | ts.SymbolFlags.Class)) !== 0 ||
5853
+ checker().getTypeOfSymbol(symbol).getCallSignatures().length > 0;
5854
+ /** The modules `declare module "x"` declares, by the name it is written with. */
5855
+ const ambientModules = () => {
5856
+ if (ambient !== undefined)
5857
+ return ambient;
5858
+ ambient = new Map();
5859
+ for (const symbol of checker().getAmbientModules()) {
5860
+ for (const declaration of symbol.declarations ?? []) {
5861
+ if (ts.isModuleDeclaration(declaration) &&
5862
+ ts.isStringLiteral(declaration.name) &&
5863
+ !ambient.has(declaration.name.text)) {
5864
+ ambient.set(declaration.name.text, symbol);
5865
+ }
4794
5866
  }
4795
- return { resolvedModule: { ...resolved, isExternalLibraryImport: false } };
4796
- }),
5867
+ }
5868
+ return ambient;
4797
5869
  };
4798
- const program = ts.createProgram({
4799
- rootNames: [toTypeScriptPath(entry)],
4800
- options: PACKAGE_OPTIONS,
4801
- host,
4802
- });
4803
- const files = program
4804
- .getSourceFiles()
4805
- .map((file) => file.fileName)
4806
- .filter((file) => inPackage(file) && PACKAGE_JAVASCRIPT.test(file))
4807
- .sort();
4808
- const own = new Set(files);
4809
- const types = createTypeQueries(program, own, packageRoot, packageNames(host), packageEntries(host), packageDependencies(host));
4810
- // Plugins walk the nodes with parents: the binder sets them.
4811
- const checker = program.getTypeChecker();
4812
- const idFileName = idFileNames(packageRoot);
4813
- const refOf = (symbol) => {
4814
- const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
4815
- const declaration = resolved.valueDeclaration ?? resolved.declarations?.[0];
4816
- if (declaration === undefined)
4817
- return undefined;
4818
- const file = declaration.getSourceFile().fileName;
4819
- return { id: `${idFileName(file)}#${declarationPath(declaration)}`, name: resolved.getName() };
5870
+ /**
5871
+ * The module symbols the own files' imports and re-exports reach, by the name they write: the
5872
+ * checker resolves each in its file's own mode, as the project's imports resolve.
5873
+ */
5874
+ const importedModules = () => {
5875
+ if (imported !== undefined)
5876
+ return imported;
5877
+ imported = new Map();
5878
+ for (const file of program.getSourceFiles()) {
5879
+ if (!own.has(file.fileName))
5880
+ continue;
5881
+ for (const specifier of specifiersOf(file)) {
5882
+ const found = checker().getSymbolAtLocation(specifier);
5883
+ if (found === undefined)
5884
+ continue;
5885
+ const list = imported.get(specifier.text) ?? [];
5886
+ if (!list.includes(found))
5887
+ list.push(found);
5888
+ imported.set(specifier.text, list);
5889
+ }
5890
+ }
5891
+ return imported;
5892
+ };
5893
+ /** The module symbol of the file `module` resolves to from the project's folder in `mode`. */
5894
+ const resolvedIn = (module, mode) => {
5895
+ const file = ts.resolveModuleName(module, resolveFrom, program.getCompilerOptions(), ts.sys, undefined, undefined, mode).resolvedModule?.resolvedFileName;
5896
+ const sourceFile = file === undefined ? undefined : program.getSourceFile(file);
5897
+ return sourceFile === undefined ? undefined : moduleSymbolOf(checker(), sourceFile);
5898
+ };
5899
+ const modulesNamed = (module) => {
5900
+ const known = modules.get(module);
5901
+ if (known !== undefined)
5902
+ return known;
5903
+ // As TypeScript resolves an import: a module `declare module` declares, else the files the
5904
+ // project's imports of it reach, and those it resolves to in either mode.
5905
+ const declared = ambientModules().get(module);
5906
+ const found = declared !== undefined
5907
+ ? [declared]
5908
+ : [
5909
+ ...new Set([
5910
+ ...(importedModules().get(module) ?? []),
5911
+ resolvedIn(module, ts.ModuleKind.ESNext),
5912
+ resolvedIn(module, ts.ModuleKind.CommonJS),
5913
+ ].flatMap((one) => (one === undefined ? [] : [resolved(one)]))),
5914
+ ];
5915
+ modules.set(module, found);
5916
+ return found;
5917
+ };
5918
+ /**
5919
+ * The names one step below a symbol: a module's exports (with what its `export =` gives), a
5920
+ * class's or interface's members, and the properties of a value's type (`const path:
5921
+ * PlatformPath` gives `join`).
5922
+ */
5923
+ const childrenOf = (symbol, depth = 0) => {
5924
+ const target = resolved(symbol);
5925
+ const known = children.get(target);
5926
+ if (known !== undefined)
5927
+ return known;
5928
+ const found = new Map();
5929
+ const add = (name, one) => {
5930
+ if (one.escapedName === ts.InternalSymbolName.ExportEquals)
5931
+ return;
5932
+ const list = found.get(name) ?? [];
5933
+ if (!list.includes(one))
5934
+ list.push(one);
5935
+ found.set(name, list);
5936
+ };
5937
+ const flags = target.flags;
5938
+ if (flags & ts.SymbolFlags.Module) {
5939
+ for (const one of checker().getExportsOfModule(target))
5940
+ add(one.getName(), one);
5941
+ const whole = target.exports?.get(ts.InternalSymbolName.ExportEquals);
5942
+ if (whole !== undefined && depth < MAX_EXPORT_EQUALS) {
5943
+ for (const [name, list] of childrenOf(whole, depth + 1)) {
5944
+ for (const one of list)
5945
+ add(name, one);
5946
+ }
5947
+ // A module whose value is itself callable (`export =` of a function or a class) is
5948
+ // named by `default`, the name a default import gives it.
5949
+ const value = resolved(whole);
5950
+ if (!found.has("default") && isCallable(value))
5951
+ add("default", value);
5952
+ }
5953
+ }
5954
+ if (flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)) {
5955
+ for (const one of checker().getDeclaredTypeOfSymbol(target).getProperties()) {
5956
+ add(one.getName(), one);
5957
+ }
5958
+ }
5959
+ if (flags &
5960
+ (ts.SymbolFlags.Variable |
5961
+ ts.SymbolFlags.Property |
5962
+ ts.SymbolFlags.Accessor |
5963
+ ts.SymbolFlags.Function |
5964
+ ts.SymbolFlags.Class)) {
5965
+ for (const one of checker().getTypeOfSymbol(target).getProperties()) {
5966
+ add(one.getName(), one);
5967
+ }
5968
+ }
5969
+ children.set(target, found);
5970
+ return found;
5971
+ };
5972
+ const declarationsOf = (symbols) => new Set(symbols.flatMap((one) => resolved(one).declarations ?? []));
5973
+ /**
5974
+ * The declarations a class or a value is known by as a receiver: its own (a class, an interface,
5975
+ * an alias), and for a value (`export const client: Client`) those of its type.
5976
+ */
5977
+ const ownerDeclarationsOf = (symbol) => {
5978
+ const target = resolved(symbol);
5979
+ const own = target.declarations ?? [];
5980
+ if ((target.flags & (ts.SymbolFlags.Variable | ts.SymbolFlags.Property)) === 0)
5981
+ return own;
5982
+ const typed = checker().getTypeOfSymbol(target).getSymbol();
5983
+ return [...own, ...(typed?.declarations ?? [])];
5984
+ };
5985
+ /** Whether a member's declaration is written in one of `owners` (`class Store { save(): void }`). */
5986
+ const declaredIn = (declaration, owners) => {
5987
+ const container = declaration.parent;
5988
+ return (owners.has(container) || (ts.isTypeLiteralNode(container) && owners.has(container.parent)));
5989
+ };
5990
+ /**
5991
+ * The members one step below `owners` (`"Store.*"`): each member written in an owner is stated
5992
+ * on any call; a member an owner inherits (`find` of its `Base`) only through a receiver that is
5993
+ * the owner, or extends it. `keep` leaves members out (a package line keeps its own package's).
5994
+ */
5995
+ const membersOf = (owners, declarations, throughReceiver, keep) => {
5996
+ for (const owner of owners) {
5997
+ const ownerDeclarations = new Set(ownerDeclarationsOf(owner));
5998
+ for (const member of [...childrenOf(owner).values()].flat()) {
5999
+ for (const declaration of resolved(member).declarations ?? []) {
6000
+ if (!keep(declaration))
6001
+ continue;
6002
+ if (declaredIn(declaration, ownerDeclarations)) {
6003
+ declarations.add(declaration);
6004
+ continue;
6005
+ }
6006
+ const classes = throughReceiver.get(declaration) ?? new Set();
6007
+ for (const one of ownerDeclarations)
6008
+ classes.add(one);
6009
+ throughReceiver.set(declaration, classes);
6010
+ }
6011
+ }
6012
+ }
6013
+ };
6014
+ /** The target: a declaration stated on any call needs no receiver as well. */
6015
+ const foundTarget = (declarations, throughReceiver) => {
6016
+ for (const declaration of declarations)
6017
+ throughReceiver.delete(declaration);
6018
+ return { kind: "found", declarations, throughReceiver };
6019
+ };
6020
+ /** `"Store.*"`: the methods and properties of the class, the inherited ones by their receiver. */
6021
+ const classTarget = (owners) => {
6022
+ const declarations = new Set();
6023
+ const throughReceiver = new Map();
6024
+ membersOf(owners, declarations, throughReceiver, () => true);
6025
+ return foundTarget(declarations, throughReceiver);
6026
+ };
6027
+ /**
6028
+ * `"*"`: what the module exports, and the members of what it exports that its own package
6029
+ * declares; a member of another package (`on` of an `EventEmitter` a class extends) is never
6030
+ * stated by it.
6031
+ */
6032
+ const packageTarget = (moduleSymbols) => {
6033
+ const packages = new Set(moduleSymbols.flatMap((one) => (resolved(one).declarations ?? []).map((declaration) => packageOf(toTypeScriptPath(declaration.getSourceFile().fileName)))));
6034
+ const exported = moduleSymbols.flatMap((one) => [...childrenOf(one).values()].flat());
6035
+ const declarations = declarationsOf(exported);
6036
+ const throughReceiver = new Map();
6037
+ membersOf(exported, declarations, throughReceiver, (declaration) => packages.has(packageOf(toTypeScriptPath(declaration.getSourceFile().fileName))));
6038
+ return foundTarget(declarations, throughReceiver);
6039
+ };
6040
+ const target = (module, name) => {
6041
+ const key = `${module}\u0000${name}`;
6042
+ const known = targets.get(key);
6043
+ if (known !== undefined)
6044
+ return known;
6045
+ const moduleSymbols = modulesNamed(module);
6046
+ let found;
6047
+ if (moduleSymbols.length === 0) {
6048
+ found = { kind: "no-module" };
6049
+ }
6050
+ else {
6051
+ const grain = factGrainOf(name);
6052
+ // A grain names the members one step below what its path reaches: a class's methods and
6053
+ // properties (with the inherited ones its type has), or the module's exports and theirs.
6054
+ const path = grain.kind === "function" ? name : grain.kind === "class" ? grain.owner : "";
6055
+ let current = moduleSymbols;
6056
+ for (const part of path === "" ? [] : path.split(".")) {
6057
+ const next = [...new Set(current.flatMap((one) => childrenOf(one).get(part) ?? []))];
6058
+ current = next;
6059
+ if (next.length === 0)
6060
+ break;
6061
+ }
6062
+ found =
6063
+ current.length === 0
6064
+ ? { kind: "no-name" }
6065
+ : grain.kind === "function"
6066
+ ? { kind: "found", declarations: declarationsOf(current), throughReceiver: new Map() }
6067
+ : grain.kind === "class"
6068
+ ? classTarget(current)
6069
+ : packageTarget(moduleSymbols);
6070
+ }
6071
+ targets.set(key, found);
6072
+ return found;
6073
+ };
6074
+ /** The paths of a module up to `LISTED_DEPTH`, shortest first, each with its symbols. */
6075
+ const listedOf = (module) => {
6076
+ const known = listed.get(module);
6077
+ if (known !== undefined)
6078
+ return known;
6079
+ const found = new Map();
6080
+ let level = modulesNamed(module).flatMap((one) => [
6081
+ ...childrenOf(one),
6082
+ ]);
6083
+ for (let depth = 1; depth <= LISTED_DEPTH && level.length > 0; depth++) {
6084
+ const next = [];
6085
+ for (const [name, symbols] of level) {
6086
+ if (found.size >= MAX_LISTED)
6087
+ break;
6088
+ found.set(name, symbols);
6089
+ if (depth === LISTED_DEPTH)
6090
+ continue;
6091
+ for (const symbol of symbols) {
6092
+ for (const [child, list] of childrenOf(symbol))
6093
+ next.push([`${name}.${child}`, list]);
6094
+ }
6095
+ }
6096
+ level = next;
6097
+ }
6098
+ listed.set(module, found);
6099
+ return found;
4820
6100
  };
4821
- const member = (symbol, name) => {
4822
- const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
4823
- const escaped = ts.escapeLeadingUnderscores(name);
4824
- return (resolved.members?.get(escaped) ??
4825
- resolved.exports?.get(escaped) ??
4826
- checker.getTypeOfSymbol(resolved).getProperty(name));
6101
+ /**
6102
+ * The shortest name in `module` that resolves to `declaration`: the declaration's own path in
6103
+ * its types (`["path", "PlatformPath", "join"]`), its last names first (`join`, then
6104
+ * `PlatformPath.join`), each resolved forward as a key is, then `default`, then the
6105
+ * declaration's own name under each of the module's exports (`Buffer.from`, where the module
6106
+ * exports a value whose type has the method), shortest export first. Nothing is listed: a hint
6107
+ * asks this for every unknown call.
6108
+ */
6109
+ const nameOf = (module, declaration) => {
6110
+ const names = pathOf(declaration);
6111
+ const resolves = (name) => {
6112
+ const found = target(module, name);
6113
+ return found.kind === "found" && found.declarations.has(declaration);
6114
+ };
6115
+ const own = [...names.map((_, at) => names.slice(names.length - 1 - at).join(".")), "default"];
6116
+ const direct = own.find(resolves);
6117
+ const last = names.at(-1);
6118
+ const moduleSymbols = modulesNamed(module);
6119
+ if (direct !== undefined || last === undefined || moduleSymbols.length === 0)
6120
+ return direct;
6121
+ const exports = [...new Set(moduleSymbols.flatMap((one) => [...childrenOf(one).keys()]))].sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
6122
+ return exports.map((name) => `${name}.${last}`).find(resolves);
4827
6123
  };
4828
6124
  return {
4829
- files,
4830
- sourceFile: (file) => program.getSourceFile(toTypeScriptPath(file)),
4831
- types,
4832
- exported(file, names) {
4833
- const sourceFile = program.getSourceFile(toTypeScriptPath(file));
4834
- const moduleSymbol = sourceFile === undefined ? undefined : moduleSymbolOf(checker, sourceFile);
4835
- const [first, ...rest] = names;
4836
- if (moduleSymbol === undefined || first === undefined)
4837
- return undefined;
4838
- let symbol = checker.getExportsOfModule(moduleSymbol).find((one) => one.getName() === first);
4839
- if (symbol === undefined) {
4840
- // `module.exports = fn`: the module is the function.
4841
- const assigned = moduleSymbol.exports?.get(ts.InternalSymbolName.ExportEquals);
4842
- const whole = assigned === undefined || !(assigned.flags & ts.SymbolFlags.Alias)
4843
- ? assigned
4844
- : checker.getAliasedSymbol(assigned);
4845
- if (whole !== undefined && (first === "default" || whole.getName() === first)) {
4846
- symbol = whole;
6125
+ modulesNamed,
6126
+ target,
6127
+ // Only the name the hint gives for a declaration, so "did you mean" and the hint agree
6128
+ // (`join`, not `posix.join` for the same function).
6129
+ names: (module) => [...listedOf(module)].flatMap(([name, symbols]) => [...declarationsOf(symbols)].some((node) => nameOf(module, node) === name) ? [name] : []),
6130
+ nameOf,
6131
+ };
6132
+ }
6133
+ /** How many aliases (imports, re-exports) a reference is followed through to its module. */
6134
+ const MAX_ALIAS_STEPS = 8;
6135
+ function unwrappedReference(node) {
6136
+ let current = node;
6137
+ while (ts.isParenthesizedExpression(current) ||
6138
+ ts.isNonNullExpression(current) ||
6139
+ ts.isAsExpression(current) ||
6140
+ ts.isSatisfiesExpression(current)) {
6141
+ current = current.expression;
6142
+ }
6143
+ return current;
6144
+ }
6145
+ /** The leftmost name of a reference: `db` of `db.users.watch`, `make` of `make().run`. */
6146
+ function referenceRoot(node) {
6147
+ const bare = unwrappedReference(node);
6148
+ if (ts.isIdentifier(bare))
6149
+ return bare;
6150
+ if (ts.isPropertyAccessExpression(bare) ||
6151
+ ts.isElementAccessExpression(bare) ||
6152
+ ts.isCallExpression(bare) ||
6153
+ ts.isNewExpression(bare)) {
6154
+ return referenceRoot(bare.expression);
6155
+ }
6156
+ return undefined;
6157
+ }
6158
+ /** The module an import or re-export declaration names (`"kit"` of `import { a } from "kit"`). */
6159
+ function specifierOf(declaration) {
6160
+ if (ts.isImportEqualsDeclaration(declaration) &&
6161
+ ts.isExternalModuleReference(declaration.moduleReference) &&
6162
+ ts.isStringLiteral(declaration.moduleReference.expression)) {
6163
+ return declaration.moduleReference.expression;
6164
+ }
6165
+ const statement = ts.findAncestor(declaration, (node) => ts.isImportDeclaration(node) || ts.isExportDeclaration(node));
6166
+ const specifier = statement !== undefined &&
6167
+ (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement))
6168
+ ? statement.moduleSpecifier
6169
+ : undefined;
6170
+ return specifier !== undefined && ts.isStringLiteral(specifier) ? specifier : undefined;
6171
+ }
6172
+ /** The module specifiers a file's top-level imports and re-exports write, in file order. */
6173
+ function specifiersOf(file) {
6174
+ return file.statements.flatMap((statement) => {
6175
+ const specifier = ts.isImportDeclaration(statement) ||
6176
+ ts.isExportDeclaration(statement) ||
6177
+ ts.isImportEqualsDeclaration(statement)
6178
+ ? specifierOf(statement)
6179
+ : undefined;
6180
+ return specifier === undefined ? [] : [specifier];
6181
+ });
6182
+ }
6183
+ /**
6184
+ * The module a `facts` key for a declaration outside the project is written from
6185
+ * (`TypeQueries.factModuleOf`), and the name in it, by the first module that names the
6186
+ * declaration (`FactNames.nameOf`) of these:
6187
+ *
6188
+ * 1. the module the reference's leftmost name is imported from, as the project writes it, after
6189
+ * following re-exports and aliases out of the project's files;
6190
+ * 2. the modules the files on that way, and the reference's own file, import or re-export;
6191
+ * 3. the module the declaration is declared in (`declare module "x"`), else its package;
6192
+ * 4. the modules of the declaration's own package the program loads: the ambient modules its files
6193
+ * declare, and the modules the program's files import from it, by name.
6194
+ *
6195
+ * A module of the project's own files is never one: a key names code outside the project.
6196
+ */
6197
+ function createFactModules(input) {
6198
+ const { checker, program, names, own, isPlatformFile, packageOf } = input;
6199
+ const known = new WeakMap();
6200
+ let byPackage;
6201
+ const isOwn = (file) => own.has(file.fileName);
6202
+ /** Whether a specifier names a module outside the project, as a key can be resolved from it. */
6203
+ const leavesProject = (specifier) => {
6204
+ const text = specifier.text;
6205
+ if (text.startsWith(".") || path.isAbsolute(text))
6206
+ return false;
6207
+ const declarations = checker().getSymbolAtLocation(specifier)?.declarations ?? [];
6208
+ return declarations.length > 0 && declarations.every((one) => !isOwn(one.getSourceFile()));
6209
+ };
6210
+ /** The modules of each package the program loads, by name: ambient ones and imported ones. */
6211
+ const modulesByPackage = () => {
6212
+ if (byPackage !== undefined)
6213
+ return byPackage;
6214
+ const found = new Map();
6215
+ const add = (file, module) => {
6216
+ const owner = packageOf(file.fileName);
6217
+ if (owner === undefined || isOwn(file))
6218
+ return;
6219
+ found.set(owner, (found.get(owner) ?? new Set()).add(module));
6220
+ };
6221
+ for (const symbol of checker().getAmbientModules()) {
6222
+ for (const declaration of symbol.declarations ?? []) {
6223
+ if (ts.isModuleDeclaration(declaration) && ts.isStringLiteral(declaration.name)) {
6224
+ add(declaration.getSourceFile(), declaration.name.text);
4847
6225
  }
4848
6226
  }
4849
- for (const name of rest) {
4850
- if (symbol === undefined)
4851
- return undefined;
4852
- symbol = member(symbol, name);
6227
+ }
6228
+ for (const file of program.getSourceFiles()) {
6229
+ for (const specifier of specifiersOf(file)) {
6230
+ if (!leavesProject(specifier))
6231
+ continue;
6232
+ const target = checker().getSymbolAtLocation(specifier)?.declarations?.[0];
6233
+ if (target !== undefined)
6234
+ add(target.getSourceFile(), specifier.text);
4853
6235
  }
4854
- return symbol === undefined ? undefined : refOf(symbol);
4855
- },
6236
+ }
6237
+ byPackage = new Map([...found].map(([owner, modules]) => [owner, [...modules].sort()]));
6238
+ return byPackage;
6239
+ };
6240
+ /** Step 1 and the files it passes: the module the reference is imported from, followed out. */
6241
+ const imported = (reference) => {
6242
+ const files = [reference.getSourceFile()];
6243
+ const root = referenceRoot(reference);
6244
+ let symbol = root === undefined ? undefined : checker().getSymbolAtLocation(root);
6245
+ for (let step = 0; step < MAX_ALIAS_STEPS && symbol !== undefined; step++) {
6246
+ if ((symbol.flags & ts.SymbolFlags.Alias) === 0)
6247
+ break;
6248
+ for (const declaration of symbol.declarations ?? []) {
6249
+ const file = declaration.getSourceFile();
6250
+ if (!isOwn(file))
6251
+ continue;
6252
+ if (!files.includes(file))
6253
+ files.push(file);
6254
+ const specifier = specifierOf(declaration);
6255
+ if (specifier !== undefined && leavesProject(specifier)) {
6256
+ return { module: specifier.text, files };
6257
+ }
6258
+ }
6259
+ symbol = checker().getImmediateAliasedSymbol(symbol);
6260
+ }
6261
+ return { files };
6262
+ };
6263
+ const isPlatformModule = (module) => {
6264
+ const declarations = names.modulesNamed(module).flatMap((one) => one.declarations ?? []);
6265
+ return (declarations.length > 0 && declarations.every((one) => isPlatformFile(one.getSourceFile())));
6266
+ };
6267
+ const search = (declaration, reference) => {
6268
+ const way = imported(reference);
6269
+ const file = declaration.getSourceFile();
6270
+ const owner = packageOf(file.fileName);
6271
+ const candidates = [
6272
+ way.module,
6273
+ ...way.files.flatMap((one) => specifiersOf(one).flatMap((specifier) => leavesProject(specifier) ? [specifier.text] : [])),
6274
+ declaredPackageOf({ packageOf }, { file: file.fileName, node: declaration }),
6275
+ ...(owner === undefined ? [] : (modulesByPackage().get(owner) ?? [])),
6276
+ ];
6277
+ for (const module of new Set(candidates)) {
6278
+ if (module === undefined)
6279
+ continue;
6280
+ const name = names.nameOf(module, declaration);
6281
+ if (name !== undefined) {
6282
+ return { kind: "named", module, name, platform: isPlatformModule(module) };
6283
+ }
6284
+ }
6285
+ return way.module === undefined
6286
+ ? { kind: "unnamed" }
6287
+ : { kind: "unnamed", through: way.module };
6288
+ };
6289
+ return (declaration, reference) => {
6290
+ const root = referenceRoot(reference);
6291
+ const symbol = root === undefined ? undefined : checker().getSymbolAtLocation(root);
6292
+ // The answer depends on the import the reference comes through, else on its file's imports.
6293
+ const key = symbol !== undefined && (symbol.flags & ts.SymbolFlags.Alias) !== 0
6294
+ ? symbol
6295
+ : reference.getSourceFile();
6296
+ let answers = known.get(declaration);
6297
+ if (answers === undefined) {
6298
+ answers = new Map();
6299
+ known.set(declaration, answers);
6300
+ }
6301
+ const cached = answers.get(key);
6302
+ if (cached !== undefined)
6303
+ return cached;
6304
+ const found = search(declaration, reference);
6305
+ answers.set(key, found);
6306
+ return found;
4856
6307
  };
4857
6308
  }
4858
6309
  /**