@stateward/core 1.2.1 → 1.3.0

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/program-record.d.ts +7 -0
  4. package/dist/backend/typescript6.d.ts +35 -32
  5. package/dist/backend/typescript6.js +3804 -163
  6. package/dist/baseline.d.ts +1 -1
  7. package/dist/baseline.js +14 -10
  8. package/dist/cache.d.ts +89 -5
  9. package/dist/cache.js +271 -40
  10. package/dist/checker.d.ts +11 -1
  11. package/dist/checker.js +32 -2
  12. package/dist/class-id.d.ts +34 -0
  13. package/dist/class-id.js +93 -0
  14. package/dist/code-text.d.ts +8 -0
  15. package/dist/code-text.js +66 -0
  16. package/dist/config-file.js +7 -5
  17. package/dist/config.d.ts +10 -2
  18. package/dist/config.js +541 -49
  19. package/dist/define.d.ts +8 -2
  20. package/dist/disk-cache.d.ts +2 -0
  21. package/dist/disk-cache.js +77 -11
  22. package/dist/engine.d.ts +51 -1
  23. package/dist/engine.js +517 -42
  24. package/dist/fact-lines.d.ts +31 -0
  25. package/dist/fact-lines.js +197 -0
  26. package/dist/facts-versions.d.ts +27 -0
  27. package/dist/facts-versions.js +99 -0
  28. package/dist/fixes.js +9 -4
  29. package/dist/guarantees.d.ts +63 -11
  30. package/dist/guarantees.js +151 -21
  31. package/dist/ignores.d.ts +11 -0
  32. package/dist/ignores.js +74 -27
  33. package/dist/implementation.d.ts +0 -6
  34. package/dist/implementation.js +0 -17
  35. package/dist/index.d.ts +10 -9
  36. package/dist/index.js +14 -7
  37. package/dist/internal.d.ts +9 -5
  38. package/dist/internal.js +6 -3
  39. package/dist/lazy.d.ts +8 -1
  40. package/dist/lazy.js +27 -2
  41. package/dist/ledger.d.ts +77 -0
  42. package/dist/ledger.js +423 -0
  43. package/dist/off-by-default.d.ts +13 -0
  44. package/dist/off-by-default.js +15 -0
  45. package/dist/options.d.ts +21 -5
  46. package/dist/options.js +22 -7
  47. package/dist/package-facts.d.ts +211 -17
  48. package/dist/package-facts.js +520 -38
  49. package/dist/plan.d.ts +1 -1
  50. package/dist/plan.js +7 -2
  51. package/dist/release.d.ts +12 -21
  52. package/dist/release.js +28 -38
  53. package/dist/renamed.d.ts +22 -3
  54. package/dist/renamed.js +50 -16
  55. package/dist/rollout.js +7 -4
  56. package/dist/safe-calls.d.ts +26 -0
  57. package/dist/safe-calls.js +345 -0
  58. package/dist/severity.d.ts +1 -1
  59. package/dist/severity.js +17 -3
  60. package/dist/stated.d.ts +37 -0
  61. package/dist/stated.js +123 -0
  62. package/dist/test-runner.d.ts +18 -0
  63. package/dist/test-runner.js +483 -0
  64. package/dist/testing-tsc.d.ts +16 -0
  65. package/dist/testing-tsc.js +86 -0
  66. package/dist/testing.d.ts +5 -4
  67. package/dist/testing.js +6 -6
  68. package/dist/timing.d.ts +15 -0
  69. package/dist/timing.js +41 -2
  70. package/dist/types.d.ts +1068 -16
  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,16 @@
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";
7
8
  import { declarationAtPath, declarationPath } from "./qualified-ids.js";
8
9
  import { displayPath } from "../display-path.js";
9
10
  import { expandTsconfigs } from "../tsconfigs.js";
11
+ import { testRunnerFiles } from "../test-runner.js";
12
+ import { checkFactKeys, factGrainOf, factKeysDigest, pathOf, readFactKeyChecks, } from "../package-facts.js";
13
+ import { declaredPackageOf } from "../class-id.js";
10
14
  /** The tsconfig could not be read or is invalid. */
11
15
  export class TsconfigError extends Error {
12
16
  /** The one change that fixes it, shown on a `= fix:` line. */
@@ -493,6 +497,64 @@ function unresolvedImportsOf(program, file) {
493
497
  }
494
498
  return found;
495
499
  }
500
+ /**
501
+ * The package modules one file imports, as TypeScript reads its imports (not its text): import
502
+ * and export declarations, `import x = require(…)`, `import(…)`, `require(…)`, `import("…")`
503
+ * types, and the JSX runtime a file with JSX uses by the project's `jsx` option. Relative and
504
+ * absolute paths are left out: they name the project's own files.
505
+ */
506
+ export function importedModules(sourceFile, options) {
507
+ const found = new Set();
508
+ const add = (specifier) => {
509
+ if (specifier === undefined || !ts.isStringLiteralLike(specifier))
510
+ return;
511
+ const name = specifier.text;
512
+ if (name === "" || name.startsWith(".") || path.isAbsolute(name))
513
+ return;
514
+ found.add(name);
515
+ };
516
+ const seen = { jsx: false };
517
+ const visit = (node) => {
518
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
519
+ add(node.moduleSpecifier);
520
+ }
521
+ else if (ts.isExternalModuleReference(node)) {
522
+ add(node.expression);
523
+ }
524
+ else if (ts.isImportTypeNode(node)) {
525
+ const argument = node.argument;
526
+ if (ts.isLiteralTypeNode(argument))
527
+ add(argument.literal);
528
+ }
529
+ else if (ts.isCallExpression(node)) {
530
+ const [first] = node.arguments;
531
+ const dynamic = node.expression.kind === ts.SyntaxKind.ImportKeyword;
532
+ const required = ts.isIdentifier(node.expression) && node.expression.text === "require";
533
+ if (dynamic || required)
534
+ add(first);
535
+ }
536
+ else if (ts.isJsxElement(node) ||
537
+ ts.isJsxSelfClosingElement(node) ||
538
+ ts.isJsxFragment(node)) {
539
+ seen.jsx = true;
540
+ }
541
+ ts.forEachChild(node, visit);
542
+ };
543
+ visit(sourceFile);
544
+ if (seen.jsx) {
545
+ if (options.jsx === ts.JsxEmit.ReactJSX || options.jsx === ts.JsxEmit.ReactJSXDev) {
546
+ found.add(`${options.jsxImportSource ?? "react"}/jsx-runtime`);
547
+ }
548
+ else if (options.jsx === ts.JsxEmit.React && options.jsxFactory === undefined) {
549
+ found.add("react");
550
+ }
551
+ }
552
+ return [...found].sort();
553
+ }
554
+ /** Whether `imported` (as `importedModules` gives them) names `module` or one of its subpaths. */
555
+ export function importsModuleIn(imported, module) {
556
+ return imported.some((name) => name === module || name.startsWith(`${module}/`));
557
+ }
496
558
  /** Whether a project with these options checks with `strictNullChecks` (TypeScript 6: on unless turned off). */
497
559
  export function checksNulls(options) {
498
560
  return options.strictNullChecks ?? options.strict ?? true;
@@ -583,10 +645,7 @@ function readTsconfig(given) {
583
645
  const libraryCache = new Map();
584
646
  const DEFAULT_LIB_DIRECTORY = toTypeScriptPath(path.dirname(ts.getDefaultLibFilePath({})));
585
647
  function isLibraryFile(fileName) {
586
- return isTypeScriptLib(fileName) || fileName.includes("/node_modules/");
587
- }
588
- function isTypeScriptLib(fileName) {
589
- return fileName.startsWith(DEFAULT_LIB_DIRECTORY);
648
+ return fileName.startsWith(DEFAULT_LIB_DIRECTORY) || fileName.includes("/node_modules/");
590
649
  }
591
650
  /**
592
651
  * What decides whether a cached source file still fits: how it is parsed. The options object
@@ -618,13 +677,7 @@ export function hostWithOverlays(options, overlays, cache,
618
677
  /** Serve a file that is not in `overlays` from `cache` without reading it from disk. */
619
678
  trustCache = false,
620
679
  /** 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) {
680
+ jsDoc = false) {
628
681
  const base = ts.createCompilerHost(options, true);
629
682
  return {
630
683
  ...base,
@@ -641,7 +694,7 @@ shared = isLibraryFile) {
641
694
  ? { ...requested, jsDocParsingMode: ts.JSDocParsingMode.ParseForTypeErrors }
642
695
  : requested;
643
696
  const optionsKey = parseKey(languageVersionOrOptions, options);
644
- const store = shared(fileName) ? libraryCache : cache;
697
+ const store = library ? libraryCache : cache;
645
698
  // By parse settings and name: two projects (a Vite app and its node config) read the same
646
699
  // library file with different settings, and one entry per name made each evict the other,
647
700
  // so every program parsed TypeScript's lib files and @types/react again.
@@ -693,7 +746,9 @@ function matcher(patterns) {
693
746
  return picomatch([...patterns], { dot: true });
694
747
  }
695
748
  /** The files of `parsed` that stateward checks and no earlier project has claimed. */
696
- function ownFileNames(parsed, config, cwd, claimed) {
749
+ function ownFileNames(parsed, config, cwd, claimed,
750
+ /** Whether a file is a test by the project's test-runner config (`test-runner.ts`). */
751
+ isTest) {
697
752
  const included = matcher(config.include);
698
753
  const excluded = matcher(config.exclude);
699
754
  const own = [];
@@ -702,7 +757,7 @@ function ownFileNames(parsed, config, cwd, claimed) {
702
757
  continue;
703
758
  const relative = path.relative(cwd, file).split(path.sep).join("/");
704
759
  const generated = file.endsWith(".d.ts") || file.includes("/node_modules/");
705
- if (!generated && included(relative) && !excluded(relative))
760
+ if (!generated && included(relative) && !excluded(relative) && !isTest(file))
706
761
  own.push(file);
707
762
  }
708
763
  return own;
@@ -724,6 +779,207 @@ function isArrayLike(checker, type) {
724
779
  return false;
725
780
  return (checker.getTypeOfSymbol(length).flags & ts.TypeFlags.NumberLike) !== 0;
726
781
  }
782
+ /** `TypeQueries.instanceClassesOf`: the classes an awaited type holds, through unions, arrays and wrappers. */
783
+ function instanceClassesOfType(checker, start, depth) {
784
+ const classes = [];
785
+ let any = false;
786
+ const seen = new Set();
787
+ const visit = (type, path, left, whole = true) => {
788
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
789
+ any = true;
790
+ return;
791
+ }
792
+ if (seen.has(type))
793
+ return;
794
+ seen.add(type);
795
+ const awaited = checker.getAwaitedType(type);
796
+ if (awaited !== undefined && awaited !== type) {
797
+ visit(awaited, path, left, whole);
798
+ return;
799
+ }
800
+ if (type.isUnionOrIntersection()) {
801
+ // A class in an intersection (`User & { orders: Order[] }`) is part of the value's type.
802
+ const part = whole && !type.isIntersection();
803
+ for (const member of type.types)
804
+ visit(member, path, left, part);
805
+ return;
806
+ }
807
+ if (!(type.flags & ts.TypeFlags.Object))
808
+ return;
809
+ if (checker.isArrayType(type) || checker.isTupleType(type)) {
810
+ if (!isTypeReference(type))
811
+ return;
812
+ for (const element of checker.getTypeArguments(type))
813
+ visit(element, `${path}[]`, left);
814
+ return;
815
+ }
816
+ const symbol = type.getSymbol();
817
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
818
+ if (symbol !== undefined && declaration !== undefined) {
819
+ // The instance side only: `typeof User` (the constructor) has the same symbol.
820
+ const instance = isTypeReference(type) ? type.target : type;
821
+ if (instance === checker.getDeclaredTypeOfSymbol(symbol)) {
822
+ classes.push({ name: symbol.getName(), declaration, path, whole });
823
+ }
824
+ return;
825
+ }
826
+ if (left <= 0 || type.getCallSignatures().length > 0)
827
+ return;
828
+ for (const property of checker.getPropertiesOfType(type)) {
829
+ const name = property.getName();
830
+ visit(checker.getTypeOfSymbol(property), path === "" ? name : `${path}.${name}`, left - 1);
831
+ }
832
+ };
833
+ visit(start, "", depth);
834
+ return { classes, any };
835
+ }
836
+ /** How many base types `genericBaseOf` reads above the type itself. */
837
+ const GENERIC_BASE_DEPTH = 8;
838
+ /**
839
+ * `TypeQueries.genericBaseOf`: the nearest generic base of a package, with its type arguments,
840
+ * through `this` and type parameters (their constraint) and the members of an intersection. A
841
+ * base written with the subclass's own type parameter (`class Base<T> extends Repository<T>`) is
842
+ * given the argument the value's type gives that parameter (`Base<User>` gives `User`).
843
+ */
844
+ function genericBaseOfType(checker, start, inPackage, names) {
845
+ const members = start.isUnion()
846
+ ? start.types.filter((one) => !(one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
847
+ : [start];
848
+ const [only] = members;
849
+ if (only === undefined || members.length > 1)
850
+ return undefined;
851
+ const argumentOf = (type) => {
852
+ const symbol = type.getSymbol();
853
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
854
+ const instance = isTypeReference(type) ? type.target : type;
855
+ return symbol !== undefined &&
856
+ declaration !== undefined &&
857
+ instance === checker.getDeclaredTypeOfSymbol(symbol)
858
+ ? { kind: "class", name: symbol.getName(), declaration }
859
+ : { kind: "other", text: checker.typeToString(type) };
860
+ };
861
+ const seen = new Set();
862
+ let level = [{ type: only, given: new Map() }];
863
+ for (let depth = 0; depth <= GENERIC_BASE_DEPTH && level.length > 0; depth++) {
864
+ const next = [];
865
+ for (const { type, given } of level) {
866
+ if (seen.has(type))
867
+ continue;
868
+ seen.add(type);
869
+ // `this` in a class's method, or a type parameter: read its constraint (the class itself).
870
+ if (type.flags & ts.TypeFlags.TypeParameter) {
871
+ const constraint = checker.getBaseConstraintOfType(type);
872
+ if (constraint !== undefined && constraint !== type)
873
+ next.push({ type: constraint, given });
874
+ continue;
875
+ }
876
+ // `getRepository(User).extend({ … })` gives `Repository<User> & { … }`: read each member.
877
+ if (type.isIntersection()) {
878
+ for (const member of type.types)
879
+ next.push({ type: member, given });
880
+ continue;
881
+ }
882
+ const written = isTypeReference(type) ? checker.getTypeArguments(type) : [];
883
+ const actual = written.map((one) => given.get(one) ?? one);
884
+ const symbol = type.getSymbol();
885
+ if (symbol !== undefined && names.has(symbol.getName()) && inPackage(symbol)) {
886
+ return { name: symbol.getName(), typeArguments: actual.map(argumentOf) };
887
+ }
888
+ const target = isTypeReference(type) ? type.target : type;
889
+ if (!target.isClassOrInterface())
890
+ continue;
891
+ const parameters = target.typeParameters ?? [];
892
+ const passed = new Map();
893
+ parameters.forEach((parameter, index) => {
894
+ const argument = actual[index];
895
+ if (argument !== undefined)
896
+ passed.set(parameter, argument);
897
+ });
898
+ for (const base of checker.getBaseTypes(target))
899
+ next.push({ type: base, given: passed });
900
+ }
901
+ level = next;
902
+ }
903
+ return undefined;
904
+ }
905
+ /**
906
+ * `TypeQueries.isOrExtends`: whether a type, or one of its base types up to `GENERIC_BASE_DEPTH`
907
+ * levels, is declared by one of `classes`. A class's own type (`typeof Store`) is read as its
908
+ * instances, `this` and a type parameter as their constraint, an intersection as its members.
909
+ */
910
+ function isOrExtendsType(checker, start, classes) {
911
+ const members = start.isUnion()
912
+ ? start.types.filter((one) => !(one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
913
+ : [start];
914
+ const [only] = members;
915
+ if (only === undefined || members.length > 1)
916
+ return false;
917
+ const seen = new Set();
918
+ let level = [only];
919
+ for (let depth = 0; depth <= GENERIC_BASE_DEPTH && level.length > 0; depth++) {
920
+ const next = [];
921
+ for (const type of level) {
922
+ if (seen.has(type))
923
+ continue;
924
+ seen.add(type);
925
+ if (type.flags & ts.TypeFlags.TypeParameter) {
926
+ const constraint = checker.getBaseConstraintOfType(type);
927
+ if (constraint !== undefined && constraint !== type)
928
+ next.push(constraint);
929
+ continue;
930
+ }
931
+ if (type.isIntersection()) {
932
+ next.push(...type.types);
933
+ continue;
934
+ }
935
+ const symbol = type.getSymbol();
936
+ if ((symbol?.declarations ?? []).some((declaration) => classes.has(declaration))) {
937
+ return true;
938
+ }
939
+ const target = isTypeReference(type) ? type.target : type;
940
+ if (target.isClassOrInterface()) {
941
+ next.push(...checker.getBaseTypes(target));
942
+ continue;
943
+ }
944
+ // A class read as a value (`Store.create()`): its static side, read as its instances.
945
+ if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Class) {
946
+ const instance = checker.getDeclaredTypeOfSymbol(symbol);
947
+ if (instance !== type)
948
+ next.push(instance);
949
+ }
950
+ }
951
+ level = next;
952
+ }
953
+ return false;
954
+ }
955
+ /** Whether a written type names a type parameter anywhere in it (`T`, `T[]`, `Promise<T>`, `T["id"]`). */
956
+ function holdsTypeParameter(checker, node) {
957
+ let found = false;
958
+ const visit = (current) => {
959
+ if (found)
960
+ return;
961
+ if (ts.isTypeReferenceNode(current) &&
962
+ checker.getTypeFromTypeNode(current).flags & ts.TypeFlags.TypeParameter) {
963
+ found = true;
964
+ return;
965
+ }
966
+ ts.forEachChild(current, visit);
967
+ };
968
+ visit(node);
969
+ return found;
970
+ }
971
+ /**
972
+ * Whether a declaration is in the global scope: in a `declare global` block, or in a file that is
973
+ * not a module (TypeScript's lib, a script `.d.ts`).
974
+ */
975
+ function isGlobalDeclaration(declaration) {
976
+ for (let node = declaration.parent;; node = node.parent) {
977
+ if (ts.isSourceFile(node))
978
+ return !ts.isExternalModule(node);
979
+ if (ts.isModuleDeclaration(node))
980
+ return (node.flags & ts.NodeFlags.GlobalAugmentation) !== 0;
981
+ }
982
+ }
727
983
  function compareLabels(a, b) {
728
984
  if (a.label < b.label)
729
985
  return -1;
@@ -759,6 +1015,36 @@ const PRIMITIVE_FLAGS = ts.TypeFlags.StringLike |
759
1015
  ts.TypeFlags.Null |
760
1016
  ts.TypeFlags.Undefined |
761
1017
  ts.TypeFlags.Void;
1018
+ /** An instantiated generic type: `Array<T>`, `Map<K, V>`, a tuple. */
1019
+ function isTypeReference(type) {
1020
+ return ((type.flags & ts.TypeFlags.Object) !== 0 &&
1021
+ "objectFlags" in type &&
1022
+ typeof type.objectFlags === "number" &&
1023
+ (type.objectFlags & ts.ObjectFlags.Reference) !== 0);
1024
+ }
1025
+ /** An object type written in place (`{ id: Id }`), not a class or an interface. */
1026
+ function isAnonymousObject(type) {
1027
+ return ((type.flags & ts.TypeFlags.Object) !== 0 &&
1028
+ "objectFlags" in type &&
1029
+ typeof type.objectFlags === "number" &&
1030
+ (type.objectFlags & ts.ObjectFlags.Anonymous) !== 0);
1031
+ }
1032
+ /** Which of TypeScript's own types `type` is, from its flags (`TypeQueries.builtinTypeOf`). */
1033
+ function builtinOf(type) {
1034
+ if ((type.flags & ts.TypeFlags.Any) !== 0)
1035
+ return "any";
1036
+ if ((type.flags & ts.TypeFlags.Unknown) !== 0)
1037
+ return "unknown";
1038
+ if ((type.flags & ts.TypeFlags.Never) !== 0)
1039
+ return "never";
1040
+ if ((type.flags & ts.TypeFlags.Void) !== 0)
1041
+ return "void";
1042
+ if ((type.flags & ts.TypeFlags.Undefined) !== 0)
1043
+ return "undefined";
1044
+ if ((type.flags & ts.TypeFlags.Null) !== 0)
1045
+ return "null";
1046
+ return undefined;
1047
+ }
762
1048
  function widened(checker, type) {
763
1049
  return type.isTypeParameter() ? checker.getBaseConstraintOfType(type) : type;
764
1050
  }
@@ -801,6 +1087,26 @@ function isPromiseType(checker, type) {
801
1087
  const awaited = checker.getAwaitedType(type);
802
1088
  return awaited !== undefined && awaited !== type;
803
1089
  }
1090
+ /** A type that stands for another one not known where it is declared (`T`, `T[K]`, `T extends U ? X : Y`). */
1091
+ const STANDS_FOR_ANOTHER = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.InstantiableNonPrimitive;
1092
+ /**
1093
+ * Whether a value of the type can be a promise: a promise-like type, `any`, `unknown`, a type
1094
+ * parameter or a type built on one, a type the global `Promise` is assignable to (`object`,
1095
+ * `{}`), or a union or an intersection with such a member.
1096
+ */
1097
+ function mayBePromiseType(checker, type) {
1098
+ if (type.flags & STANDS_FOR_ANOTHER)
1099
+ return true;
1100
+ if (type.isUnion())
1101
+ return type.types.some((part) => mayBePromiseType(checker, part));
1102
+ if (type.isIntersection())
1103
+ return type.types.some((part) => mayBePromiseType(checker, part));
1104
+ if (isPromiseType(checker, type))
1105
+ return true;
1106
+ const promise = checker.resolveName("Promise", undefined, ts.SymbolFlags.Type, false);
1107
+ return (promise !== undefined &&
1108
+ checker.isTypeAssignableTo(checker.getDeclaredTypeOfSymbol(promise), type));
1109
+ }
804
1110
  const NULLISH = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
805
1111
  /** The property a stated guarantee is written in by 1.1.0 (`__guarantee?: "owned"`). */
806
1112
  const GUARANTEE_PROPERTY = "__guarantee";
@@ -823,6 +1129,128 @@ function declaresMarkerProperty(file, marker) {
823
1129
  visit(file);
824
1130
  return found;
825
1131
  }
1132
+ /** Whether a property name is a marker's: `"__guarantee:<name>"`, or the 1.1.0 `__guarantee`. */
1133
+ function isMarkerName(name) {
1134
+ if (!(ts.isStringLiteral(name) || ts.isIdentifier(name)))
1135
+ return false;
1136
+ return name.text === GUARANTEE_PROPERTY || name.text.startsWith(GUARANTEE_PREFIX);
1137
+ }
1138
+ /** Whether `file` writes any marker property in a type or class (a quick text filter first). */
1139
+ function declaresAnyMarker(file) {
1140
+ if (!file.text.includes(GUARANTEE_PROPERTY))
1141
+ return false;
1142
+ let found = false;
1143
+ const visit = (node) => {
1144
+ if (found)
1145
+ return;
1146
+ if ((ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) &&
1147
+ isMarkerName(node.name)) {
1148
+ found = true;
1149
+ return;
1150
+ }
1151
+ ts.forEachChild(node, visit);
1152
+ };
1153
+ visit(file);
1154
+ return found;
1155
+ }
1156
+ /** Whether a written type defines a marker itself (`T & { "__guarantee:owned"?: true }`). */
1157
+ function definesMarker(type) {
1158
+ let found = false;
1159
+ const visit = (node) => {
1160
+ if (found)
1161
+ return;
1162
+ if (ts.isPropertySignature(node) && isMarkerName(node.name)) {
1163
+ found = true;
1164
+ return;
1165
+ }
1166
+ ts.forEachChild(node, visit);
1167
+ };
1168
+ visit(type);
1169
+ return found;
1170
+ }
1171
+ /**
1172
+ * The declarations of a file whose written type states a guarantee, in source order
1173
+ * (`TypeQueries.statedDeclarationsIn`). A function's return type is not one: what it states
1174
+ * (`Owned<…>`) reaches the code through each call, which a rule reads there.
1175
+ */
1176
+ function statedDeclarationsOf(checker, sourceFile) {
1177
+ const found = [];
1178
+ const guaranteesOfNode = (type) => definesMarker(type) ? [] : guaranteesOfType(checker, checker.getTypeFromTypeNode(type));
1179
+ /** The first reference in the annotation that states a guarantee: where the marker is written. */
1180
+ const markerReference = (type) => {
1181
+ let found;
1182
+ const visit = (node) => {
1183
+ if (found !== undefined)
1184
+ return;
1185
+ if (ts.isTypeReferenceNode(node) &&
1186
+ ts.isIdentifier(node.typeName) &&
1187
+ guaranteesOfNode(node).length > 0) {
1188
+ found = node;
1189
+ return;
1190
+ }
1191
+ ts.forEachChild(node, visit);
1192
+ };
1193
+ visit(type);
1194
+ return found;
1195
+ };
1196
+ /**
1197
+ * Whether a reference is to a type alias that states the guarantee itself (`type OrderStatus =
1198
+ * OpenUnion<…>`): the alias is the declaration that states it, and each use of it is a use.
1199
+ */
1200
+ const refersToStatedAlias = (reference) => {
1201
+ const found = checker.getSymbolAtLocation(reference.typeName);
1202
+ const symbol = found !== undefined && found.flags & ts.SymbolFlags.Alias
1203
+ ? checker.getAliasedSymbol(found)
1204
+ : found;
1205
+ return (symbol?.declarations?.some((declaration) => ts.isTypeAliasDeclaration(declaration) &&
1206
+ declaration.typeParameters === undefined &&
1207
+ guaranteesOfNode(declaration.type).length > 0) === true);
1208
+ };
1209
+ const add = (node, type, name) => {
1210
+ // `o: typeof settings` names the type of a stated value; it states nothing of its own.
1211
+ if (type === undefined || name === undefined || ts.isTypeQueryNode(type))
1212
+ return;
1213
+ const names = guaranteesOfNode(type);
1214
+ if (names.length === 0)
1215
+ return;
1216
+ const reference = markerReference(type);
1217
+ if (reference !== undefined && refersToStatedAlias(reference))
1218
+ return;
1219
+ found.push({
1220
+ file: sourceFile.fileName,
1221
+ start: node.getStart(sourceFile),
1222
+ headEnd: type.end,
1223
+ end: node.end,
1224
+ name: name.getText(sourceFile),
1225
+ marker: reference === undefined ? (names[0] ?? "") : reference.typeName.getText(sourceFile),
1226
+ guarantees: names,
1227
+ });
1228
+ };
1229
+ const hasBody = (node) => (ts.isFunctionDeclaration(node) ||
1230
+ ts.isMethodDeclaration(node) ||
1231
+ ts.isArrowFunction(node) ||
1232
+ ts.isFunctionExpression(node) ||
1233
+ ts.isConstructorDeclaration(node)) &&
1234
+ node.body !== undefined;
1235
+ const visit = (node) => {
1236
+ if (ts.isVariableDeclaration(node)) {
1237
+ add(node, node.type, ts.isIdentifier(node.name) ? node.name : undefined);
1238
+ }
1239
+ else if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node)) {
1240
+ add(node, node.type, node.name);
1241
+ }
1242
+ else if (ts.isParameter(node)) {
1243
+ if (ts.isIdentifier(node.name) && hasBody(node.parent))
1244
+ add(node, node.type, node.name);
1245
+ }
1246
+ else if (ts.isTypeAliasDeclaration(node) && node.typeParameters === undefined) {
1247
+ add(node, node.type, node.name);
1248
+ }
1249
+ ts.forEachChild(node, visit);
1250
+ };
1251
+ visit(sourceFile);
1252
+ return found;
1253
+ }
826
1254
  /** Adds the `as` names a file's import and export specifiers give: `onSnapshot` → `listen`. */
827
1255
  function addRenamed(file, renamed) {
828
1256
  const add = (specifier) => {
@@ -964,20 +1392,21 @@ function guaranteesOfType(checker, found) {
964
1392
  return [...new Set(shared ?? [])].sort();
965
1393
  }
966
1394
  /**
967
- * The literals of the `"__guarantee:<name>"` property of `type` (its first member that states it),
968
- * without the `undefined` the optional property adds; undefined when no member states it.
1395
+ * The literals of the optional property `property` of `type` (its first member that states it),
1396
+ * without the `undefined` the optional property adds; undefined when no member states it. A
1397
+ * guarantee's is `"__guarantee:<name>"`.
969
1398
  */
970
- function guaranteeValuesOfType(checker, found, name) {
1399
+ function markerValuesOfType(checker, found, property) {
971
1400
  const type = widened(checker, found);
972
1401
  if (type === undefined)
973
1402
  return undefined;
974
1403
  for (const member of type.isUnion() ? type.types : [type]) {
975
1404
  if (member.flags & NULLISH)
976
1405
  continue;
977
- const property = checker.getPropertyOfType(member, `${GUARANTEE_PREFIX}${name}`);
978
- if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
1406
+ const marker = checker.getPropertyOfType(member, property);
1407
+ if (marker === undefined || !(marker.flags & ts.SymbolFlags.Optional))
979
1408
  continue;
980
- const value = checker.getTypeOfSymbol(property);
1409
+ const value = checker.getTypeOfSymbol(marker);
981
1410
  const literals = [];
982
1411
  for (const part of value.isUnion() ? value.types : [value]) {
983
1412
  if (part.flags & ts.TypeFlags.Undefined)
@@ -1363,6 +1792,147 @@ function signalParameter(checker, call) {
1363
1792
  }
1364
1793
  return undefined;
1365
1794
  }
1795
+ /** As `TypeQueries.parameterTakesUnknown`. */
1796
+ function takesUnknown(checker, call, index) {
1797
+ if (call.arguments.slice(0, index + 1).some(ts.isSpreadElement))
1798
+ return false;
1799
+ const declaration = checker.getResolvedSignature(call)?.getDeclaration();
1800
+ if (declaration === undefined || ts.isJSDocSignature(declaration))
1801
+ return false;
1802
+ const parameter = declaration.parameters[index];
1803
+ if (parameter === undefined || parameter.dotDotDotToken !== undefined)
1804
+ return false;
1805
+ // The declared type, before the call's type arguments replace a type parameter.
1806
+ const type = checker.getTypeAtLocation(parameter);
1807
+ if (type.flags & ts.TypeFlags.Unknown)
1808
+ return true;
1809
+ if (!type.isTypeParameter())
1810
+ return false;
1811
+ // Only the function's own type parameter: a class's (`Map<K, V>.set`) is fixed by the instance.
1812
+ const owner = type.getSymbol()?.declarations?.[0]?.parent;
1813
+ if (owner !== declaration)
1814
+ return false;
1815
+ const constraint = type.getConstraint();
1816
+ return constraint === undefined || (constraint.flags & ts.TypeFlags.Unknown) !== 0;
1817
+ }
1818
+ /** Whether a declaration is, or is written inside, a type, interface or class with type parameters. */
1819
+ function insideGeneric(declaration) {
1820
+ for (let at = declaration; !ts.isSourceFile(at); at = at.parent) {
1821
+ if ((ts.isTypeAliasDeclaration(at) || ts.isInterfaceDeclaration(at) || ts.isClassLike(at)) &&
1822
+ (at.typeParameters ?? []).length > 0) {
1823
+ return true;
1824
+ }
1825
+ }
1826
+ return false;
1827
+ }
1828
+ /** How deep `typeShape` follows nested object types before it gives up. */
1829
+ const SHAPE_DEPTH = 8;
1830
+ /** As `TypeQueries.typeShapeOf`, for a type; `inside` holds the object types being read. */
1831
+ function typeShape(isPlatformFile, checker, type, inside) {
1832
+ if (inside.length > SHAPE_DEPTH)
1833
+ return undefined;
1834
+ if (type.flags & ts.TypeFlags.EnumLike)
1835
+ return undefined;
1836
+ if (type.isUnion()) {
1837
+ const members = [];
1838
+ let booleans = 0;
1839
+ for (const member of type.types) {
1840
+ if (member.flags & ts.TypeFlags.BooleanLiteral) {
1841
+ booleans += 1;
1842
+ continue;
1843
+ }
1844
+ const shape = typeShape(isPlatformFile, checker, member, inside);
1845
+ if (shape === undefined)
1846
+ return undefined;
1847
+ members.push(shape);
1848
+ }
1849
+ // `boolean` is `true | false` to the checker; a check tests it with `typeof`.
1850
+ if (booleans === 2)
1851
+ members.push({ kind: "primitive", name: "boolean" });
1852
+ else if (booleans === 1) {
1853
+ const literal = type.types.find((member) => member.flags & ts.TypeFlags.BooleanLiteral);
1854
+ const shape = literal === undefined ? undefined : typeShape(isPlatformFile, checker, literal, inside);
1855
+ if (shape === undefined)
1856
+ return undefined;
1857
+ members.push(shape);
1858
+ }
1859
+ return members.length === 1 && members[0] !== undefined
1860
+ ? members[0]
1861
+ : { kind: "union", members };
1862
+ }
1863
+ if (type.flags & ts.TypeFlags.Boolean)
1864
+ return { kind: "primitive", name: "boolean" };
1865
+ const literal = literalOf(checker, type);
1866
+ if (literal !== undefined && !(type.flags & ts.TypeFlags.Intersection)) {
1867
+ return { kind: "literal", literal };
1868
+ }
1869
+ if (type.flags & ts.TypeFlags.String)
1870
+ return { kind: "primitive", name: "string" };
1871
+ if (type.flags & ts.TypeFlags.Number)
1872
+ return { kind: "primitive", name: "number" };
1873
+ if (type.flags & ts.TypeFlags.BigInt)
1874
+ return { kind: "primitive", name: "bigint" };
1875
+ if (!(type.flags & ts.TypeFlags.Object) || type.isIntersection())
1876
+ return undefined;
1877
+ if (checker.isArrayType(type) && isTypeReference(type)) {
1878
+ const [element] = checker.getTypeArguments(type);
1879
+ const shape = element === undefined
1880
+ ? undefined
1881
+ : typeShape(isPlatformFile, checker, element, [...inside, type]);
1882
+ return shape === undefined ? undefined : { kind: "array", element: shape };
1883
+ }
1884
+ if (checker.isTupleType(type))
1885
+ return undefined;
1886
+ if (isTypeReference(type) && checker.getTypeArguments(type).length > 0)
1887
+ return undefined;
1888
+ if ((type.aliasTypeArguments ?? []).length > 0)
1889
+ return undefined;
1890
+ if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) {
1891
+ return undefined;
1892
+ }
1893
+ if (checker.getIndexInfosOfType(type).length > 0)
1894
+ return undefined;
1895
+ const symbol = type.getSymbol();
1896
+ const declarations = symbol?.declarations ?? [];
1897
+ if (declarations.some((one) => isPlatformFile(one.getSourceFile()))) {
1898
+ return undefined;
1899
+ }
1900
+ const named = type.aliasSymbol?.getName() ?? symbol?.getName();
1901
+ const name = named === undefined || named.startsWith("__") ? undefined : named;
1902
+ // The type's identity: two types of one name (`billing.Address`, `shipping.Address`) differ.
1903
+ const first = declarations[0];
1904
+ const id = first === undefined
1905
+ ? checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation)
1906
+ : `${first.getSourceFile().fileName}:${String(first.pos)}`;
1907
+ if (inside.includes(type)) {
1908
+ return name === undefined ? undefined : { kind: "recursive", id, name };
1909
+ }
1910
+ const hidden = declarations.some((one) => ts.isClassLike(one) &&
1911
+ one.members.some((member) => (member.name !== undefined && ts.isPrivateIdentifier(member.name)) ||
1912
+ (ts.getCombinedModifierFlags(member) &
1913
+ (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) !==
1914
+ 0));
1915
+ if (hidden || declarations.some(insideGeneric))
1916
+ return undefined;
1917
+ const properties = [];
1918
+ for (const property of checker.getPropertiesOfType(type)) {
1919
+ if (property.flags & (ts.SymbolFlags.Method | ts.SymbolFlags.Accessor))
1920
+ return undefined;
1921
+ const shape = typeShape(isPlatformFile, checker, checker.getTypeOfSymbol(property), [
1922
+ ...inside,
1923
+ type,
1924
+ ]);
1925
+ if (shape === undefined)
1926
+ return undefined;
1927
+ properties.push({
1928
+ name: property.getName(),
1929
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
1930
+ shape,
1931
+ });
1932
+ }
1933
+ const text = name ?? checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation);
1934
+ return { kind: "object", id, name, text: text.replace(/\s+/g, " ").trim(), properties };
1935
+ }
1366
1936
  function withoutNullish(type) {
1367
1937
  const nothing = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
1368
1938
  return (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & nothing));
@@ -1397,6 +1967,37 @@ function isReadonlyChain(checker, node) {
1397
1967
  }
1398
1968
  return segments > 0;
1399
1969
  }
1970
+ /** See `TypeQueries.propIsDeeplyReadonly`: no part of a value of this type can be changed. */
1971
+ function isDeeplyReadonly(checker, type, depth) {
1972
+ if (depth > 6)
1973
+ return false;
1974
+ const resolved = widened(checker, type);
1975
+ if (resolved === undefined)
1976
+ return false;
1977
+ if (resolved.flags & (PRIMITIVE_FLAGS | ts.TypeFlags.Never | ts.TypeFlags.ESSymbolLike)) {
1978
+ return true;
1979
+ }
1980
+ if (resolved.isUnion() || resolved.isIntersection()) {
1981
+ return resolved.types.every((part) => isDeeplyReadonly(checker, part, depth + 1));
1982
+ }
1983
+ if (!(resolved.flags & ts.TypeFlags.Object))
1984
+ return false;
1985
+ if (checker.getSignaturesOfType(resolved, ts.SignatureKind.Call).length > 0)
1986
+ return false;
1987
+ if (checker.getSignaturesOfType(resolved, ts.SignatureKind.Construct).length > 0)
1988
+ return false;
1989
+ const indexes = checker.getIndexInfosOfType(resolved);
1990
+ if (resolved.getSymbol()?.getName() === "ReadonlyArray") {
1991
+ return (indexes.length > 0 &&
1992
+ indexes.every((info) => info.isReadonly && isDeeplyReadonly(checker, info.type, depth + 1)));
1993
+ }
1994
+ return (indexes.every((info) => info.isReadonly && isDeeplyReadonly(checker, info.type, depth + 1)) &&
1995
+ checker
1996
+ .getPropertiesOfType(resolved)
1997
+ .every((property) => !(property.flags & ts.SymbolFlags.Method) &&
1998
+ isReadonlyProperty(resolved, property) &&
1999
+ isDeeplyReadonly(checker, checker.getTypeOfSymbol(property), depth + 1)));
2000
+ }
1400
2001
  /** An object type, or a part of one, that a callee could write to or call a method of. */
1401
2002
  function isWritableObject(checker, type) {
1402
2003
  const resolved = widened(checker, type);
@@ -1499,49 +2100,2254 @@ export function idFileNames(root) {
1499
2100
  return name;
1500
2101
  };
1501
2102
  }
2103
+ /** The type questions the flow scan asks in one file before it stops (`TypeQueries.typedFlowsIn`). */
2104
+ export const FLOW_BUDGET = 200_000;
2105
+ /** How deep a type is searched for a stated alias: `Promise<Order>` → `Order` → `id: OrderId`. */
2106
+ const FLOW_DEPTH = 3;
2107
+ /** The words of a reference's text: one line, at most this long. */
2108
+ const REFERENCE_TEXT_MAX = 60;
2109
+ /** A JSDoc tag as one line, without the end of the comment: `@throws {AErr}`. */
2110
+ function tagText(tag, sourceFile) {
2111
+ const [first = ""] = sourceFile.text.slice(tag.getStart(sourceFile), tag.end).split("\n");
2112
+ const text = first
2113
+ .replace(/\*\/.*$/, "")
2114
+ .replace(/\s+/g, " ")
2115
+ .trim();
2116
+ return text.length <= REFERENCE_TEXT_MAX ? text : `${text.slice(0, REFERENCE_TEXT_MAX - 1)}…`;
2117
+ }
2118
+ function shortText(node, sourceFile) {
2119
+ const text = codeOnOneLine(node.getText(sourceFile));
2120
+ return text.length <= REFERENCE_TEXT_MAX ? text : `${text.slice(0, REFERENCE_TEXT_MAX - 1)}…`;
2121
+ }
2122
+ function isWrapperExpression(node) {
2123
+ return (ts.isParenthesizedExpression(node) ||
2124
+ ts.isAsExpression(node) ||
2125
+ ts.isSatisfiesExpression(node) ||
2126
+ ts.isNonNullExpression(node) ||
2127
+ ts.isTypeAssertionExpression(node));
2128
+ }
2129
+ function isAssignmentOperator(kind) {
2130
+ return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
2131
+ }
2132
+ /** Whether `node` sits in a type (`typeof x` in an annotation, `x` in `implements x`). */
2133
+ function inTypePosition(node) {
2134
+ for (let at = node; !ts.isSourceFile(at.parent); at = at.parent) {
2135
+ const parent = at.parent;
2136
+ if (ts.isExpressionWithTypeArguments(parent)) {
2137
+ const clause = parent.parent;
2138
+ return ts.isHeritageClause(clause) && clause.token === ts.SyntaxKind.ImplementsKeyword;
2139
+ }
2140
+ if (ts.isTypeNode(parent))
2141
+ return true;
2142
+ if (ts.isStatement(parent) || ts.isExpression(parent))
2143
+ return false;
2144
+ }
2145
+ return false;
2146
+ }
1502
2147
  /**
1503
- * TypeScript's errors for a function whose end can be reached although it must return a value:
1504
- * TS2366, TS2355, TS2534 and TS7030 (`TypeQueries.reportsReachableEnd`).
2148
+ * The form of a reference at `node`, and the node whose text shows it. A reference that names a
2149
+ * member (`a.watch`) or an element key (`a["watch"]`) is the access around it.
1505
2150
  */
1506
- const REACHABLE_END_CODES = new Set([2366, 2355, 2534, 7030]);
1507
- export function createTypeQueries(program, own,
1508
- /** The project folder qualified ids are relative to. */
1509
- root, packageOf, isEntry, dependenciesOf) {
1510
- // The only place in the codebase that reaches the type checker. Created on the first question:
1511
- // a run whose results all come from the cache never builds one.
1512
- let created;
1513
- const typeChecker = () => (created ??= program.getTypeChecker());
1514
- const declarations = new Map();
1515
- const declaredTraits = new Map();
1516
- // The starts of TypeScript's "end of the function can be reached" errors, per file asked about.
1517
- const reachableEndErrors = new WeakMap();
1518
- let declaredDispose;
1519
- let renamedNames;
1520
- const idFileName = idFileNames(root);
1521
- // symbolAt is asked about the same node by several rules (on excalidraw 570,000 questions about
1522
- // 170,000 nodes, 52,000 symbols): the program does not change under these queries, so each
1523
- // node's answer and each symbol's ref are computed once.
1524
- const refsByNode = new WeakMap();
1525
- const refsBySymbol = new WeakMap();
1526
- const refOfSymbol = (symbol) => {
1527
- const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
1528
- if (declaration === undefined)
1529
- return undefined;
1530
- const id = `${idFileName(declaration.getSourceFile().fileName)}#${declarationPath(declaration)}`;
1531
- declarations.set(id, declaration);
1532
- return { id, name: symbol.getName() };
1533
- };
1534
- const refAnswer = (node) => {
1535
- const found = typeChecker().getSymbolAtLocation(node);
1536
- if (found === undefined)
1537
- return NO_REF;
2151
+ function referenceForm(node) {
2152
+ const parent = node.parent;
2153
+ if (inTypePosition(node))
2154
+ return { form: "type", shown: node };
2155
+ if (ts.isImportSpecifier(parent) ||
2156
+ ts.isImportClause(parent) ||
2157
+ ts.isNamespaceImport(parent) ||
2158
+ ts.isImportEqualsDeclaration(parent)) {
2159
+ return { form: "import", shown: parent };
2160
+ }
2161
+ if (ts.isExportSpecifier(parent))
2162
+ return { form: "export", shown: parent };
2163
+ if (ts.isJsxAttribute(parent) && parent.name === node) {
2164
+ return { form: "jsx-attribute", shown: parent };
2165
+ }
2166
+ if (ts.isBindingElement(parent))
2167
+ return { form: "alias", shown: parent };
2168
+ if ((ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent)) && parent.name === node) {
2169
+ return { form: "write", shown: parent };
2170
+ }
2171
+ if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) {
2172
+ return { form: "stored", shown: parent.parent };
2173
+ }
2174
+ let outer = node;
2175
+ if ((ts.isPropertyAccessExpression(parent) && parent.name === node) ||
2176
+ (ts.isElementAccessExpression(parent) && parent.argumentExpression === node)) {
2177
+ outer = parent;
2178
+ }
2179
+ while (isWrapperExpression(outer.parent))
2180
+ outer = outer.parent;
2181
+ const at = outer.parent;
2182
+ if (ts.isJsxOpeningElement(at) || ts.isJsxSelfClosingElement(at) || ts.isJsxClosingElement(at)) {
2183
+ return { form: "jsx-tag", shown: at };
2184
+ }
2185
+ if (ts.isExportAssignment(at))
2186
+ return { form: "export", shown: at };
2187
+ if (((ts.isCallExpression(at) || ts.isNewExpression(at) || ts.isDecorator(at)) &&
2188
+ at.expression === outer) ||
2189
+ (ts.isTaggedTemplateExpression(at) && at.tag === outer)) {
2190
+ return { form: "call", shown: at };
2191
+ }
2192
+ if ((ts.isCallExpression(at) || ts.isNewExpression(at)) && at.expression !== outer) {
2193
+ return { form: "argument", shown: at };
2194
+ }
2195
+ if (ts.isSpreadElement(at) && (ts.isCallExpression(at.parent) || ts.isNewExpression(at.parent))) {
2196
+ return { form: "argument", shown: at.parent };
2197
+ }
2198
+ if (ts.isJsxExpression(at) || ts.isJsxSpreadAttribute(at)) {
2199
+ return { form: "argument", shown: at.parent };
2200
+ }
2201
+ if ((ts.isBinaryExpression(at) &&
2202
+ isAssignmentOperator(at.operatorToken.kind) &&
2203
+ at.left === outer) ||
2204
+ ((ts.isPrefixUnaryExpression(at) || ts.isPostfixUnaryExpression(at)) &&
2205
+ (at.operator === ts.SyntaxKind.PlusPlusToken ||
2206
+ at.operator === ts.SyntaxKind.MinusMinusToken)) ||
2207
+ ts.isDeleteExpression(at) ||
2208
+ ((ts.isForOfStatement(at) || ts.isForInStatement(at)) && at.initializer === outer)) {
2209
+ return { form: "write", shown: at };
2210
+ }
2211
+ if ((ts.isVariableDeclaration(at) ||
2212
+ ts.isPropertyDeclaration(at) ||
2213
+ ts.isParameter(at) ||
2214
+ ts.isBindingElement(at)) &&
2215
+ at.initializer === outer) {
2216
+ return { form: "alias", shown: at };
2217
+ }
2218
+ if (ts.isBinaryExpression(at) &&
2219
+ at.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
2220
+ at.right === outer) {
2221
+ return { form: "alias", shown: at };
2222
+ }
2223
+ if (ts.isArrayLiteralExpression(at) || ts.isSpreadAssignment(at)) {
2224
+ return { form: "stored", shown: ts.isSpreadAssignment(at) ? at.parent : at };
2225
+ }
2226
+ if (ts.isSpreadElement(at) && ts.isArrayLiteralExpression(at.parent)) {
2227
+ return { form: "stored", shown: at.parent };
2228
+ }
2229
+ if (ts.isPropertyAssignment(at) && at.initializer === outer) {
2230
+ return { form: "stored", shown: at.parent };
2231
+ }
2232
+ if (ts.isReturnStatement(at) ||
2233
+ ts.isYieldExpression(at) ||
2234
+ (ts.isArrowFunction(at) && at.body === outer)) {
2235
+ return { form: "returned", shown: at };
2236
+ }
2237
+ if (ts.isComputedPropertyName(at) ||
2238
+ (ts.isElementAccessExpression(at) && at.argumentExpression === outer)) {
2239
+ return { form: "computed", shown: at.parent };
2240
+ }
2241
+ if (ts.isConditionalExpression(at) && at.condition !== outer
2242
+ ? true
2243
+ : (ts.isBinaryExpression(at) &&
2244
+ (at.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken ||
2245
+ at.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
2246
+ at.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
2247
+ at.operatorToken.kind === ts.SyntaxKind.CommaToken)) ||
2248
+ (ts.isForOfStatement(at) && at.expression === outer)) {
2249
+ return { form: "other", shown: at };
2250
+ }
2251
+ if (ts.isPropertyAccessExpression(at) ||
2252
+ ts.isElementAccessExpression(at) ||
2253
+ ts.isConditionalExpression(at) ||
2254
+ ts.isBinaryExpression(at) ||
2255
+ ts.isPrefixUnaryExpression(at) ||
2256
+ ts.isPostfixUnaryExpression(at) ||
2257
+ ts.isTypeOfExpression(at) ||
2258
+ ts.isVoidExpression(at) ||
2259
+ ts.isAwaitExpression(at) ||
2260
+ ts.isTemplateSpan(at) ||
2261
+ ts.isExpressionStatement(at) ||
2262
+ ts.isIfStatement(at) ||
2263
+ ts.isWhileStatement(at) ||
2264
+ ts.isDoStatement(at) ||
2265
+ ts.isSwitchStatement(at) ||
2266
+ ts.isCaseClause(at) ||
2267
+ ts.isForInStatement(at) ||
2268
+ ts.isForStatement(at)) {
2269
+ return { form: "read", shown: at };
2270
+ }
2271
+ return { form: "other", shown: at };
2272
+ }
2273
+ /**
2274
+ * The reference ledger's scan of one program: which declarations state a trait (`statedOf`, by
2275
+ * symbol, memoised), and every reference to them in a file (`referencesIn`).
2276
+ */
2277
+ function createLedgerScan(program, typeChecker, isOwn, refOfSymbol) {
2278
+ const scans = new Map();
2279
+ const scanFor = (proves) => {
2280
+ const sorted = (list) => [...new Set(list ?? [])].sort();
2281
+ const traits = sorted(proves.traits);
2282
+ const returns = sorted(proves.returns);
2283
+ const made = sorted(proves.made);
2284
+ const holders = sorted(proves.holders);
2285
+ const produced = sorted(proves.flows?.produced);
2286
+ const decided = sorted(proves.flows?.decided);
2287
+ const escaped = sorted(proves.flows?.escaped);
2288
+ const tags = sorted(proves.tags);
2289
+ const key = JSON.stringify([traits, returns, made, holders, produced, decided, escaped, tags]);
2290
+ let scan = scans.get(key);
2291
+ if (scan === undefined) {
2292
+ scan = {
2293
+ traits: new Set(traits),
2294
+ returns: new Set(returns),
2295
+ made: new Set(made),
2296
+ holders: new Set(holders),
2297
+ produced: new Set(produced),
2298
+ decided: new Set(decided),
2299
+ escaped: new Set(escaped),
2300
+ tags: new Set(tags),
2301
+ tagged: new Map(),
2302
+ bySymbol: new Map(),
2303
+ names: undefined,
2304
+ targets: undefined,
2305
+ };
2306
+ scans.set(key, scan);
2307
+ }
2308
+ return scan;
2309
+ };
2310
+ /** The traits a type alias states for the flow scan: those of `produced` and `decided`. */
2311
+ const aliasTraits = (scan) => new Set([...scan.produced, ...scan.decided]);
2312
+ const writtenTraits = (type, wanted) => {
2313
+ if (definesMarker(type))
2314
+ return [];
2315
+ const checker = typeChecker();
2316
+ return guaranteesOfType(checker, checker.getTypeFromTypeNode(type)).filter((one) => wanted.has(one));
2317
+ };
2318
+ /** A rest parameter states a trait by its elements: `...stops: Owned<…>[]`. */
2319
+ const restTraits = (type, wanted) => {
2320
+ const checker = typeChecker();
2321
+ const element = checker.getIndexTypeOfType(checker.getTypeFromTypeNode(type), ts.IndexKind.Number);
2322
+ return element === undefined
2323
+ ? []
2324
+ : guaranteesOfType(checker, element).filter((one) => wanted.has(one));
2325
+ };
2326
+ /** What a function states by its written return type, or the promise it returns. */
2327
+ const returnTraits = (fn, wanted) => {
2328
+ if (fn.type === undefined || wanted.size === 0 || definesMarker(fn.type))
2329
+ return [];
2330
+ const checker = typeChecker();
2331
+ const type = checker.getTypeFromTypeNode(fn.type);
2332
+ const direct = guaranteesOfType(checker, type);
2333
+ const awaited = checker.getAwaitedType(type);
2334
+ const all = awaited === undefined || awaited === type
2335
+ ? direct
2336
+ : [...direct, ...guaranteesOfType(checker, awaited)];
2337
+ return [...new Set(all)].filter((one) => wanted.has(one)).sort();
2338
+ };
2339
+ /** The marker as the annotation writes it: the first reference in it that states a trait. */
2340
+ const markerOf = (type, fallback) => {
2341
+ if (type === undefined)
2342
+ return fallback;
2343
+ const checker = typeChecker();
2344
+ let found;
2345
+ const visit = (node) => {
2346
+ if (found !== undefined)
2347
+ return;
2348
+ if (ts.isTypeReferenceNode(node) &&
2349
+ guaranteesOfType(checker, checker.getTypeFromTypeNode(node)).length > 0) {
2350
+ found = node.typeName.getText();
2351
+ return;
2352
+ }
2353
+ ts.forEachChild(node, visit);
2354
+ };
2355
+ visit(type);
2356
+ return found ?? fallback;
2357
+ };
2358
+ const heldFunction = (node) => {
2359
+ if (!(ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node)) ||
2360
+ node.initializer === undefined) {
2361
+ return undefined;
2362
+ }
2363
+ let value = node.initializer;
2364
+ while (ts.isParenthesizedExpression(value) ||
2365
+ ts.isAsExpression(value) ||
2366
+ ts.isSatisfiesExpression(value) ||
2367
+ ts.isNonNullExpression(value) ||
2368
+ ts.isTypeAssertionExpression(value)) {
2369
+ value = value.expression;
2370
+ }
2371
+ return ts.isArrowFunction(value) || ts.isFunctionExpression(value) ? value : undefined;
2372
+ };
2373
+ /** Whether `file`'s text writes one of the tags `scan` lists. */
2374
+ const writesTags = (file, scan) => {
2375
+ if (scan.tags.size === 0)
2376
+ return false;
2377
+ let known = scan.tagged.get(file);
2378
+ if (known === undefined) {
2379
+ known = [...scan.tags].some((tag) => file.text.includes(`@${tag}`));
2380
+ scan.tagged.set(file, known);
2381
+ }
2382
+ return known;
2383
+ };
2384
+ /**
2385
+ * The JSDoc tags of `scan` written on a declaration a tag can state a trait of (a function, a
2386
+ * method, a variable, a property or method of a type, a type alias), with the tag nodes; a
2387
+ * variable's tags may sit on the function it holds too.
2388
+ */
2389
+ const tagsOn = (node, scan) => {
2390
+ const found = new Map();
2391
+ if (!(ts.isFunctionDeclaration(node) ||
2392
+ ts.isMethodDeclaration(node) ||
2393
+ ts.isMethodSignature(node) ||
2394
+ ts.isVariableDeclaration(node) ||
2395
+ ts.isPropertyDeclaration(node) ||
2396
+ ts.isPropertySignature(node) ||
2397
+ ts.isTypeAliasDeclaration(node)) ||
2398
+ !writesTags(node.getSourceFile(), scan)) {
2399
+ return found;
2400
+ }
2401
+ const held = heldFunction(node);
2402
+ for (const at of held === undefined ? [node] : [node, held]) {
2403
+ for (const tag of ts.getJSDocTags(at)) {
2404
+ const name = tag.tagName.text;
2405
+ if (scan.tags.has(name) && !found.has(`@${name}`))
2406
+ found.set(`@${name}`, tag);
2407
+ }
2408
+ }
2409
+ return found;
2410
+ };
2411
+ /** The value a declaration is made by, through `(…)`, `as`, `satisfies` and `!`. */
2412
+ const madeBy = (node) => {
2413
+ let value = node.initializer;
2414
+ while (value !== undefined &&
2415
+ (ts.isParenthesizedExpression(value) ||
2416
+ ts.isAsExpression(value) ||
2417
+ ts.isSatisfiesExpression(value) ||
2418
+ ts.isNonNullExpression(value) ||
2419
+ ts.isTypeAssertionExpression(value))) {
2420
+ value = value.expression;
2421
+ }
2422
+ return value;
2423
+ };
2424
+ /**
2425
+ * What a module variable with no written type states by the call that makes it (`const
2426
+ * ThemeContext = requiredContext<Theme>()`), of the traits `wanted` lists.
2427
+ */
2428
+ const madeTraits = (node, wanted) => {
2429
+ if (wanted.size === 0 || node.type !== undefined || !ts.isIdentifier(node.name))
2430
+ return [];
2431
+ // Only a module's own variables: a variable inside a function is asked no type question.
2432
+ const statement = node.parent.parent;
2433
+ if (!ts.isVariableStatement(statement) || !ts.isSourceFile(statement.parent))
2434
+ return [];
2435
+ const value = madeBy(node);
2436
+ if (value === undefined || !ts.isCallExpression(value))
2437
+ return [];
2438
+ const checker = typeChecker();
2439
+ return guaranteesOfType(checker, checker.getTypeAtLocation(node.name)).filter((one) => wanted.has(one));
2440
+ };
2441
+ /** The types written on a variable: its annotation, and the type arguments of the call that makes it. */
2442
+ const writtenOn = (node) => {
2443
+ if (node.type !== undefined)
2444
+ return [node.type];
2445
+ const value = madeBy(node);
2446
+ return value !== undefined && ts.isCallExpression(value)
2447
+ ? [...(value.typeArguments ?? [])]
2448
+ : [];
2449
+ };
2450
+ /** The traits of `wanted` a type holds: itself, a union member, a parameter or a return, three levels down. */
2451
+ const heldTraits = (type, wanted, depth) => {
2452
+ const checker = typeChecker();
2453
+ const found = new Set(guaranteesOfType(checker, type).filter((one) => wanted.has(one)));
2454
+ if (depth < 3) {
2455
+ const parts = type.isUnion() ? type.types : [];
2456
+ for (const part of parts) {
2457
+ for (const one of heldTraits(part, wanted, depth + 1))
2458
+ found.add(one);
2459
+ }
2460
+ for (const signature of type.getCallSignatures()) {
2461
+ const types = [
2462
+ ...signature.parameters.map((parameter) => checker.getTypeOfSymbol(parameter)),
2463
+ signature.getReturnType(),
2464
+ ];
2465
+ for (const one of types) {
2466
+ for (const trait of heldTraits(one, wanted, depth + 1))
2467
+ found.add(trait);
2468
+ }
2469
+ }
2470
+ }
2471
+ return [...found].sort();
2472
+ };
2473
+ /**
2474
+ * An element of an array destructuring (`setSaving` of `const [saving, setSaving] =
2475
+ * useState<Pending<boolean>>(false)`) whose declaration writes a trait `scan.holders` lists, and
2476
+ * whose own type holds it: the variable declaration is the stated declaration, named by the
2477
+ * first element.
2478
+ */
2479
+ const heldDeclaration = (node, scan) => {
2480
+ const pattern = node.parent;
2481
+ const holder = pattern.parent;
2482
+ if (scan.holders.size === 0 ||
2483
+ !ts.isArrayBindingPattern(pattern) ||
2484
+ !ts.isVariableDeclaration(holder) ||
2485
+ !ts.isIdentifier(node.name) ||
2486
+ node.dotDotDotToken !== undefined) {
2487
+ return undefined;
2488
+ }
2489
+ const written = writtenOn(holder).flatMap((type) => writtenTraits(type, scan.holders));
2490
+ if (written.length === 0)
2491
+ return undefined;
2492
+ const checker = typeChecker();
2493
+ const traits = heldTraits(checker.getTypeAtLocation(node.name), new Set(written), 0);
2494
+ const [first] = pattern.elements;
2495
+ if (traits.length === 0 || first === undefined)
2496
+ return undefined;
2497
+ const file = node.getSourceFile();
2498
+ return {
2499
+ nameNode: node.name,
2500
+ id: `${file.fileName}#${String(holder.getStart(file))}`,
2501
+ // `const [, setSaving] = …`: the setter alone names the state.
2502
+ name: ts.isBindingElement(first) ? first.name.getText(file) : node.name.text,
2503
+ word: node.name.text,
2504
+ marker: markerOf(writtenOn(holder)[0], traits[0] ?? ""),
2505
+ traits,
2506
+ };
2507
+ };
2508
+ /**
2509
+ * Whether a written type names, as its marker, another type alias that states a trait itself
2510
+ * (`type Id = OrderId`): that alias is the stated declaration, as core's scan reads it.
2511
+ */
2512
+ const aliasOfStatedAlias = (type) => {
2513
+ const checker = typeChecker();
2514
+ let found;
2515
+ const visit = (node) => {
2516
+ if (found !== undefined)
2517
+ return;
2518
+ if (ts.isTypeReferenceNode(node) &&
2519
+ ts.isIdentifier(node.typeName) &&
2520
+ guaranteesOfType(checker, checker.getTypeFromTypeNode(node)).length > 0) {
2521
+ found = node;
2522
+ return;
2523
+ }
2524
+ ts.forEachChild(node, visit);
2525
+ };
2526
+ visit(type);
2527
+ if (found === undefined)
2528
+ return false;
2529
+ const symbol = checker.getSymbolAtLocation(found.typeName);
2530
+ const target = symbol === undefined ? undefined : resolved(symbol);
2531
+ return (target?.declarations?.some((declaration) => ts.isTypeAliasDeclaration(declaration) &&
2532
+ declaration.typeParameters === undefined &&
2533
+ !definesMarker(declaration.type) &&
2534
+ guaranteesOfType(checker, checker.getTypeFromTypeNode(declaration.type)).length > 0) === true);
2535
+ };
2536
+ /** The traits a declaration states (of those `scan` lists), with its name and marker. */
2537
+ const statedDeclaration = (node, scan) => {
2538
+ const file = node.getSourceFile();
2539
+ if (!isOwn(file.fileName))
2540
+ return undefined;
2541
+ if (ts.isBindingElement(node))
2542
+ return heldDeclaration(node, scan);
2543
+ let traits = [];
2544
+ let type;
2545
+ let name;
2546
+ if (ts.isVariableDeclaration(node) ||
2547
+ ts.isPropertyDeclaration(node) ||
2548
+ ts.isPropertySignature(node)) {
2549
+ if (!(ts.isIdentifier(node.name) ||
2550
+ ts.isPrivateIdentifier(node.name) ||
2551
+ ts.isStringLiteral(node.name))) {
2552
+ return undefined;
2553
+ }
2554
+ name = node.name;
2555
+ if (node.type !== undefined) {
2556
+ type = node.type;
2557
+ traits = writtenTraits(node.type, scan.traits);
2558
+ }
2559
+ const fn = heldFunction(node);
2560
+ if (fn !== undefined) {
2561
+ const returned = returnTraits(fn, scan.returns);
2562
+ if (returned.length > 0 && type === undefined)
2563
+ type = fn.type;
2564
+ traits = [...traits, ...returned];
2565
+ }
2566
+ if (ts.isVariableDeclaration(node))
2567
+ traits = [...traits, ...madeTraits(node, scan.made)];
2568
+ // `const st = useState<Pending<boolean>>(false)`: the pair kept whole holds the state; its
2569
+ // reads (`st[1](true)`) are references the proof reads or lists as not checked.
2570
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.type === undefined) {
2571
+ traits = [
2572
+ ...traits,
2573
+ ...writtenOn(node).flatMap((written) => writtenTraits(written, scan.holders)),
2574
+ ];
2575
+ }
2576
+ traits = [...traits, ...tagsOn(node, scan).keys()];
2577
+ }
2578
+ else if (ts.isParameter(node)) {
2579
+ const fn = node.parent;
2580
+ if (!ts.isIdentifier(node.name) || node.type === undefined)
2581
+ return undefined;
2582
+ if (!("body" in fn) || fn.body === undefined)
2583
+ return undefined;
2584
+ name = node.name;
2585
+ type = node.type;
2586
+ // `o: typeof settings` names the type of a stated value; it states nothing of its own.
2587
+ traits = ts.isTypeQueryNode(node.type)
2588
+ ? []
2589
+ : node.dotDotDotToken === undefined
2590
+ ? writtenTraits(node.type, scan.traits)
2591
+ : restTraits(node.type, scan.traits);
2592
+ }
2593
+ else if ((ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) &&
2594
+ node.name !== undefined) {
2595
+ name = node.name;
2596
+ type = node.type;
2597
+ traits = [...returnTraits(node, scan.returns), ...tagsOn(node, scan).keys()];
2598
+ }
2599
+ else if (ts.isMethodSignature(node) && ts.isIdentifier(node.name)) {
2600
+ name = node.name;
2601
+ traits = [...tagsOn(node, scan).keys()];
2602
+ }
2603
+ else if (ts.isTypeAliasDeclaration(node)) {
2604
+ // `type OrderId = Opaque<string, "OrderId">`: a type a flow trait is stated on. An alias of
2605
+ // such an alias (`type Id = OrderId`) states nothing of its own. A tag may sit on any alias.
2606
+ const wanted = aliasTraits(scan);
2607
+ name = node.name;
2608
+ if (node.typeParameters === undefined && wanted.size > 0 && !aliasOfStatedAlias(node.type)) {
2609
+ type = node.type;
2610
+ traits = writtenTraits(node.type, wanted);
2611
+ }
2612
+ traits = [...traits, ...tagsOn(node, scan).keys()];
2613
+ }
2614
+ if (name === undefined || traits.length === 0)
2615
+ return undefined;
2616
+ // A property is listed at its name (after `static`, `readonly`), anything else where it starts.
2617
+ const start = ts.isPropertyDeclaration(node) || ts.isPropertySignature(node)
2618
+ ? name.getStart(file)
2619
+ : node.getStart(file);
2620
+ const sorted = [...new Set(traits)].sort();
2621
+ return {
2622
+ nameNode: name,
2623
+ id: `${file.fileName}#${String(start)}`,
2624
+ name: name.getText(file),
2625
+ word: ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name)
2626
+ ? name.text
2627
+ : name.getText(file),
2628
+ marker: markerOf(type, sorted[0] ?? ""),
2629
+ traits: sorted,
2630
+ };
2631
+ };
2632
+ const statedOf = (symbol, scan) => {
2633
+ const known = scan.bySymbol.get(symbol);
2634
+ if (known !== undefined)
2635
+ return known ?? undefined;
2636
+ const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
2637
+ const found = declaration === undefined ? undefined : statedDeclaration(declaration, scan);
2638
+ scan.bySymbol.set(symbol, found ?? null);
2639
+ return found;
2640
+ };
2641
+ /** The names of every stated declaration of the project's files: the prefilter's words. */
2642
+ const namesOf = (scan) => {
2643
+ if (scan.names !== undefined)
2644
+ return scan.names;
2645
+ const names = new Set();
2646
+ const declared = (trait) => program
2647
+ .getSourceFiles()
2648
+ .some((file) => file.text.includes(`${GUARANTEE_PREFIX}${trait}`) &&
2649
+ declaresMarkerProperty(file, `${GUARANTEE_PREFIX}${trait}`));
2650
+ // Values are asked about only when a trait a value states is declared, type aliases only when
2651
+ // a flow trait is: a project that declares only `Opaque` asks nothing of its variables.
2652
+ const values = [...scan.traits, ...scan.returns, ...scan.made, ...scan.holders].some(declared);
2653
+ const aliases = [...aliasTraits(scan)].some(declared);
2654
+ const ownFiles = program.getSourceFiles().filter((file) => isOwn(file.fileName));
2655
+ const tags = ownFiles.some((file) => writesTags(file, scan));
2656
+ if (values || aliases || tags) {
2657
+ for (const file of ownFiles) {
2658
+ const tagged = writesTags(file, scan);
2659
+ if (!values && !aliases && !tagged)
2660
+ continue;
2661
+ const visit = (node) => {
2662
+ if ((tagged && tagsOn(node, scan).size > 0) ||
2663
+ (values &&
2664
+ (ts.isVariableDeclaration(node) ||
2665
+ ts.isPropertyDeclaration(node) ||
2666
+ ts.isPropertySignature(node) ||
2667
+ ts.isParameter(node) ||
2668
+ ts.isFunctionDeclaration(node) ||
2669
+ ts.isMethodDeclaration(node)) &&
2670
+ (node.type !== undefined ||
2671
+ heldFunction(node)?.type !== undefined ||
2672
+ (scan.made.size > 0 &&
2673
+ ts.isVariableDeclaration(node) &&
2674
+ node.initializer !== undefined))) ||
2675
+ (values &&
2676
+ scan.holders.size > 0 &&
2677
+ ts.isBindingElement(node) &&
2678
+ ts.isArrayBindingPattern(node.parent)) ||
2679
+ (aliases && ts.isTypeAliasDeclaration(node))) {
2680
+ const stated = statedDeclaration(node, scan);
2681
+ if (stated !== undefined)
2682
+ names.add(stated.word);
2683
+ }
2684
+ ts.forEachChild(node, visit);
2685
+ };
2686
+ visit(file);
2687
+ }
2688
+ }
2689
+ scan.names = names;
2690
+ return names;
2691
+ };
2692
+ const resolved = (symbol) => symbol.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(symbol) : symbol;
2693
+ /** The symbol a name refers to, as find-references reads it. */
2694
+ const symbolOfReference = (node) => {
2695
+ const checker = typeChecker();
2696
+ const parent = node.parent;
2697
+ if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) {
2698
+ return checker.getShorthandAssignmentValueSymbol(parent);
2699
+ }
2700
+ if (ts.isExportSpecifier(parent)) {
2701
+ return parent.parent.parent.moduleSpecifier === undefined
2702
+ ? checker.getExportSpecifierLocalTargetSymbol(parent)
2703
+ : checker.getSymbolAtLocation(node);
2704
+ }
2705
+ if (ts.isBindingElement(parent) &&
2706
+ ts.isObjectBindingPattern(parent.parent) &&
2707
+ (parent.propertyName === node || (parent.propertyName === undefined && parent.name === node))) {
2708
+ const key = parent.propertyName ?? parent.name;
2709
+ if (!ts.isIdentifier(key) && !ts.isStringLiteral(key))
2710
+ return undefined;
2711
+ return checker.getTypeAtLocation(parent.parent).getProperty(key.text);
2712
+ }
2713
+ if (ts.isJsxAttribute(parent) && parent.name === node && ts.isIdentifier(node)) {
2714
+ // `<Search onSearch={post} />`: the prop of the component's props type, as find-references reads it.
2715
+ const contextual = checker.getContextualType(parent.parent);
2716
+ const whole = contextual?.getProperty(node.text);
2717
+ if (whole !== undefined || !contextual?.isUnion()) {
2718
+ return whole ?? checker.getSymbolAtLocation(node);
2719
+ }
2720
+ const found = contextual.types.flatMap((member) => member.getProperty(node.text) ?? []);
2721
+ return found.length === 1 ? found[0] : checker.getSymbolAtLocation(node);
2722
+ }
2723
+ if ((ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent)) &&
2724
+ parent.name === node &&
2725
+ ts.isObjectLiteralExpression(parent.parent)) {
2726
+ const contextual = checker.getContextualType(parent.parent);
2727
+ if (contextual === undefined || !ts.isIdentifier(node))
2728
+ return undefined;
2729
+ // `setForm({ ...form, saving: true })`: the setter takes `Form | ((prev: Form) => Form)`, and
2730
+ // the property is `Form`'s, as find-references reads it.
2731
+ const whole = contextual.getProperty(node.text);
2732
+ if (whole !== undefined || !contextual.isUnion())
2733
+ return whole;
2734
+ const found = contextual.types.flatMap((member) => member.getProperty(node.text) ?? []);
2735
+ return found.length === 1 ? found[0] : undefined;
2736
+ }
2737
+ return checker.getSymbolAtLocation(node);
2738
+ };
2739
+ /**
2740
+ * The local names `file` gives stated declarations by an import (`import { a as b }`, a default
2741
+ * import, `import x = …`) or a re-export (`export { default as b } from …`): a reference by such
2742
+ * a name does not read the declaration's name.
2743
+ */
2744
+ const importedNames = (file, scan) => {
2745
+ const found = new Set();
2746
+ const consider = (name) => {
2747
+ const symbol = typeChecker().getSymbolAtLocation(name);
2748
+ if (symbol === undefined)
2749
+ return;
2750
+ const target = resolved(symbol);
2751
+ for (const root of typeChecker().getRootSymbols(target)) {
2752
+ if (statedOf(root, scan) !== undefined)
2753
+ found.add(name.text);
2754
+ }
2755
+ };
2756
+ for (const statement of file.statements) {
2757
+ if (ts.isImportDeclaration(statement)) {
2758
+ const clause = statement.importClause;
2759
+ if (clause?.name !== undefined)
2760
+ consider(clause.name);
2761
+ const bindings = clause?.namedBindings;
2762
+ if (bindings !== undefined && ts.isNamedImports(bindings)) {
2763
+ for (const element of bindings.elements)
2764
+ consider(element.name);
2765
+ }
2766
+ }
2767
+ else if (ts.isImportEqualsDeclaration(statement)) {
2768
+ consider(statement.name);
2769
+ }
2770
+ else if (ts.isExportDeclaration(statement) &&
2771
+ statement.moduleSpecifier !== undefined &&
2772
+ statement.exportClause !== undefined &&
2773
+ ts.isNamedExports(statement.exportClause)) {
2774
+ // `export { default as dflt } from "./owner.js"`: both names are references.
2775
+ for (const element of statement.exportClause.elements) {
2776
+ if (ts.isIdentifier(element.name))
2777
+ consider(element.name);
2778
+ if (element.propertyName !== undefined && ts.isIdentifier(element.propertyName)) {
2779
+ consider(element.propertyName);
2780
+ }
2781
+ }
2782
+ }
2783
+ }
2784
+ return found;
2785
+ };
2786
+ /** Whether `node` is the name of the declaration it resolves to (not a reference to it). */
2787
+ const isOwnName = (node, stated) => stated.nameNode === node;
2788
+ const referencesIn = (sourceFile, proves) => {
2789
+ const scan = scanFor(proves);
2790
+ if (scan.traits.size === 0 &&
2791
+ scan.returns.size === 0 &&
2792
+ scan.made.size === 0 &&
2793
+ scan.holders.size === 0 &&
2794
+ scan.tags.size === 0 &&
2795
+ aliasTraits(scan).size === 0) {
2796
+ return [];
2797
+ }
2798
+ const names = namesOf(scan);
2799
+ if (names.size === 0)
2800
+ return [];
2801
+ const words = new Set(names);
2802
+ const { text } = sourceFile;
2803
+ const mentions = [...names].some((name) => text.includes(name.replace(/^#/, "")));
2804
+ for (const name of importedNames(sourceFile, scan))
2805
+ words.add(name);
2806
+ if (!mentions && words.size === names.size)
2807
+ return [];
2808
+ const found = [];
2809
+ const add = (node) => {
2810
+ const symbol = symbolOfReference(node);
2811
+ if (symbol === undefined)
2812
+ return;
2813
+ const seen = new Set();
2814
+ for (const root of typeChecker().getRootSymbols(resolved(symbol))) {
2815
+ const stated = statedOf(root, scan);
2816
+ if (stated === undefined || seen.has(stated.id) || isOwnName(node, stated))
2817
+ continue;
2818
+ seen.add(stated.id);
2819
+ const ref = refOfSymbol(root);
2820
+ if (ref === undefined)
2821
+ continue;
2822
+ const { form, shown } = referenceForm(node);
2823
+ for (const trait of stated.traits) {
2824
+ found.push({
2825
+ declaration: stated.id,
2826
+ symbol: ref,
2827
+ name: stated.name,
2828
+ marker: stated.marker,
2829
+ trait,
2830
+ node,
2831
+ form,
2832
+ text: shortText(shown, sourceFile),
2833
+ });
2834
+ }
2835
+ }
2836
+ };
2837
+ const tagged = writesTags(sourceFile, scan);
2838
+ /** The tags on a declaration of this file: each is a reference that stands for its body. */
2839
+ const addTags = (node) => {
2840
+ const tags = tagsOn(node, scan);
2841
+ if (tags.size === 0)
2842
+ return;
2843
+ const stated = statedDeclaration(node, scan);
2844
+ const symbol = stated === undefined ? undefined : symbolOfReference(stated.nameNode);
2845
+ const ref = symbol === undefined ? undefined : refOfSymbol(symbol);
2846
+ if (stated === undefined || ref === undefined)
2847
+ return;
2848
+ for (const [trait, tag] of tags) {
2849
+ found.push({
2850
+ declaration: stated.id,
2851
+ symbol: ref,
2852
+ name: stated.name,
2853
+ marker: stated.marker,
2854
+ trait,
2855
+ node: tag,
2856
+ form: "tag",
2857
+ text: tagText(tag, sourceFile),
2858
+ });
2859
+ }
2860
+ };
2861
+ const visit = (node) => {
2862
+ if (tagged)
2863
+ addTags(node);
2864
+ if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && words.has(node.text)) {
2865
+ add(node);
2866
+ }
2867
+ else if (ts.isStringLiteral(node) &&
2868
+ ts.isElementAccessExpression(node.parent) &&
2869
+ node.parent.argumentExpression === node &&
2870
+ names.has(node.text)) {
2871
+ add(node);
2872
+ }
2873
+ ts.forEachChild(node, visit);
2874
+ };
2875
+ visit(sourceFile);
2876
+ return found.sort((a, b) => a.node.getStart(sourceFile) - b.node.getStart(sourceFile) ||
2877
+ (a.declaration < b.declaration ? -1 : a.declaration > b.declaration ? 1 : 0) ||
2878
+ (a.trait < b.trait ? -1 : a.trait > b.trait ? 1 : 0));
2879
+ };
2880
+ /** The own files each own file imports (and re-exports from, and `import()`s). */
2881
+ const importsOf = (file) => {
2882
+ const checker = typeChecker();
2883
+ const found = [];
2884
+ const add = (specifier) => {
2885
+ if (specifier === undefined || !ts.isStringLiteralLike(specifier))
2886
+ return;
2887
+ const symbol = checker.getSymbolAtLocation(specifier);
2888
+ const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
2889
+ if (declaration !== undefined && ts.isSourceFile(declaration)) {
2890
+ found.push(declaration.fileName);
2891
+ }
2892
+ };
2893
+ const dynamic = file.text.includes("import(") || file.text.includes("require(");
2894
+ const visit = (node) => {
2895
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node))
2896
+ add(node.moduleSpecifier);
2897
+ else if (ts.isImportEqualsDeclaration(node) &&
2898
+ ts.isExternalModuleReference(node.moduleReference)) {
2899
+ add(node.moduleReference.expression);
2900
+ }
2901
+ else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
2902
+ add(node.argument.literal);
2903
+ }
2904
+ else if (ts.isCallExpression(node) &&
2905
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
2906
+ (ts.isIdentifier(node.expression) && node.expression.text === "require"))) {
2907
+ add(node.arguments[0]);
2908
+ }
2909
+ if (dynamic ||
2910
+ ts.isSourceFile(node) ||
2911
+ ts.isModuleDeclaration(node) ||
2912
+ ts.isModuleBlock(node)) {
2913
+ ts.forEachChild(node, visit);
2914
+ }
2915
+ };
2916
+ visit(file);
2917
+ return found;
2918
+ };
2919
+ /**
2920
+ * The own files whose imports reach one of `declaring`: the declaring files, and every file that
2921
+ * imports one of the set, until none is added. A declaring file that is not a module (its
2922
+ * types are global) is reached by every file.
2923
+ */
2924
+ const reachingFiles = (declaring) => {
2925
+ const files = program.getSourceFiles().filter((file) => isOwn(file.fileName));
2926
+ if (files.some((file) => declaring.has(file.fileName) && !ts.isExternalModule(file))) {
2927
+ return "all";
2928
+ }
2929
+ const importers = new Map();
2930
+ for (const file of files) {
2931
+ for (const imported of importsOf(file)) {
2932
+ const list = importers.get(imported) ?? [];
2933
+ list.push(file.fileName);
2934
+ importers.set(imported, list);
2935
+ }
2936
+ }
2937
+ const reached = new Set(declaring);
2938
+ const queue = [...declaring];
2939
+ for (let next = queue.pop(); next !== undefined; next = queue.pop()) {
2940
+ for (const importer of importers.get(next) ?? []) {
2941
+ if (reached.has(importer))
2942
+ continue;
2943
+ reached.add(importer);
2944
+ queue.push(importer);
2945
+ }
2946
+ }
2947
+ return reached;
2948
+ };
2949
+ /** The stated type aliases and members of `scan`'s flow traits, found once per scan. */
2950
+ const flowTargets = (scan) => {
2951
+ if (scan.targets !== undefined)
2952
+ return scan.targets;
2953
+ const checker = typeChecker();
2954
+ const aliases = [];
2955
+ const bySymbol = new Map();
2956
+ const byMember = new Map();
2957
+ const members = new Map();
2958
+ const alias = aliasTraits(scan);
2959
+ const wanted = [...alias, ...scan.escaped];
2960
+ const declared = wanted.filter((trait) => program
2961
+ .getSourceFiles()
2962
+ .some((file) => file.text.includes(`${GUARANTEE_PREFIX}${trait}`) &&
2963
+ declaresMarkerProperty(file, `${GUARANTEE_PREFIX}${trait}`)));
2964
+ const target = (stated, symbol, file) => {
2965
+ const ref = refOfSymbol(symbol);
2966
+ if (ref === undefined)
2967
+ return undefined;
2968
+ return {
2969
+ stated,
2970
+ symbol,
2971
+ ref,
2972
+ file,
2973
+ produced: stated.traits.filter((trait) => scan.produced.has(trait)),
2974
+ decided: stated.traits.filter((trait) => scan.decided.has(trait)),
2975
+ escaped: stated.traits.filter((trait) => scan.escaped.has(trait)),
2976
+ };
2977
+ };
2978
+ if (declared.length > 0) {
2979
+ for (const file of program.getSourceFiles()) {
2980
+ if (!isOwn(file.fileName))
2981
+ continue;
2982
+ const visit = (node) => {
2983
+ if (ts.isTypeAliasDeclaration(node) && alias.size > 0) {
2984
+ const stated = statedDeclaration(node, scan);
2985
+ const symbol = checker.getSymbolAtLocation(node.name);
2986
+ const found = stated === undefined || symbol === undefined
2987
+ ? undefined
2988
+ : target(stated, symbol, file.fileName);
2989
+ if (found !== undefined && (found.produced.length > 0 || found.decided.length > 0)) {
2990
+ aliases.push(found);
2991
+ bySymbol.set(found.symbol, found);
2992
+ const type = checker.getDeclaredTypeOfSymbol(found.symbol);
2993
+ for (const member of type.isUnion() ? type.types : [type]) {
2994
+ if (member.flags & NULLISH)
2995
+ continue;
2996
+ byMember.set(member, [...(byMember.get(member) ?? []), found]);
2997
+ }
2998
+ }
2999
+ }
3000
+ else if (scan.escaped.size > 0 &&
3001
+ (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node)) &&
3002
+ node.type !== undefined) {
3003
+ const stated = statedDeclaration(node, scan);
3004
+ const symbol = checker.getSymbolAtLocation(node.name);
3005
+ const found = stated === undefined || symbol === undefined
3006
+ ? undefined
3007
+ : target(stated, symbol, file.fileName);
3008
+ if (found !== undefined && found.escaped.length > 0) {
3009
+ members.set(stated?.word ?? "", [...(members.get(stated?.word ?? "") ?? []), found]);
3010
+ }
3011
+ }
3012
+ ts.forEachChild(node, visit);
3013
+ };
3014
+ visit(file);
3015
+ }
3016
+ }
3017
+ const declaring = new Set([
3018
+ ...aliases.map((one) => one.file),
3019
+ ...[...members.values()].flat().map((one) => one.file),
3020
+ ]);
3021
+ scan.targets = {
3022
+ aliases,
3023
+ bySymbol,
3024
+ byMember,
3025
+ members,
3026
+ reaching: declaring.size === 0 ? new Set() : reachingFiles(declaring),
3027
+ };
3028
+ return scan.targets;
3029
+ };
3030
+ /** Through `(…)`, `!` and a branch of `?:`, `??`, `||`, `&&` or `,`: the values an expression gives. */
3031
+ const leavesOf = (expression) => {
3032
+ if (ts.isParenthesizedExpression(expression) || ts.isNonNullExpression(expression)) {
3033
+ return leavesOf(expression.expression);
3034
+ }
3035
+ if (ts.isConditionalExpression(expression)) {
3036
+ return [...leavesOf(expression.whenTrue), ...leavesOf(expression.whenFalse)];
3037
+ }
3038
+ if (ts.isBinaryExpression(expression)) {
3039
+ const kind = expression.operatorToken.kind;
3040
+ if (kind === ts.SyntaxKind.QuestionQuestionToken ||
3041
+ kind === ts.SyntaxKind.BarBarToken ||
3042
+ kind === ts.SyntaxKind.AmpersandAmpersandToken) {
3043
+ return [...leavesOf(expression.left), ...leavesOf(expression.right)];
3044
+ }
3045
+ if (kind === ts.SyntaxKind.CommaToken)
3046
+ return leavesOf(expression.right);
3047
+ }
3048
+ return [expression];
3049
+ };
3050
+ /** Whether every value of `type` is `undefined`, `null`, `void` or `never`: it builds nothing. */
3051
+ const holdsNothing = (type) => (type.isUnion() ? type.types : [type]).every((member) => (member.flags &
3052
+ (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void | ts.TypeFlags.Never)) !==
3053
+ 0);
3054
+ /** `Object.assign`, `Reflect.set`: the callee's two words, or undefined. */
3055
+ const calleeWords = (call) => {
3056
+ const callee = call.expression;
3057
+ if (ts.isIdentifier(callee))
3058
+ return callee.text;
3059
+ if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
3060
+ return `${callee.expression.text}.${callee.name.text}`;
3061
+ }
3062
+ return undefined;
3063
+ };
3064
+ /** Methods that decide by the value they are given: `list.includes(s)`, `map.get(s)`. */
3065
+ const DECIDING_METHODS = new Set([
3066
+ "includes",
3067
+ "indexOf",
3068
+ "lastIndexOf",
3069
+ "has",
3070
+ "get",
3071
+ ]);
3072
+ /** Calls that read a value as a key of an object: a lookup by it. */
3073
+ const KEYED_CALLS = new Set([
3074
+ "Reflect.get",
3075
+ "Reflect.has",
3076
+ "Reflect.getOwnPropertyDescriptor",
3077
+ "Object.hasOwn",
3078
+ ]);
3079
+ /** Calls that write a property of their first argument whatever its type says. */
3080
+ const REFLECT_WRITES = new Set([
3081
+ "Object.assign",
3082
+ "Object.defineProperty",
3083
+ "Object.defineProperties",
3084
+ "Object.setPrototypeOf",
3085
+ "Reflect.set",
3086
+ "Reflect.defineProperty",
3087
+ "Reflect.setPrototypeOf",
3088
+ ]);
3089
+ const flowsIn = (sourceFile, proves, budget) => {
3090
+ const scan = scanFor(proves);
3091
+ if (aliasTraits(scan).size === 0 && scan.escaped.size === 0)
3092
+ return [];
3093
+ const targets = flowTargets(scan);
3094
+ if (targets.aliases.length === 0 && targets.members.size === 0)
3095
+ return [];
3096
+ if (targets.reaching !== "all" && !targets.reaching.has(sourceFile.fileName))
3097
+ return [];
3098
+ const checker = typeChecker();
3099
+ const found = [];
3100
+ const seen = new Set();
3101
+ let questions = 0;
3102
+ let stopped;
3103
+ const add = (node, shown, flow, kind, via) => {
3104
+ const traits = flow[kind];
3105
+ for (const trait of traits) {
3106
+ const key = `${String(node.getStart(sourceFile))}-${String(node.end)}-${flow.stated.id}-${trait}-${kind}`;
3107
+ if (seen.has(key))
3108
+ continue;
3109
+ seen.add(key);
3110
+ found.push({
3111
+ declaration: flow.stated.id,
3112
+ symbol: flow.ref,
3113
+ name: flow.stated.name,
3114
+ marker: flow.stated.marker,
3115
+ trait,
3116
+ node,
3117
+ form: kind,
3118
+ via,
3119
+ text: shortText(shown, sourceFile),
3120
+ });
3121
+ }
3122
+ };
3123
+ const typeAt = (node) => {
3124
+ questions += 1;
3125
+ return checker.getTypeAtLocation(node);
3126
+ };
3127
+ const contextual = (node) => {
3128
+ questions += 1;
3129
+ return checker.getContextualType(node);
3130
+ };
3131
+ // ---- what a type holds -------------------------------------------------------------------
3132
+ const heldMemo = new Map();
3133
+ /** The stated aliases a type holds: itself, a member, a constraint, three levels in. */
3134
+ const aliasesIn = (type) => {
3135
+ const known = heldMemo.get(type);
3136
+ if (known !== undefined)
3137
+ return known;
3138
+ const into = new Set();
3139
+ const visiting = new Set();
3140
+ const enter = (given, depth) => {
3141
+ if (depth > FLOW_DEPTH || visiting.has(given))
3142
+ return;
3143
+ questions += 1;
3144
+ const named = given.aliasSymbol === undefined ? undefined : targets.bySymbol.get(given.aliasSymbol);
3145
+ if (named !== undefined)
3146
+ into.add(named);
3147
+ for (const one of targets.byMember.get(given) ?? [])
3148
+ into.add(one);
3149
+ if (given.flags & PRIMITIVE_FLAGS)
3150
+ return;
3151
+ visiting.add(given);
3152
+ if (given.flags & ts.TypeFlags.TypeParameter) {
3153
+ const constraint = checker.getBaseConstraintOfType(given);
3154
+ if (constraint !== undefined && constraint !== given)
3155
+ enter(constraint, depth);
3156
+ }
3157
+ else if (given.isUnionOrIntersection()) {
3158
+ for (const member of given.types)
3159
+ enter(member, depth);
3160
+ }
3161
+ else if (depth < FLOW_DEPTH && given.flags & ts.TypeFlags.Object) {
3162
+ if (isTypeReference(given)) {
3163
+ for (const argument of checker.getTypeArguments(given))
3164
+ enter(argument, depth + 1);
3165
+ }
3166
+ for (const signature of given.getCallSignatures()) {
3167
+ enter(signature.getReturnType(), depth + 1);
3168
+ }
3169
+ // `Record<string, OrderId>`: an alias's type arguments, and any index signature.
3170
+ for (const argument of given.aliasTypeArguments ?? [])
3171
+ enter(argument, depth + 1);
3172
+ for (const info of checker.getIndexInfosOfType(given))
3173
+ enter(info.type, depth + 1);
3174
+ if (isOwnObject(given)) {
3175
+ for (const property of checker.getPropertiesOfType(given)) {
3176
+ enter(checker.getTypeOfSymbol(property), depth + 1);
3177
+ }
3178
+ }
3179
+ }
3180
+ visiting.delete(given);
3181
+ };
3182
+ enter(type, 0);
3183
+ const list = [...into].sort((a, b) => compareIds(a.stated.id, b.stated.id));
3184
+ heldMemo.set(type, list);
3185
+ return list;
3186
+ };
3187
+ /** An object type the scan looks into: written in place, or declared in the project. */
3188
+ const isOwnObject = (type) => {
3189
+ if (isAnonymousObject(type))
3190
+ return true;
3191
+ const declarations = type.getSymbol()?.declarations ?? [];
3192
+ return declarations.some((one) => isOwn(one.getSourceFile().fileName));
3193
+ };
3194
+ /** The stated aliases `type` is itself (a member of): not what it holds inside. */
3195
+ const aliasesOf = (type) => {
3196
+ const named = type.aliasSymbol === undefined ? undefined : targets.bySymbol.get(type.aliasSymbol);
3197
+ if (named !== undefined)
3198
+ return [named];
3199
+ const into = new Set();
3200
+ for (const member of type.isUnion() ? type.types : [type]) {
3201
+ if (member.flags & NULLISH)
3202
+ continue;
3203
+ const own = member.aliasSymbol === undefined ? undefined : targets.bySymbol.get(member.aliasSymbol);
3204
+ if (own !== undefined)
3205
+ into.add(own);
3206
+ for (const one of targets.byMember.get(member) ?? [])
3207
+ into.add(one);
3208
+ }
3209
+ return [...into];
3210
+ };
3211
+ /**
3212
+ * Whether every member of `source` fits a member of `target` that holds no stated alias: a
3213
+ * `number` given as `OrderId | number` builds no `OrderId`.
3214
+ */
3215
+ const fitsOther = (source, target) => {
3216
+ const others = (target.isUnion() ? target.types : [target]).filter((member) => aliasesIn(member).length === 0);
3217
+ if (others.length === 0)
3218
+ return false;
3219
+ return (source.isUnion() ? source.types : [source]).every((member) => others.some((other) => checker.isTypeAssignableTo(member, other)));
3220
+ };
3221
+ // ---- produced ----------------------------------------------------------------------------
3222
+ /** A value given to a place of type `target`: each of its values whose own type lacks an alias it holds. */
3223
+ const given = (expression, target, via) => {
3224
+ if (target === undefined)
3225
+ return;
3226
+ const wanted = aliasesIn(target).filter((one) => one.produced.length > 0);
3227
+ if (wanted.length === 0)
3228
+ return;
3229
+ for (const leaf of leavesOf(expression)) {
3230
+ // A literal's members are places of their own; a cast is read as one.
3231
+ if (ts.isObjectLiteralExpression(leaf) || ts.isArrayLiteralExpression(leaf))
3232
+ continue;
3233
+ const source = typeAt(leaf);
3234
+ if (holdsNothing(source))
3235
+ continue;
3236
+ const any = (source.flags & ts.TypeFlags.Any) !== 0;
3237
+ const own = any ? [] : aliasesIn(source);
3238
+ if (!any && fitsOther(source, target))
3239
+ continue;
3240
+ const kind = via ?? (any ? "any" : source.getCallSignatures().length > 0 ? "function-type" : "value");
3241
+ for (const one of wanted) {
3242
+ if (!own.includes(one))
3243
+ add(leaf, leaf, one, "produced", kind);
3244
+ }
3245
+ }
3246
+ };
3247
+ /** The return types of the other declarations of an overloaded function, for its implementation's returns. */
3248
+ const overloadTarget = (node) => {
3249
+ let fn = node.parent;
3250
+ while (!ts.isFunctionLike(fn) && !ts.isSourceFile(fn))
3251
+ fn = fn.parent;
3252
+ if (!(ts.isFunctionDeclaration(fn) || ts.isMethodDeclaration(fn)) ||
3253
+ fn.body === undefined ||
3254
+ fn.name === undefined) {
3255
+ return undefined;
3256
+ }
3257
+ const symbol = checker.getSymbolAtLocation(fn.name);
3258
+ const others = (symbol?.declarations ?? []).filter((one) => one !== fn && ts.isFunctionLike(one) && !("body" in one && one.body !== undefined));
3259
+ if (others.length === 0)
3260
+ return undefined;
3261
+ return others.flatMap((one) => {
3262
+ const signature = checker.getSignatureFromDeclaration(one);
3263
+ return signature === undefined ? [] : [checker.getReturnTypeOfSignature(signature)];
3264
+ });
3265
+ };
3266
+ /**
3267
+ * The types a class member takes from the classes and interfaces its class extends or
3268
+ * implements (`override id()` over `id(): OrderId`): a value it gives is given to them too.
3269
+ */
3270
+ const inheritedTypes = (member) => {
3271
+ const owner = member.parent;
3272
+ if (!ts.isClassLike(owner) || member.name === undefined)
3273
+ return [];
3274
+ const name = ts.isIdentifier(member.name) || ts.isPrivateIdentifier(member.name)
3275
+ ? member.name.text
3276
+ : ts.isStringLiteral(member.name)
3277
+ ? member.name.text
3278
+ : undefined;
3279
+ if (name === undefined)
3280
+ return [];
3281
+ return (owner.heritageClauses ?? []).flatMap((clause) => clause.types.flatMap((base) => {
3282
+ questions += 1;
3283
+ const property = checker.getPropertyOfType(checker.getTypeAtLocation(base), name);
3284
+ return property === undefined ? [] : [checker.getTypeOfSymbol(property)];
3285
+ }));
3286
+ };
3287
+ /** The return types a method or getter takes from the members it overrides. */
3288
+ const inheritedReturns = (node) => {
3289
+ let fn = node.parent;
3290
+ while (!ts.isFunctionLike(fn) && !ts.isSourceFile(fn))
3291
+ fn = fn.parent;
3292
+ if (!(ts.isMethodDeclaration(fn) || ts.isGetAccessorDeclaration(fn)))
3293
+ return [];
3294
+ const types = inheritedTypes(fn);
3295
+ if (ts.isGetAccessorDeclaration(fn))
3296
+ return types;
3297
+ return types.flatMap((type) => type.getCallSignatures().map((signature) => signature.getReturnType()));
3298
+ };
3299
+ const returned = (expression) => {
3300
+ const overloads = overloadTarget(expression);
3301
+ if (overloads !== undefined) {
3302
+ for (const type of overloads)
3303
+ given(expression, type, "overload");
3304
+ return;
3305
+ }
3306
+ given(expression, contextual(expression));
3307
+ for (const type of inheritedReturns(expression))
3308
+ given(expression, type, "override");
3309
+ };
3310
+ /**
3311
+ * Each property of `source` that the target type (`target`) holds a stated alias in while the
3312
+ * source's own property does not: a spread attribute or property.
3313
+ */
3314
+ const spreadInto = (node, target, shown) => {
3315
+ if (target === undefined)
3316
+ return;
3317
+ const source = typeAt(node);
3318
+ if (holdsNothing(source))
3319
+ return;
3320
+ const any = (source.flags & ts.TypeFlags.Any) !== 0;
3321
+ for (const property of checker.getPropertiesOfType(source)) {
3322
+ const into = target.isUnion()
3323
+ ? target.types.flatMap((member) => checker.getPropertyOfType(member, property.getName()) ?? [])
3324
+ : [checker.getPropertyOfType(target, property.getName())].flatMap((one) => one ?? []);
3325
+ for (const wanted of into) {
3326
+ const held = aliasesIn(checker.getTypeOfSymbol(wanted)).filter((one) => one.produced.length > 0);
3327
+ if (held.length === 0)
3328
+ continue;
3329
+ const own = any ? [] : aliasesIn(checker.getTypeOfSymbol(property));
3330
+ for (const one of held) {
3331
+ if (!own.includes(one))
3332
+ add(node, shown, one, "produced", any ? "any" : "spread");
3333
+ }
3334
+ }
3335
+ }
3336
+ if (any) {
3337
+ for (const one of aliasesIn(target).filter((alias) => alias.produced.length > 0)) {
3338
+ add(node, shown, one, "produced", "any");
3339
+ }
3340
+ }
3341
+ };
3342
+ /** The element type an iterable or array gives, when the checker can say. */
3343
+ const elementOf = (type) => checker.getIndexTypeOfType(type, ts.IndexKind.Number);
3344
+ /** A spread argument: its elements given to the parameters from its index on. */
3345
+ const spreadArgument = (call, spread) => {
3346
+ questions += 1;
3347
+ const signature = checker.getResolvedSignature(call);
3348
+ const index = call.arguments?.indexOf(spread) ?? -1;
3349
+ if (signature === undefined || index < 0)
3350
+ return;
3351
+ const wanted = signature.parameters
3352
+ .slice(index)
3353
+ .flatMap((parameter) => aliasesIn(checker.getTypeOfSymbol(parameter)))
3354
+ .filter((one) => one.produced.length > 0);
3355
+ if (wanted.length === 0)
3356
+ return;
3357
+ const source = typeAt(spread.expression);
3358
+ const any = (source.flags & ts.TypeFlags.Any) !== 0;
3359
+ const own = any ? [] : aliasesIn(source);
3360
+ for (const one of wanted) {
3361
+ if (!own.includes(one))
3362
+ add(spread, call, one, "produced", any ? "any" : "spread");
3363
+ }
3364
+ };
3365
+ /** A call whose type arguments give it a stated alias its arguments do not hold: `getJson<Order>(url)`. */
3366
+ const genericCall = (call) => {
3367
+ questions += 1;
3368
+ const signature = checker.getResolvedSignature(call);
3369
+ const declaration = signature?.getDeclaration();
3370
+ if (signature === undefined || declaration === undefined)
3371
+ return;
3372
+ const generic = checker.getSignatureFromDeclaration(declaration);
3373
+ if (generic?.typeParameters === undefined || generic.typeParameters.length === 0)
3374
+ return;
3375
+ const held = aliasesIn(checker.getReturnTypeOfSignature(signature)).filter((one) => one.produced.length > 0);
3376
+ if (held.length === 0)
3377
+ return;
3378
+ const declared = new Set(aliasesIn(checker.getReturnTypeOfSignature(generic)));
3379
+ // A type argument a parameter takes too (`useState<OrderId | null>(null)`, `new
3380
+ // Map<OrderId, number>()`): its values come in through the arguments, each read where it
3381
+ // is given, so the call makes none of its own. Only for a function of a package or the
3382
+ // standard library: a function of the project could still cast inside its body.
3383
+ if (!isOwn(declaration.getSourceFile().fileName)) {
3384
+ for (const parameter of signature.parameters) {
3385
+ for (const one of aliasesIn(checker.getTypeOfSymbol(parameter)))
3386
+ declared.add(one);
3387
+ }
3388
+ }
3389
+ const fromArguments = new Set();
3390
+ for (const argument of call.arguments ?? []) {
3391
+ const type = typeAt(ts.isSpreadElement(argument) ? argument.expression : argument);
3392
+ for (const one of aliasesIn(type))
3393
+ fromArguments.add(one);
3394
+ }
3395
+ if (ts.isPropertyAccessExpression(call.expression) ||
3396
+ ts.isElementAccessExpression(call.expression)) {
3397
+ for (const one of aliasesIn(typeAt(call.expression.expression)))
3398
+ fromArguments.add(one);
3399
+ }
3400
+ for (const one of held) {
3401
+ if (!declared.has(one) && !fromArguments.has(one)) {
3402
+ add(call, call, one, "produced", "generic-call");
3403
+ }
3404
+ }
3405
+ };
3406
+ /** `.call`, `.apply`, `.bind`, `Reflect.apply`, `Reflect.construct`: arguments no parameter types. */
3407
+ const indirectCall = (call) => {
3408
+ const callee = call.expression;
3409
+ const words = calleeWords(call);
3410
+ let fn;
3411
+ let passed = [];
3412
+ if (words === "Reflect.apply" || words === "Reflect.construct") {
3413
+ fn = call.arguments[0];
3414
+ const list = call.arguments[words === "Reflect.apply" ? 2 : 1];
3415
+ passed = list === undefined ? [] : [list];
3416
+ }
3417
+ else if (ts.isPropertyAccessExpression(callee) &&
3418
+ (callee.name.text === "call" || callee.name.text === "apply" || callee.name.text === "bind")) {
3419
+ fn = callee.expression;
3420
+ passed = call.arguments.slice(1);
3421
+ }
3422
+ if (fn === undefined)
3423
+ return;
3424
+ const type = typeAt(fn);
3425
+ const signatures = [...type.getCallSignatures(), ...type.getConstructSignatures()];
3426
+ if (signatures.length === 0)
3427
+ return;
3428
+ const wanted = signatures
3429
+ .flatMap((signature) => signature.parameters)
3430
+ .flatMap((parameter) => aliasesIn(checker.getTypeOfSymbol(parameter)))
3431
+ .filter((one) => one.produced.length > 0);
3432
+ if (wanted.length === 0)
3433
+ return;
3434
+ const own = new Set();
3435
+ let any = false;
3436
+ for (const argument of passed) {
3437
+ const argumentType = typeAt(argument);
3438
+ if (argumentType.flags & ts.TypeFlags.Any)
3439
+ any = true;
3440
+ for (const one of aliasesIn(argumentType))
3441
+ own.add(one);
3442
+ }
3443
+ for (const one of wanted) {
3444
+ if (any || !own.has(one))
3445
+ add(call, call, one, "produced", "indirect-call");
3446
+ }
3447
+ };
3448
+ /** `Object.assign(o, …)`, `Reflect.set(o, "id", …)`, `new Proxy(o, …)`: a holder written past its type. */
3449
+ const reflectWrite = (call, words) => {
3450
+ const first = call.arguments?.[0];
3451
+ if (first === undefined)
3452
+ return;
3453
+ const holder = typeAt(first);
3454
+ const produced = aliasesIn(holder).filter((one) => one.produced.length > 0);
3455
+ if (produced.length > 0) {
3456
+ let wanted = produced;
3457
+ const key = call.arguments?.[1];
3458
+ if ((words === "Reflect.set" ||
3459
+ words === "Object.defineProperty" ||
3460
+ words === "Reflect.defineProperty") &&
3461
+ key !== undefined &&
3462
+ ts.isStringLiteralLike(key)) {
3463
+ const property = checker.getPropertyOfType(holder, key.text);
3464
+ wanted = property === undefined ? [] : aliasesIn(checker.getTypeOfSymbol(property));
3465
+ }
3466
+ else if (words === "Object.assign") {
3467
+ const fromSources = new Set();
3468
+ for (const source of (call.arguments ?? []).slice(1)) {
3469
+ for (const property of checker.getPropertiesOfType(typeAt(source))) {
3470
+ const into = checker.getPropertyOfType(holder, property.getName());
3471
+ if (into === undefined)
3472
+ continue;
3473
+ const held = aliasesIn(checker.getTypeOfSymbol(into));
3474
+ const own = aliasesIn(checker.getTypeOfSymbol(property));
3475
+ for (const one of held)
3476
+ if (!own.includes(one))
3477
+ fromSources.add(one);
3478
+ }
3479
+ }
3480
+ wanted = produced.filter((one) => fromSources.has(one));
3481
+ }
3482
+ for (const one of wanted) {
3483
+ if (one.produced.length > 0)
3484
+ add(call, call, one, "produced", "reflect");
3485
+ }
3486
+ }
3487
+ if (words !== "Proxy") {
3488
+ for (const one of heldMembers(holder))
3489
+ add(call, call, one, "escaped", "reflect");
3490
+ }
3491
+ };
3492
+ // ---- escaped -----------------------------------------------------------------------------
3493
+ /** The stated members `type` holds itself (or a member of its union): `this` of a class with `saving`. */
3494
+ const heldMembers = (type) => {
3495
+ if (targets.members.size === 0)
3496
+ return [];
3497
+ const into = new Set();
3498
+ const base = widened(checker, type) ?? type;
3499
+ for (const member of base.isUnionOrIntersection() ? base.types : [base]) {
3500
+ if (!(member.flags & ts.TypeFlags.Object))
3501
+ continue;
3502
+ for (const [name, list] of targets.members) {
3503
+ questions += 1;
3504
+ const property = checker.getPropertyOfType(member, name);
3505
+ if (property === undefined)
3506
+ continue;
3507
+ const roots = checker.getRootSymbols(property);
3508
+ for (const one of list)
3509
+ if (roots.includes(one.symbol))
3510
+ into.add(one);
3511
+ }
3512
+ }
3513
+ return [...into];
3514
+ };
3515
+ /**
3516
+ * An object literal for a holder whose stated member it writes where no reference names it
3517
+ * (the literal is typed by a union with a function, as a state setter takes), or into which it
3518
+ * spreads a holder.
3519
+ */
3520
+ const literalHolder = (literal) => {
3521
+ const type = contextual(literal);
3522
+ if (type === undefined)
3523
+ return;
3524
+ const held = heldMembers(type);
3525
+ for (const one of held) {
3526
+ const written = literal.properties.some((property) => {
3527
+ if (ts.isSpreadAssignment(property))
3528
+ return heldMembers(typeAt(property.expression)).includes(one);
3529
+ const name = property.name;
3530
+ if (!(ts.isIdentifier(name) || ts.isStringLiteral(name)))
3531
+ return false;
3532
+ if (name.text !== one.stated.word)
3533
+ return false;
3534
+ const symbol = symbolOfReference(name);
3535
+ return (symbol === undefined || !checker.getRootSymbols(resolved(symbol)).includes(one.symbol));
3536
+ });
3537
+ if (written)
3538
+ add(literal, literal, one, "escaped", "literal");
3539
+ }
3540
+ };
3541
+ // ---- decided -----------------------------------------------------------------------------
3542
+ /** A value of a stated alias the code decides by: its declared type, else the object whose tag it is. */
3543
+ const decidedBy = (expression, shown) => {
3544
+ let inner = expression;
3545
+ while (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner))
3546
+ inner = inner.expression;
3547
+ if (ts.isLiteralExpression(inner) ||
3548
+ inner.kind === ts.SyntaxKind.TrueKeyword ||
3549
+ inner.kind === ts.SyntaxKind.FalseKeyword) {
3550
+ return;
3551
+ }
3552
+ const name = ts.isPropertyAccessExpression(inner) ? inner.name : inner;
3553
+ questions += 1;
3554
+ const symbol = ts.isIdentifier(name) ? checker.getSymbolAtLocation(name) : undefined;
3555
+ const declared = symbol !== undefined && symbol.flags & (ts.SymbolFlags.Variable | ts.SymbolFlags.Property)
3556
+ ? checker.getTypeOfSymbol(symbol)
3557
+ : undefined;
3558
+ let found = [
3559
+ ...(declared === undefined ? [] : aliasesOf(declared)),
3560
+ ...aliasesOf(typeAt(inner)),
3561
+ ];
3562
+ if (found.length === 0 &&
3563
+ (ts.isPropertyAccessExpression(inner) || ts.isElementAccessExpression(inner))) {
3564
+ found = aliasesOf(typeAt(inner.expression));
3565
+ }
3566
+ for (const one of new Set(found)) {
3567
+ if (one.decided.length > 0)
3568
+ add(inner, shown, one, "decided", "value");
3569
+ }
3570
+ // A value made from one (`s.toLowerCase()`, `s as string`, `String(s)`, `` `${s}` ``): the
3571
+ // code decides by what is made, not by the value itself.
3572
+ if (found.length === 0) {
3573
+ for (const source of derivedSources(inner)) {
3574
+ for (const one of new Set(aliasesOf(typeAt(source)))) {
3575
+ if (one.decided.length > 0)
3576
+ add(inner, shown, one, "decided", "derived");
3577
+ }
3578
+ }
3579
+ }
3580
+ };
3581
+ /**
3582
+ * The expressions a value is made from, when it is made from another value: the operand of a
3583
+ * cast, the receiver of a method call, the arguments of a call, the parts of a template.
3584
+ */
3585
+ const derivedSources = (expression) => {
3586
+ let inner = expression;
3587
+ while (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner)) {
3588
+ inner = inner.expression;
3589
+ }
3590
+ if (ts.isAsExpression(inner) ||
3591
+ ts.isSatisfiesExpression(inner) ||
3592
+ ts.isTypeAssertionExpression(inner)) {
3593
+ return [inner.expression, ...derivedSources(inner.expression)];
3594
+ }
3595
+ if (ts.isTemplateExpression(inner)) {
3596
+ return inner.templateSpans.flatMap((span) => [
3597
+ span.expression,
3598
+ ...derivedSources(span.expression),
3599
+ ]);
3600
+ }
3601
+ if (ts.isCallExpression(inner)) {
3602
+ const receiver = ts.isPropertyAccessExpression(inner.expression)
3603
+ ? [inner.expression.expression]
3604
+ : [];
3605
+ return [...receiver, ...inner.arguments.filter((one) => !ts.isSpreadElement(one))];
3606
+ }
3607
+ return [];
3608
+ };
3609
+ /**
3610
+ * A method called on a value of an alias the code decides by (`s.startsWith("p")`): what it
3611
+ * gives is made from the value.
3612
+ */
3613
+ const derivedCall = (call) => {
3614
+ if (!ts.isPropertyAccessExpression(call.expression))
3615
+ return;
3616
+ for (const one of new Set(aliasesOf(typeAt(call.expression.expression)))) {
3617
+ if (one.decided.length > 0)
3618
+ add(call, call, one, "decided", "derived");
3619
+ }
3620
+ };
3621
+ /**
3622
+ * A value of a stated alias given to a call that decides by it, to a parameter whose type does
3623
+ * not hold the alias: `list.includes(s)`, `map.get(s)`, `Object.is(s, …)`.
3624
+ */
3625
+ const decidingCall = (call) => {
3626
+ const callee = call.expression;
3627
+ const words = calleeWords(call);
3628
+ const method = ts.isPropertyAccessExpression(callee) ? callee.name.text : undefined;
3629
+ // Besides the methods known to decide, a call that answers yes or no (`pattern.test(s)`,
3630
+ // `Object.hasOwn(labels, s)`) or takes the value as a key (`Reflect.get(labels, s)`).
3631
+ // A generic key (`Reflect.get<T, P extends PropertyKey>`) is inferred as the value's own
3632
+ // type, so these read the value as a key whatever the parameter is inferred as.
3633
+ const keyed = words !== undefined && KEYED_CALLS.has(words);
3634
+ const known = keyed || words === "Object.is" || (method !== undefined && DECIDING_METHODS.has(method));
3635
+ const answers = known || (typeAt(call).flags & ts.TypeFlags.BooleanLike) !== 0;
3636
+ for (const argument of call.arguments) {
3637
+ if (ts.isSpreadElement(argument))
3638
+ continue;
3639
+ const target = contextual(argument);
3640
+ if (!answers && (target === undefined || !isPropertyKey(target)))
3641
+ continue;
3642
+ const wanted = target === undefined ? [] : aliasesIn(target);
3643
+ for (const one of new Set(aliasesOf(typeAt(argument)))) {
3644
+ if (one.decided.length > 0 && (keyed || !wanted.includes(one))) {
3645
+ add(argument, call, one, "decided", "call");
3646
+ }
3647
+ }
3648
+ }
3649
+ };
3650
+ /** `PropertyKey`: `string | number | symbol`, the type of a key (`Reflect.get`'s second parameter). */
3651
+ const isPropertyKey = (given) => {
3652
+ // `Reflect.get<T, P extends PropertyKey>(…)`: the parameter's constraint says it.
3653
+ const type = given.flags & ts.TypeFlags.TypeParameter
3654
+ ? (checker.getBaseConstraintOfType(given) ?? given)
3655
+ : given;
3656
+ return (type.isUnion() &&
3657
+ type.types.some((one) => (one.flags & ts.TypeFlags.ESSymbolLike) !== 0) &&
3658
+ type.types.some((one) => (one.flags & ts.TypeFlags.StringLike) !== 0));
3659
+ };
3660
+ /** A union of literals only (`"pending" | "paid"`): a closed set of values. */
3661
+ const isClosedLiterals = (type) => type.isUnion() &&
3662
+ type.types.every((member) => (member.flags &
3663
+ (ts.TypeFlags.Literal |
3664
+ ts.TypeFlags.EnumLiteral |
3665
+ ts.TypeFlags.Undefined |
3666
+ ts.TypeFlags.Null)) !==
3667
+ 0);
3668
+ /**
3669
+ * A value of a stated alias handed to a closed union that does not hold the alias (a parameter
3670
+ * or variable typed `"pending" | "paid"`): the code there decides by the value as if it could
3671
+ * hold nothing else.
3672
+ */
3673
+ const handedToClosed = (value, target, shown, via) => {
3674
+ if (target === undefined || !isClosedLiterals(target))
3675
+ return;
3676
+ const wanted = aliasesIn(target);
3677
+ for (const one of new Set(aliasesOf(typeAt(value)))) {
3678
+ if (one.decided.length > 0 && !wanted.includes(one))
3679
+ add(value, shown, one, "decided", via);
3680
+ }
3681
+ };
3682
+ const isRelation = (kind) => kind === ts.SyntaxKind.LessThanToken ||
3683
+ kind === ts.SyntaxKind.LessThanEqualsToken ||
3684
+ kind === ts.SyntaxKind.GreaterThanToken ||
3685
+ kind === ts.SyntaxKind.GreaterThanEqualsToken;
3686
+ const isEquality = (kind) => kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
3687
+ kind === ts.SyntaxKind.EqualsEqualsToken ||
3688
+ kind === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
3689
+ kind === ts.SyntaxKind.ExclamationEqualsToken;
3690
+ const producing = targets.aliases.some((one) => one.produced.length > 0);
3691
+ const deciding = targets.aliases.some((one) => one.decided.length > 0);
3692
+ const escaping = targets.members.size > 0;
3693
+ const visit = (node) => {
3694
+ if (stopped !== undefined)
3695
+ return;
3696
+ if (questions >= budget) {
3697
+ stopped = node;
3698
+ return;
3699
+ }
3700
+ if (producing) {
3701
+ if (ts.isReturnStatement(node) && node.expression !== undefined)
3702
+ returned(node.expression);
3703
+ else if (ts.isArrowFunction(node) && !ts.isBlock(node.body))
3704
+ given(node.body, contextual(node.body));
3705
+ else if (ts.isYieldExpression(node) && node.expression !== undefined) {
3706
+ given(node.expression, contextual(node.expression));
3707
+ }
3708
+ else if ((ts.isVariableDeclaration(node) ||
3709
+ ts.isPropertyDeclaration(node) ||
3710
+ ts.isParameter(node) ||
3711
+ ts.isBindingElement(node)) &&
3712
+ node.initializer !== undefined) {
3713
+ given(node.initializer, contextual(node.initializer));
3714
+ if (ts.isPropertyDeclaration(node)) {
3715
+ for (const type of inheritedTypes(node))
3716
+ given(node.initializer, type, "override");
3717
+ }
3718
+ }
3719
+ else if (ts.isBinaryExpression(node) &&
3720
+ isAssignmentOperator(node.operatorToken.kind) &&
3721
+ !ts.isObjectLiteralExpression(node.left) &&
3722
+ !ts.isArrayLiteralExpression(node.left)) {
3723
+ given(node.right, contextual(node.right) ?? typeAt(node.left));
3724
+ }
3725
+ else if (ts.isPropertyAssignment(node))
3726
+ given(node.initializer, contextual(node.initializer));
3727
+ else if (ts.isShorthandPropertyAssignment(node))
3728
+ given(node.name, contextual(node.name));
3729
+ else if (ts.isSpreadAssignment(node) && ts.isObjectLiteralExpression(node.parent)) {
3730
+ spreadInto(node.expression, contextual(node.parent), node.parent);
3731
+ }
3732
+ else if (ts.isArrayLiteralExpression(node)) {
3733
+ for (const element of node.elements) {
3734
+ if (ts.isSpreadElement(element)) {
3735
+ const target = contextual(node);
3736
+ const item = target === undefined ? undefined : elementOf(target);
3737
+ const wanted = item === undefined ? [] : aliasesIn(item);
3738
+ const source = typeAt(element.expression);
3739
+ const any = (source.flags & ts.TypeFlags.Any) !== 0;
3740
+ const own = any ? [] : aliasesIn(elementOf(source) ?? source);
3741
+ for (const one of wanted) {
3742
+ if (one.produced.length > 0 && !own.includes(one)) {
3743
+ add(element, node, one, "produced", any ? "any" : "spread");
3744
+ }
3745
+ }
3746
+ }
3747
+ else if (!ts.isOmittedExpression(element)) {
3748
+ given(element, contextual(element));
3749
+ }
3750
+ }
3751
+ }
3752
+ else if (ts.isJsxAttribute(node) && node.initializer !== undefined) {
3753
+ const value = ts.isJsxExpression(node.initializer)
3754
+ ? node.initializer.expression
3755
+ : node.initializer;
3756
+ if (value !== undefined && ts.isExpression(value))
3757
+ given(value, contextual(value));
3758
+ }
3759
+ else if (ts.isJsxSpreadAttribute(node)) {
3760
+ // The element shows what the spread is given to: `<Show {...props} />`.
3761
+ spreadInto(node.expression, contextual(node.parent), node.parent.parent);
3762
+ }
3763
+ else if (ts.isAsExpression(node) ||
3764
+ ts.isTypeAssertionExpression(node) ||
3765
+ ts.isSatisfiesExpression(node)) {
3766
+ const constant = ts.isTypeReferenceNode(node.type) &&
3767
+ ts.isIdentifier(node.type.typeName) &&
3768
+ node.type.typeName.text === "const";
3769
+ if (!constant) {
3770
+ questions += 1;
3771
+ given(node.expression, checker.getTypeFromTypeNode(node.type), "cast");
3772
+ }
3773
+ }
3774
+ else if (ts.isForOfStatement(node) && !ts.isVariableDeclarationList(node.initializer)) {
3775
+ const target = typeAt(node.initializer);
3776
+ const item = elementOf(typeAt(node.expression));
3777
+ const wanted = aliasesIn(target).filter((one) => one.produced.length > 0);
3778
+ const own = item === undefined ? [] : aliasesIn(item);
3779
+ for (const one of wanted) {
3780
+ if (!own.includes(one))
3781
+ add(node.initializer, node, one, "produced", "for-of");
3782
+ }
3783
+ }
3784
+ // `p--`, `p += 1`, `id += s`: the place typed by the brand gets a value computed from it,
3785
+ // which no builder made.
3786
+ const computed = ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
3787
+ (node.operator === ts.SyntaxKind.PlusPlusToken ||
3788
+ node.operator === ts.SyntaxKind.MinusMinusToken)) ||
3789
+ (ts.isBinaryExpression(node) &&
3790
+ node.operatorToken.kind >= ts.SyntaxKind.FirstCompoundAssignment &&
3791
+ node.operatorToken.kind <= ts.SyntaxKind.LastCompoundAssignment &&
3792
+ // `??=`, `||=`, `&&=` give the right side as it is, read as an assignment.
3793
+ node.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionEqualsToken &&
3794
+ node.operatorToken.kind !== ts.SyntaxKind.BarBarEqualsToken &&
3795
+ node.operatorToken.kind !== ts.SyntaxKind.AmpersandAmpersandEqualsToken);
3796
+ if (computed) {
3797
+ const target = ts.isBinaryExpression(node) ? node.left : node.operand;
3798
+ for (const one of aliasesIn(typeAt(target))) {
3799
+ if (one.produced.length > 0)
3800
+ add(node, node, one, "produced", "derived");
3801
+ }
3802
+ }
3803
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
3804
+ for (const argument of node.arguments ?? []) {
3805
+ if (ts.isSpreadElement(argument))
3806
+ spreadArgument(node, argument);
3807
+ else
3808
+ given(argument, contextual(argument));
3809
+ }
3810
+ genericCall(node);
3811
+ if (ts.isCallExpression(node))
3812
+ indirectCall(node);
3813
+ }
3814
+ }
3815
+ if ((producing || escaping) && (ts.isCallExpression(node) || ts.isNewExpression(node))) {
3816
+ const words = calleeWords(node);
3817
+ if (words !== undefined &&
3818
+ (REFLECT_WRITES.has(words) || (words === "Proxy" && ts.isNewExpression(node)))) {
3819
+ reflectWrite(node, words);
3820
+ }
3821
+ }
3822
+ if (escaping) {
3823
+ if (ts.isObjectLiteralExpression(node))
3824
+ literalHolder(node);
3825
+ else if (ts.isBinaryExpression(node) &&
3826
+ isAssignmentOperator(node.operatorToken.kind) &&
3827
+ ts.isElementAccessExpression(node.left) &&
3828
+ !ts.isStringLiteralLike(node.left.argumentExpression)) {
3829
+ for (const one of heldMembers(typeAt(node.left.expression))) {
3830
+ add(node.left, node, one, "escaped", "reflect");
3831
+ }
3832
+ }
3833
+ }
3834
+ if (deciding) {
3835
+ if (ts.isSwitchStatement(node))
3836
+ decidedBy(node.expression, node.expression);
3837
+ else if (ts.isBinaryExpression(node) &&
3838
+ (isEquality(node.operatorToken.kind) || isRelation(node.operatorToken.kind))) {
3839
+ decidedBy(node.left, node);
3840
+ decidedBy(node.right, node);
3841
+ }
3842
+ else if (ts.isBinaryExpression(node) &&
3843
+ node.operatorToken.kind === ts.SyntaxKind.InKeyword) {
3844
+ decidedBy(node.left, node);
3845
+ }
3846
+ else if (ts.isElementAccessExpression(node) &&
3847
+ !ts.isStringLiteralLike(node.argumentExpression) &&
3848
+ !ts.isNumericLiteral(node.argumentExpression)) {
3849
+ decidedBy(node.argumentExpression, node);
3850
+ }
3851
+ else if (ts.isCallExpression(node)) {
3852
+ decidingCall(node);
3853
+ derivedCall(node);
3854
+ for (const argument of node.arguments) {
3855
+ if (!ts.isSpreadElement(argument)) {
3856
+ handedToClosed(argument, contextual(argument), node, "call");
3857
+ }
3858
+ }
3859
+ }
3860
+ else if (ts.isVariableDeclaration(node) &&
3861
+ node.type !== undefined &&
3862
+ node.initializer !== undefined) {
3863
+ handedToClosed(node.initializer, typeAt(node.name), node, "value");
3864
+ }
3865
+ }
3866
+ ts.forEachChild(node, visit);
3867
+ };
3868
+ visit(sourceFile);
3869
+ if (stopped !== undefined) {
3870
+ const at = stopped;
3871
+ for (const one of targets.aliases) {
3872
+ add(at, at, one, "produced", "stopped");
3873
+ add(at, at, one, "decided", "stopped");
3874
+ }
3875
+ for (const one of [...targets.members.values()].flat())
3876
+ add(at, at, one, "escaped", "stopped");
3877
+ }
3878
+ return found.sort((a, b) => a.node.getStart(sourceFile) - b.node.getStart(sourceFile) ||
3879
+ a.node.end - b.node.end ||
3880
+ compareIds(a.declaration, b.declaration) ||
3881
+ compareIds(a.trait, b.trait) ||
3882
+ compareIds(a.form, b.form));
3883
+ };
3884
+ return { referencesIn, flowsIn };
3885
+ }
3886
+ function compareIds(a, b) {
3887
+ return a < b ? -1 : a > b ? 1 : 0;
3888
+ }
3889
+ /** Whether every value of `type` is a primitive, or an array or tuple of them, `depth` levels down. */
3890
+ function onlyPrimitives(checker, found, depth) {
3891
+ const type = widened(checker, found);
3892
+ if (type === undefined || depth > 3)
3893
+ return false;
3894
+ const members = type.isUnion() ? type.types : [type];
3895
+ return members.every((member) => {
3896
+ if (member.flags & PRIMITIVE_FLAGS)
3897
+ return true;
3898
+ if (!isTypeReference(member) || !checker.isArrayLikeType(member))
3899
+ return false;
3900
+ return checker
3901
+ .getTypeArguments(member)
3902
+ .every((argument) => onlyPrimitives(checker, argument, depth + 1));
3903
+ });
3904
+ }
3905
+ /**
3906
+ * TypeScript's errors for a function whose end can be reached although it must return a value:
3907
+ * TS2366, TS2355, TS2534 and TS7030 (`TypeQueries.reportsReachableEnd`).
3908
+ */
3909
+ const REACHABLE_END_CODES = new Set([2366, 2355, 2534, 7030]);
3910
+ /**
3911
+ * The platform's packages every project has: Node's types. TypeScript's own lib is the platform
3912
+ * too; the config's `platform` adds more (`bun-types`, `@cloudflare/workers-types`).
3913
+ */
3914
+ export const PLATFORM_PACKAGES = ["@types/node"];
3915
+ /** `@types/node` as a path pattern: `/node_modules/@types/node/`, either slash. */
3916
+ function packagePathPattern(name) {
3917
+ const escaped = name.split("/").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3918
+ return `[\\\\/]node_modules[\\\\/]${escaped.join("[\\\\/]")}[\\\\/]`;
3919
+ }
3920
+ /**
3921
+ * The test of whether a file is of the platform: TypeScript's own lib, or a file of one of the
3922
+ * platform's packages (`PLATFORM_PACKAGES` and the config's `platform`).
3923
+ */
3924
+ function platformFiles(program, extra) {
3925
+ const names = [...new Set([...PLATFORM_PACKAGES, ...extra])];
3926
+ const pattern = new RegExp(names.map(packagePathPattern).join("|"));
3927
+ return (file) => program.isSourceFileDefaultLibrary(file) || pattern.test(file.fileName);
3928
+ }
3929
+ /** Properties of the platform's types that are plain data on the closed list, as `<type>.<name>`. */
3930
+ const PLATFORM_PROPERTIES = new Set([
3931
+ "Array.length",
3932
+ "ReadonlyArray.length",
3933
+ "String.length",
3934
+ "Map.size",
3935
+ "ReadonlyMap.size",
3936
+ "Set.size",
3937
+ "ReadonlySet.size",
3938
+ "AbortController.signal",
3939
+ "AbortSignal.aborted",
3940
+ "Error.message",
3941
+ "Error.name",
3942
+ ]);
3943
+ /** Platform values whose every property is a constant (`Math.PI`, `Number.MAX_SAFE_INTEGER`). */
3944
+ const PLATFORM_CONSTANTS = new Set(["Math", "NumberConstructor"]);
3945
+ /** The members of a type, a type parameter widened to its constraint, without `null` and `undefined`. */
3946
+ function definedMembers(checker, type) {
3947
+ const wide = widened(checker, type);
3948
+ if (wide === undefined)
3949
+ return undefined;
3950
+ const defined = checker.getNonNullableType(wide);
3951
+ if (defined.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) {
3952
+ return undefined;
3953
+ }
3954
+ return defined.isUnion() ? defined.types : [defined];
3955
+ }
3956
+ /** Whether `type` is a number type: `number`, a literal, a numeric enum, or an intersection with one. */
3957
+ function isNumberType(type) {
3958
+ if (type.isIntersection())
3959
+ return type.types.some(isNumberType);
3960
+ return (type.flags & ts.TypeFlags.NumberLike) !== 0;
3961
+ }
3962
+ const OBJECT = { kind: "global", name: "Object" };
3963
+ const UNDEFINED = { kind: "undefined" };
3964
+ /** The type nodes whose constructor is fixed by their kind (`number` is `Number`). */
3965
+ const KEYWORD_METADATA = new Map([
3966
+ [ts.SyntaxKind.VoidKeyword, UNDEFINED],
3967
+ [ts.SyntaxKind.UndefinedKeyword, UNDEFINED],
3968
+ [ts.SyntaxKind.NeverKeyword, UNDEFINED],
3969
+ [ts.SyntaxKind.FunctionType, { kind: "global", name: "Function" }],
3970
+ [ts.SyntaxKind.ConstructorType, { kind: "global", name: "Function" }],
3971
+ [ts.SyntaxKind.ArrayType, { kind: "global", name: "Array" }],
3972
+ [ts.SyntaxKind.TupleType, { kind: "global", name: "Array" }],
3973
+ [ts.SyntaxKind.BooleanKeyword, { kind: "global", name: "Boolean" }],
3974
+ [ts.SyntaxKind.TemplateLiteralType, { kind: "global", name: "String" }],
3975
+ [ts.SyntaxKind.StringKeyword, { kind: "global", name: "String" }],
3976
+ [ts.SyntaxKind.NumberKeyword, { kind: "global", name: "Number" }],
3977
+ [ts.SyntaxKind.BigIntKeyword, { kind: "global", name: "BigInt" }],
3978
+ [ts.SyntaxKind.SymbolKeyword, { kind: "global", name: "Symbol" }],
3979
+ ]);
3980
+ function global(name) {
3981
+ return { kind: "global", name };
3982
+ }
3983
+ function sameMetadata(a, b) {
3984
+ switch (a.kind) {
3985
+ case "global":
3986
+ return b.kind === "global" && a.name === b.name;
3987
+ case "undefined":
3988
+ return b.kind === "undefined";
3989
+ case "class":
3990
+ return b.kind === "class" && a.name === b.name;
3991
+ case "unresolved":
3992
+ return b.kind === "unresolved" && a.name === b.name;
3993
+ default: {
3994
+ const unreachable = a;
3995
+ return unreachable;
3996
+ }
3997
+ }
3998
+ }
3999
+ /** The compiler's `serializeTypeNode`, giving the constructor instead of an expression. */
4000
+ function serializedTypeNode(context, given) {
4001
+ if (given === undefined)
4002
+ return OBJECT;
4003
+ let node = given;
4004
+ while (ts.isParenthesizedTypeNode(node))
4005
+ node = node.type;
4006
+ const keyword = KEYWORD_METADATA.get(node.kind);
4007
+ if (keyword !== undefined)
4008
+ return keyword;
4009
+ if (ts.isTypePredicateNode(node)) {
4010
+ return node.assertsModifier === undefined ? global("Boolean") : UNDEFINED;
4011
+ }
4012
+ if (ts.isLiteralTypeNode(node))
4013
+ return serializedLiteral(node.literal);
4014
+ if (ts.isTypeReferenceNode(node))
4015
+ return serializedReference(context, node.typeName);
4016
+ if (ts.isUnionTypeNode(node))
4017
+ return serializedMembers(context, node.types, false);
4018
+ if (ts.isIntersectionTypeNode(node))
4019
+ return serializedMembers(context, node.types, true);
4020
+ if (ts.isConditionalTypeNode(node)) {
4021
+ return serializedMembers(context, [node.trueType, node.falseType], false);
4022
+ }
4023
+ if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
4024
+ return serializedTypeNode(context, node.type);
4025
+ }
4026
+ return OBJECT;
4027
+ }
4028
+ function serializedLiteral(literal) {
4029
+ if (ts.isPrefixUnaryExpression(literal)) {
4030
+ return ts.isBigIntLiteral(literal.operand) ? global("BigInt") : global("Number");
4031
+ }
4032
+ if (ts.isStringLiteral(literal) || ts.isNoSubstitutionTemplateLiteral(literal)) {
4033
+ return global("String");
4034
+ }
4035
+ if (ts.isNumericLiteral(literal))
4036
+ return global("Number");
4037
+ if (ts.isBigIntLiteral(literal))
4038
+ return global("BigInt");
4039
+ if (literal.kind === ts.SyntaxKind.TrueKeyword || literal.kind === ts.SyntaxKind.FalseKeyword) {
4040
+ return global("Boolean");
4041
+ }
4042
+ return UNDEFINED;
4043
+ }
4044
+ /** The compiler's `serializeUnionOrIntersectionConstituents`. */
4045
+ function serializedMembers(context, types, isIntersection) {
4046
+ let serialized;
4047
+ for (const written of types) {
4048
+ let member = written;
4049
+ while (ts.isParenthesizedTypeNode(member))
4050
+ member = member.type;
4051
+ if (member.kind === ts.SyntaxKind.NeverKeyword) {
4052
+ if (isIntersection)
4053
+ return UNDEFINED;
4054
+ continue;
4055
+ }
4056
+ if (member.kind === ts.SyntaxKind.UnknownKeyword) {
4057
+ if (!isIntersection)
4058
+ return OBJECT;
4059
+ continue;
4060
+ }
4061
+ if (member.kind === ts.SyntaxKind.AnyKeyword)
4062
+ return OBJECT;
4063
+ const nullish = member.kind === ts.SyntaxKind.UndefinedKeyword ||
4064
+ (ts.isLiteralTypeNode(member) && member.literal.kind === ts.SyntaxKind.NullKeyword);
4065
+ if (nullish && !context.keepsNullish)
4066
+ continue;
4067
+ const one = serializedTypeNode(context, member);
4068
+ if (one.kind === "global" && one.name === "Object")
4069
+ return one;
4070
+ if (serialized === undefined)
4071
+ serialized = one;
4072
+ else if (!sameMetadata(serialized, one))
4073
+ return OBJECT;
4074
+ }
4075
+ return serialized ?? UNDEFINED;
4076
+ }
4077
+ /** An import or export that brings only a type (`import type`, `import { type X }`). */
4078
+ function isTypeOnlyAlias(symbol) {
4079
+ const declarations = symbol.declarations ?? [];
4080
+ return declarations.length > 0 && declarations.every(ts.isTypeOnlyImportOrExportDeclaration);
4081
+ }
4082
+ /** The compiler's `getTypeReferenceSerializationKind` and `serializeTypeReferenceNode`. */
4083
+ function serializedReference(context, typeName) {
4084
+ const { checker } = context;
4085
+ const name = typeName.getText();
4086
+ const resolve = (symbol) => symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias
4087
+ ? checker.getAliasedSymbol(symbol)
4088
+ : symbol;
4089
+ // The name as a value (what the emitted code would reach at run time) and as a type.
4090
+ const written = ts.isIdentifier(typeName)
4091
+ ? checker.resolveName(typeName.text, typeName, ts.SymbolFlags.Value, false)
4092
+ : checker.getSymbolAtLocation(typeName);
4093
+ const valueSymbol = written !== undefined && written.flags & (ts.SymbolFlags.Value | ts.SymbolFlags.Alias)
4094
+ ? written
4095
+ : undefined;
4096
+ const typeSymbol = resolve(checker.getSymbolAtLocation(typeName));
4097
+ const value = resolve(valueSymbol);
4098
+ const isTypeOnly = valueSymbol !== undefined && isTypeOnlyAlias(valueSymbol);
4099
+ if (value !== undefined && value === typeSymbol) {
4100
+ const promise = checker.resolveName("Promise", undefined, ts.SymbolFlags.Value, false);
4101
+ if (promise !== undefined && value === promise)
4102
+ return global("Promise");
4103
+ const constructorType = checker.getTypeOfSymbol(value);
4104
+ if (constructorType.getConstructSignatures().length > 0) {
4105
+ return isTypeOnly
4106
+ ? global("Function")
4107
+ : { kind: "class", name, symbol: context.refOf(value) };
4108
+ }
4109
+ }
4110
+ // A name that does not resolve gives no symbol, or the checker's unknown symbol (no declarations).
4111
+ if (typeSymbol === undefined || (typeSymbol.declarations ?? []).length === 0) {
4112
+ return isTypeOnly ? OBJECT : { kind: "unresolved", name };
4113
+ }
4114
+ const type = checker.getDeclaredTypeOfSymbol(typeSymbol);
4115
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
4116
+ return OBJECT;
4117
+ const isKind = (flags, target) => (type.flags & flags) !== 0 || checker.isTypeAssignableTo(type, target);
4118
+ if (isKind(ts.TypeFlags.Void, checker.getVoidType()) ||
4119
+ isKind(ts.TypeFlags.Undefined, checker.getUndefinedType()) ||
4120
+ isKind(ts.TypeFlags.Null, checker.getNullType()) ||
4121
+ isKind(ts.TypeFlags.Never, checker.getNeverType())) {
4122
+ return UNDEFINED;
4123
+ }
4124
+ if (isKind(ts.TypeFlags.BooleanLike, checker.getBooleanType()))
4125
+ return global("Boolean");
4126
+ if (isKind(ts.TypeFlags.NumberLike, checker.getNumberType()))
4127
+ return global("Number");
4128
+ if (isKind(ts.TypeFlags.BigIntLike, checker.getBigIntType()))
4129
+ return global("BigInt");
4130
+ if (isKind(ts.TypeFlags.StringLike, checker.getStringType()))
4131
+ return global("String");
4132
+ if (checker.isTupleType(type))
4133
+ return global("Array");
4134
+ if (isKind(ts.TypeFlags.ESSymbolLike, checker.getESSymbolType()))
4135
+ return global("Symbol");
4136
+ if (type.flags & ts.TypeFlags.Object && type.getCallSignatures().length > 0) {
4137
+ return global("Function");
4138
+ }
4139
+ if (checker.isArrayType(type))
4140
+ return global("Array");
4141
+ return OBJECT;
4142
+ }
4143
+ /** The type node TypeScript serializes for a parameter: a rest parameter's element type. */
4144
+ function metadataTypeNode(node) {
4145
+ if (!ts.isParameter(node) || node.dotDotDotToken === undefined)
4146
+ return node.type;
4147
+ const type = node.type;
4148
+ if (type === undefined)
4149
+ return undefined;
4150
+ if (ts.isArrayTypeNode(type))
4151
+ return type.elementType;
4152
+ if (ts.isTypeReferenceNode(type) && type.typeArguments?.length === 1) {
4153
+ return type.typeArguments[0];
4154
+ }
4155
+ return undefined;
4156
+ }
4157
+ function decoratorMetadata(options, context, node) {
4158
+ if (options.experimentalDecorators !== true || options.emitDecoratorMetadata !== true) {
4159
+ return { kind: "not-emitted" };
4160
+ }
4161
+ const typeNode = metadataTypeNode(node);
4162
+ return {
4163
+ kind: "emitted",
4164
+ type: serializedTypeNode({ ...context, keepsNullish: checksNulls(options) }, typeNode),
4165
+ withoutNullish: serializedTypeNode({ ...context, keepsNullish: false }, typeNode),
4166
+ };
4167
+ }
4168
+ export function createTypeQueries(program, own,
4169
+ /** The project folder qualified ids are relative to. */
4170
+ root, packageOf, isEntry, dependenciesOf,
4171
+ /** Packages the config adds to the platform (`Config.platform`). */
4172
+ platform = []) {
4173
+ const isPlatformFile = platformFiles(program, platform);
4174
+ // Module names resolve as from the project's tsconfig (a file there need not exist).
4175
+ const { configFilePath } = program.getCompilerOptions();
4176
+ const resolveFrom = path.join(typeof configFilePath === "string" ? path.dirname(configFilePath) : root, "__stateward_types__.ts");
4177
+ // The only place in the codebase that reaches the type checker. Created on the first question:
4178
+ // a run whose results all come from the cache never builds one.
4179
+ let created;
4180
+ const typeChecker = () => (created ??= program.getTypeChecker());
4181
+ const factNames = createFactNames(typeChecker, program, packageOf, resolveFrom, own);
4182
+ const factModuleOf = createFactModules({
4183
+ checker: typeChecker,
4184
+ program,
4185
+ names: factNames,
4186
+ own,
4187
+ isPlatformFile,
4188
+ packageOf,
4189
+ });
4190
+ const declarations = new Map();
4191
+ const declaredTraits = new Map();
4192
+ let anyMarker;
4193
+ let ledgerScan;
4194
+ // The starts of TypeScript's "end of the function can be reached" errors, per file asked about.
4195
+ const reachableEndErrors = new WeakMap();
4196
+ let declaredDispose;
4197
+ let renamedNames;
4198
+ const idFileName = idFileNames(root);
4199
+ // symbolAt is asked about the same node by several rules (on excalidraw 570,000 questions about
4200
+ // 170,000 nodes, 52,000 symbols): the program does not change under these queries, so each
4201
+ // node's answer and each symbol's ref are computed once.
4202
+ const refsByNode = new WeakMap();
4203
+ const refsBySymbol = new WeakMap();
4204
+ const refOfSymbol = (symbol) => {
4205
+ const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
4206
+ if (declaration === undefined)
4207
+ return undefined;
4208
+ const id = `${idFileName(declaration.getSourceFile().fileName)}#${declarationPath(declaration)}`;
4209
+ declarations.set(id, declaration);
4210
+ return { id, name: symbol.getName() };
4211
+ };
4212
+ const refAnswer = (node) => {
4213
+ const found = typeChecker().getSymbolAtLocation(node);
4214
+ if (found === undefined)
4215
+ return NO_REF;
1538
4216
  const symbol = found.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(found) : found;
1539
4217
  let entry = refsBySymbol.get(symbol);
1540
4218
  if (entry === undefined) {
1541
4219
  entry = { ref: refOfSymbol(symbol) };
1542
4220
  refsBySymbol.set(symbol, entry);
1543
4221
  }
1544
- return entry;
4222
+ return entry;
4223
+ };
4224
+ // The platform's types that a class or interface of the project extends or implements: a value
4225
+ // typed by one of them may be the project's own code.
4226
+ let extendedPlatform;
4227
+ const platformExtended = () => {
4228
+ if (extendedPlatform !== undefined)
4229
+ return extendedPlatform;
4230
+ const checker = typeChecker();
4231
+ const found = new Set();
4232
+ const visit = (node) => {
4233
+ if (ts.isHeritageClause(node)) {
4234
+ for (const written of node.types) {
4235
+ const symbol = checker.getTypeAtLocation(written).getSymbol();
4236
+ const declarations = symbol?.declarations ?? [];
4237
+ if (symbol !== undefined &&
4238
+ declarations.length > 0 &&
4239
+ declarations.every((one) => isPlatformFile(one.getSourceFile()))) {
4240
+ found.add(symbol);
4241
+ }
4242
+ }
4243
+ return;
4244
+ }
4245
+ ts.forEachChild(node, visit);
4246
+ };
4247
+ for (const file of program.getSourceFiles()) {
4248
+ if (!own.has(toTypeScriptPath(file.fileName)))
4249
+ continue;
4250
+ if (!file.text.includes("extends") && !file.text.includes("implements"))
4251
+ continue;
4252
+ visit(file);
4253
+ }
4254
+ extendedPlatform = found;
4255
+ return found;
4256
+ };
4257
+ /** The platform's name of one type, as `platformTypeOf` says it. */
4258
+ const platformNameOfType = (type) => {
4259
+ if (type.flags & ts.TypeFlags.StringLike)
4260
+ return "String";
4261
+ // A branded string (`string & { … }`): its string part.
4262
+ if (type.isIntersection() && type.types.some((part) => part.flags & ts.TypeFlags.StringLike)) {
4263
+ return "String";
4264
+ }
4265
+ if (type.flags & ts.TypeFlags.NumberLike)
4266
+ return "Number";
4267
+ if (type.flags & ts.TypeFlags.BigIntLike)
4268
+ return "BigInt";
4269
+ if (type.flags & ts.TypeFlags.BooleanLike)
4270
+ return "Boolean";
4271
+ if ((type.flags & ts.TypeFlags.Object) === 0)
4272
+ return undefined;
4273
+ if (typeChecker().isTupleType(type))
4274
+ return "Array";
4275
+ const symbol = type.getSymbol();
4276
+ const declarations = symbol?.declarations ?? [];
4277
+ if (symbol === undefined ||
4278
+ declarations.length === 0 ||
4279
+ !declarations.every((one) => isPlatformFile(one.getSourceFile())) ||
4280
+ platformExtended().has(symbol)) {
4281
+ return undefined;
4282
+ }
4283
+ return symbol.getName();
4284
+ };
4285
+ const platformNameOf = (type) => {
4286
+ const members = definedMembers(typeChecker(), type);
4287
+ if (members === undefined)
4288
+ return undefined;
4289
+ const names = new Set(members.map(platformNameOfType));
4290
+ const [only] = names;
4291
+ return names.size === 1 ? only : undefined;
4292
+ };
4293
+ /** Whether reading `property` from a value of type `receiver` runs no code and cannot throw. */
4294
+ const plainProperty = (property, receiver) => {
4295
+ const declarations = property.declarations ?? [];
4296
+ if (declarations.length === 0) {
4297
+ // A key of a mapped type with no declaration of its own (`Record<"a" | "b", number>`).
4298
+ const members = definedMembers(typeChecker(), receiver);
4299
+ return (members?.every((member) => "objectFlags" in member &&
4300
+ typeof member.objectFlags === "number" &&
4301
+ (member.objectFlags & ts.ObjectFlags.Mapped) !== 0) === true);
4302
+ }
4303
+ if (declarations.some((one) => ts.isGetAccessor(one) || ts.isSetAccessor(one)))
4304
+ return false;
4305
+ if (declarations.every((one) => isPlatformFile(one.getSourceFile()))) {
4306
+ const owner = platformNameOf(receiver);
4307
+ return (owner !== undefined &&
4308
+ (PLATFORM_CONSTANTS.has(owner) || PLATFORM_PROPERTIES.has(`${owner}.${property.getName()}`)));
4309
+ }
4310
+ const members = definedMembers(typeChecker(), receiver);
4311
+ if (members === undefined)
4312
+ return false;
4313
+ const inModule = members.every((member) => ((member.getSymbol()?.flags ?? 0) & (ts.SymbolFlags.ValueModule | ts.SymbolFlags.Enum)) !==
4314
+ 0);
4315
+ if (inModule) {
4316
+ return declarations.every((one) => ts.isEnumMember(one) ||
4317
+ ts.isVariableDeclaration(one) ||
4318
+ ts.isFunctionDeclaration(one) ||
4319
+ ts.isClassDeclaration(one));
4320
+ }
4321
+ // A member declared as a property is read as one, as far as the declared types say: a class
4322
+ // that implements an interface may give it as a getter, which this does not see.
4323
+ return declarations.every((one) => ts.isPropertyDeclaration(one) ||
4324
+ (ts.isParameter(one) && ts.isConstructorDeclaration(one.parent)) ||
4325
+ ts.isPropertyAssignment(one) ||
4326
+ ts.isShorthandPropertyAssignment(one) ||
4327
+ ts.isPropertySignature(one));
4328
+ };
4329
+ const arrayElements = (type) => {
4330
+ const checker = typeChecker();
4331
+ const members = definedMembers(checker, type);
4332
+ if (members === undefined)
4333
+ return undefined;
4334
+ let primitives = true;
4335
+ for (const member of members) {
4336
+ const tuple = checker.isTupleType(member);
4337
+ const name = tuple ? "Array" : platformNameOfType(member);
4338
+ if (name !== "Array" && name !== "ReadonlyArray")
4339
+ return undefined;
4340
+ if (!isTypeReference(member))
4341
+ return undefined;
4342
+ for (const element of checker.getTypeArguments(member)) {
4343
+ const wide = widened(checker, element);
4344
+ const parts = wide === undefined ? [] : wide.isUnion() ? wide.types : [wide];
4345
+ if (wide === undefined || !parts.every((part) => (part.flags & PRIMITIVE_FLAGS) !== 0)) {
4346
+ primitives = false;
4347
+ }
4348
+ }
4349
+ }
4350
+ return primitives ? "primitives" : "values";
1545
4351
  };
1546
4352
  return {
1547
4353
  symbolAt(node) {
@@ -1558,6 +4364,23 @@ root, packageOf, isEntry, dependenciesOf) {
1558
4364
  },
1559
4365
  isOwnFile: (file) => own.has(toTypeScriptPath(file)),
1560
4366
  packageOf: (file) => packageOf(toTypeScriptPath(file)),
4367
+ factTarget: (module, name) => factNames.target(module, name),
4368
+ factNames: (module) => factNames.names(module),
4369
+ factNameOf: (module, declaration) => factNames.nameOf(module, declaration),
4370
+ factModuleOf,
4371
+ exportedClassOf(module, name) {
4372
+ const exported = factNames
4373
+ .modulesNamed(module)
4374
+ .flatMap((moduleSymbol) => typeChecker().getExportsOfModule(moduleSymbol))
4375
+ .find((one) => one.getName() === name);
4376
+ if (exported === undefined)
4377
+ return undefined;
4378
+ const target = exported.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(exported) : exported;
4379
+ const node = target.declarations?.find(ts.isClassLike);
4380
+ if (node === undefined)
4381
+ return undefined;
4382
+ return { file: node.getSourceFile().fileName, node };
4383
+ },
1561
4384
  literalsOf(node) {
1562
4385
  const found = typeChecker().getTypeAtLocation(node);
1563
4386
  const type = found.isTypeParameter() ? typeChecker().getBaseConstraintOfType(found) : found;
@@ -1684,6 +4507,16 @@ root, packageOf, isEntry, dependenciesOf) {
1684
4507
  }));
1685
4508
  }));
1686
4509
  },
4510
+ expectsCallableReturn(node) {
4511
+ const checker = typeChecker();
4512
+ const type = checker.getContextualType(node);
4513
+ if (type === undefined)
4514
+ return false;
4515
+ return (type.isUnion() ? type.types : [type]).some((member) => member.getCallSignatures().some((signature) => {
4516
+ const returned = checker.getReturnTypeOfSignature(signature);
4517
+ return (returned.isUnion() ? returned.types : [returned]).some((part) => part.getCallSignatures().length > 0);
4518
+ }));
4519
+ },
1687
4520
  canBeUndefined(node) {
1688
4521
  const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
1689
4522
  // An unconstrained type parameter can be anything, undefined included.
@@ -1696,6 +4529,14 @@ root, packageOf, isEntry, dependenciesOf) {
1696
4529
  const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Null;
1697
4530
  return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0);
1698
4531
  },
4532
+ canBeFalse(node) {
4533
+ const checker = typeChecker();
4534
+ const type = widened(checker, checker.getTypeAtLocation(node));
4535
+ if (type === undefined)
4536
+ return true;
4537
+ const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown;
4538
+ return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0 || member === checker.getFalseType());
4539
+ },
1699
4540
  parameterIsNever(call, argumentIndex) {
1700
4541
  const declaration = typeChecker().getResolvedSignature(call)?.declaration;
1701
4542
  if (declaration === undefined || !("parameters" in declaration))
@@ -1746,17 +4587,71 @@ root, packageOf, isEntry, dependenciesOf) {
1746
4587
  const type = checker.getContextualType(node);
1747
4588
  return type === undefined ? [] : guaranteesOfType(checker, type);
1748
4589
  },
4590
+ markerValuesOf(node, property) {
4591
+ return markerValuesOfType(typeChecker(), typeChecker().getTypeAtLocation(node), property);
4592
+ },
1749
4593
  guaranteeValuesOf(target, name, contextual = false) {
1750
4594
  const checker = typeChecker();
1751
4595
  if ("kind" in target) {
1752
4596
  const type = contextual && ts.isExpression(target)
1753
4597
  ? checker.getContextualType(target)
1754
4598
  : checker.getTypeAtLocation(target);
1755
- return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
4599
+ return type === undefined
4600
+ ? undefined
4601
+ : markerValuesOfType(checker, type, `${GUARANTEE_PREFIX}${name}`);
1756
4602
  }
1757
4603
  const declaration = declarations.get(target.id);
1758
4604
  const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
1759
- return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
4605
+ return type === undefined
4606
+ ? undefined
4607
+ : markerValuesOfType(checker, type, `${GUARANTEE_PREFIX}${name}`);
4608
+ },
4609
+ heldAliasesOf(node, contextual = false) {
4610
+ const checker = typeChecker();
4611
+ const type = contextual ? checker.getContextualType(node) : checker.getTypeAtLocation(node);
4612
+ if (type === undefined)
4613
+ return [];
4614
+ const found = new Map();
4615
+ const seen = new Set();
4616
+ const enter = (given, depth, top) => {
4617
+ const base = widened(checker, given);
4618
+ if (base === undefined || depth > 3 || seen.has(base))
4619
+ return;
4620
+ seen.add(base);
4621
+ const alias = base.aliasSymbol;
4622
+ if (!top &&
4623
+ alias?.declarations?.some(ts.isTypeAliasDeclaration) === true &&
4624
+ (base.aliasTypeArguments?.length ?? 0) === 0) {
4625
+ found.set(`${alias.getName()}#${String(alias.declarations[0]?.pos ?? 0)}`, alias);
4626
+ return;
4627
+ }
4628
+ if (base.isUnion()) {
4629
+ for (const member of base.types)
4630
+ enter(member, depth, top);
4631
+ }
4632
+ else if (base.flags & ts.TypeFlags.Object) {
4633
+ if (isTypeReference(base)) {
4634
+ for (const argument of checker.getTypeArguments(base)) {
4635
+ enter(argument, depth + 1, false);
4636
+ }
4637
+ }
4638
+ else if (isAnonymousObject(base)) {
4639
+ for (const property of checker.getPropertiesOfType(base)) {
4640
+ const declaration = property.valueDeclaration ?? property.declarations?.[0];
4641
+ if (declaration !== undefined) {
4642
+ enter(checker.getTypeOfSymbolAtLocation(property, declaration), depth + 1, false);
4643
+ }
4644
+ }
4645
+ }
4646
+ }
4647
+ };
4648
+ enter(type, 0, true);
4649
+ return [...found.values()]
4650
+ .sort((a, b) => (a.getName() < b.getName() ? -1 : a.getName() > b.getName() ? 1 : 0))
4651
+ .flatMap((symbol) => {
4652
+ const ref = refOfSymbol(symbol);
4653
+ return ref === undefined ? [] : [ref];
4654
+ });
1760
4655
  },
1761
4656
  contextualAliasOf(node) {
1762
4657
  const checker = typeChecker();
@@ -1771,8 +4666,16 @@ root, packageOf, isEntry, dependenciesOf) {
1771
4666
  const whole = aliasOf(type);
1772
4667
  if (whole !== undefined)
1773
4668
  return refOfSymbol(whole);
1774
- const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0);
1775
- const aliases = new Set(members.map(aliasOf));
4669
+ // `return "x"` in an async function expects `OrderId | PromiseLike<OrderId>`.
4670
+ const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0 &&
4671
+ !(member.getSymbol()?.getName() === "PromiseLike" &&
4672
+ member.symbol.declarations?.some((declaration) => program.isSourceFileDefaultLibrary(declaration.getSourceFile())) === true));
4673
+ // `show("bad")` with a parameter `OrderId | number`: a member without an alias that the value
4674
+ // does not fit (`number`) is not what it becomes.
4675
+ const own = checker.getTypeAtLocation(node);
4676
+ const aliases = new Set(members
4677
+ .filter((member) => aliasOf(member) !== undefined || checker.isTypeAssignableTo(own, member))
4678
+ .map(aliasOf));
1776
4679
  const [only] = aliases;
1777
4680
  return aliases.size === 1 && only !== undefined ? refOfSymbol(only) : undefined;
1778
4681
  },
@@ -1808,6 +4711,32 @@ root, packageOf, isEntry, dependenciesOf) {
1808
4711
  }
1809
4712
  return renamedNames;
1810
4713
  },
4714
+ statedDeclarationsIn(sourceFile) {
4715
+ anyMarker ??= program.getSourceFiles().some(declaresAnyMarker);
4716
+ return anyMarker ? statedDeclarationsOf(typeChecker(), sourceFile) : [];
4717
+ },
4718
+ statedReferencesIn(sourceFile, proves) {
4719
+ anyMarker ??= program.getSourceFiles().some(declaresAnyMarker);
4720
+ // A tag needs no marker: its scan reads only the files whose text writes it.
4721
+ if (!anyMarker && (proves.tags ?? []).length === 0)
4722
+ return [];
4723
+ ledgerScan ??= createLedgerScan(program, typeChecker, (file) => own.has(toTypeScriptPath(file)), refOfSymbol);
4724
+ return ledgerScan.referencesIn(sourceFile, proves);
4725
+ },
4726
+ typedFlowsIn(sourceFile, proves, budget = FLOW_BUDGET) {
4727
+ anyMarker ??= program.getSourceFiles().some(declaresAnyMarker);
4728
+ if (!anyMarker)
4729
+ return [];
4730
+ ledgerScan ??= createLedgerScan(program, typeChecker, (file) => own.has(toTypeScriptPath(file)), refOfSymbol);
4731
+ return ledgerScan.flowsIn(sourceFile, proves, budget);
4732
+ },
4733
+ holdsOnlyPrimitives(node) {
4734
+ return onlyPrimitives(typeChecker(), typeChecker().getTypeAtLocation(node), 0);
4735
+ },
4736
+ valueOriginOf(node) {
4737
+ const symbol = typeChecker().getTypeAtLocation(node).getSymbol();
4738
+ return symbol === undefined ? undefined : refOfSymbol(symbol);
4739
+ },
1811
4740
  declaresTrait(name) {
1812
4741
  const known = declaredTraits.get(name);
1813
4742
  if (known !== undefined)
@@ -1879,6 +4808,43 @@ root, packageOf, isEntry, dependenciesOf) {
1879
4808
  return false;
1880
4809
  return typeChecker().isTypeAssignableTo(rest, typeChecker().getNonNullableType(typeChecker().getTypeAtLocation(to)));
1881
4810
  },
4811
+ valueAssignableTo(output, orUndefined, target) {
4812
+ const checker = typeChecker();
4813
+ const to = checker.getTypeAtLocation(target);
4814
+ if (orUndefined && !checker.isTypeAssignableTo(checker.getUndefinedType(), to))
4815
+ return false;
4816
+ if (output === "array") {
4817
+ const members = to.isUnion() ? to.types : [to];
4818
+ const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.NonPrimitive;
4819
+ return members.some((one) => (one.flags & open) !== 0 || checker.isArrayLikeType(one));
4820
+ }
4821
+ // An output that still holds a type parameter (`T[]`, `Promise<T>`) says nothing certain
4822
+ // about the value until its arguments are known.
4823
+ if (typeof output !== "string" && holdsTypeParameter(checker, output))
4824
+ return undefined;
4825
+ const declared = typeof output === "string" ? undefined : checker.getTypeFromTypeNode(output);
4826
+ const from = declared !== undefined
4827
+ ? (checker.getAwaitedType(declared) ?? declared)
4828
+ : output === "string"
4829
+ ? checker.getStringType()
4830
+ : output === "number"
4831
+ ? checker.getNumberType()
4832
+ : checker.getBooleanType();
4833
+ if (from.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
4834
+ return undefined;
4835
+ if (checker.isTypeAssignableTo(from, to))
4836
+ return true;
4837
+ // A brand (`string & { __brand: "Uuid" }`) adds no runtime value: the developer states that
4838
+ // the value was checked, so the type it brands counts.
4839
+ return (to.isUnion() ? to.types : [to]).some((member) => {
4840
+ if (!member.isIntersection())
4841
+ return false;
4842
+ const plain = member.types.filter((one) => (one.flags & ts.TypeFlags.Object) === 0);
4843
+ return (plain.length > 0 &&
4844
+ plain.length < member.types.length &&
4845
+ plain.every((one) => checker.isTypeAssignableTo(from, one)));
4846
+ });
4847
+ },
1882
4848
  parameterIsReadonly(call, argumentIndex) {
1883
4849
  // After a spread argument the indexes no longer line up with the parameters.
1884
4850
  if (call.arguments.slice(0, argumentIndex + 1).some(ts.isSpreadElement))
@@ -1908,6 +4874,21 @@ root, packageOf, isEntry, dependenciesOf) {
1908
4874
  awaitedTagsOf(node, property) {
1909
4875
  return awaitedTags(typeChecker(), typeChecker().getTypeAtLocation(node), property);
1910
4876
  },
4877
+ propIsDeeplyReadonly(attribute) {
4878
+ const checker = typeChecker();
4879
+ // The component's props type, as the attributes are checked against it.
4880
+ const props = checker.getContextualType(attribute.parent);
4881
+ const symbol = props === undefined
4882
+ ? undefined
4883
+ : checker.getPropertyOfType(props, attribute.name.getText());
4884
+ const declarations = symbol?.declarations ?? [];
4885
+ if (symbol === undefined ||
4886
+ declarations.length === 0 ||
4887
+ !declarations.every((one) => own.has(one.getSourceFile().fileName))) {
4888
+ return false;
4889
+ }
4890
+ return isDeeplyReadonly(checker, checker.getTypeOfSymbol(symbol), 0);
4891
+ },
1911
4892
  isReadonlyPath(node) {
1912
4893
  return isReadonlyChain(typeChecker(), node);
1913
4894
  },
@@ -1940,6 +4921,153 @@ root, packageOf, isEntry, dependenciesOf) {
1940
4921
  const members = type.isUnion() ? type.types : [type];
1941
4922
  return members.every((member) => (member.flags & PRIMITIVE_FLAGS) !== 0);
1942
4923
  },
4924
+ isNumber(node) {
4925
+ const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
4926
+ if (type === undefined)
4927
+ return false;
4928
+ return (type.isUnion() ? type.types : [type]).every(isNumberType);
4929
+ },
4930
+ platformTypeOf(node) {
4931
+ return platformNameOf(typeChecker().getTypeAtLocation(node));
4932
+ },
4933
+ arrayElementsOf(node) {
4934
+ return arrayElements(typeChecker().getTypeAtLocation(node));
4935
+ },
4936
+ arrayCanBeEmpty(node) {
4937
+ const checker = typeChecker();
4938
+ const members = definedMembers(checker, checker.getTypeAtLocation(node));
4939
+ if (members === undefined)
4940
+ return undefined;
4941
+ let empty = false;
4942
+ for (const member of members) {
4943
+ if (checker.isTupleType(member) && isTypeReference(member)) {
4944
+ const target = member.target;
4945
+ const required = "minLength" in target && typeof target.minLength === "number" ? target.minLength : 0;
4946
+ if (required === 0)
4947
+ empty = true;
4948
+ continue;
4949
+ }
4950
+ const name = platformNameOfType(member);
4951
+ if (name !== "Array" && name !== "ReadonlyArray")
4952
+ return undefined;
4953
+ empty = true;
4954
+ }
4955
+ return empty;
4956
+ },
4957
+ readIsPlain(node) {
4958
+ const checker = typeChecker();
4959
+ if (ts.isBindingElement(node)) {
4960
+ const pattern = node.parent;
4961
+ const source = checker.getTypeAtLocation(pattern);
4962
+ if (ts.isArrayBindingPattern(pattern))
4963
+ return arrayElements(source) !== undefined;
4964
+ if (node.dotDotDotToken !== undefined)
4965
+ return false;
4966
+ const key = node.propertyName ?? node.name;
4967
+ if (!ts.isIdentifier(key) && !ts.isStringLiteral(key))
4968
+ return false;
4969
+ const members = definedMembers(checker, source);
4970
+ const [only] = members ?? [];
4971
+ const property = members?.length === 1 && only !== undefined
4972
+ ? checker.getPropertyOfType(only, key.text)
4973
+ : undefined;
4974
+ return property !== undefined && plainProperty(property, source);
4975
+ }
4976
+ if (ts.isPropertyAccessExpression(node)) {
4977
+ const property = checker.getSymbolAtLocation(node.name);
4978
+ return (property !== undefined &&
4979
+ plainProperty(property, checker.getTypeAtLocation(node.expression)));
4980
+ }
4981
+ const receiver = checker.getTypeAtLocation(node.expression);
4982
+ const members = definedMembers(checker, receiver);
4983
+ const [only] = members ?? [];
4984
+ if (members?.length !== 1 || only === undefined)
4985
+ return false;
4986
+ const argument = node.argumentExpression;
4987
+ if (ts.isNumericLiteral(argument) && checker.isTupleType(only) && isTypeReference(only)) {
4988
+ const target = only.target;
4989
+ const fixed = "minLength" in target && typeof target.minLength === "number" ? target.minLength : 0;
4990
+ return Number(argument.text) < fixed;
4991
+ }
4992
+ if (ts.isStringLiteralLike(argument)) {
4993
+ const property = checker.getPropertyOfType(only, argument.text);
4994
+ if (property !== undefined)
4995
+ return plainProperty(property, receiver);
4996
+ }
4997
+ // A key of an index signature: the read itself runs nothing, but it may find nothing, so the
4998
+ // value must be a primitive that is not read further.
4999
+ if (checker.getIndexInfosOfType(only).length === 0)
5000
+ return false;
5001
+ const value = checker.getTypeAtLocation(node);
5002
+ const parts = value.isUnion() ? value.types : [value];
5003
+ if (!parts.every((part) => (part.flags & PRIMITIVE_FLAGS) !== 0))
5004
+ return false;
5005
+ let outer = node;
5006
+ while (ts.isParenthesizedExpression(outer.parent) ||
5007
+ ts.isNonNullExpression(outer.parent) ||
5008
+ ts.isAsExpression(outer.parent) ||
5009
+ ts.isSatisfiesExpression(outer.parent)) {
5010
+ outer = outer.parent;
5011
+ }
5012
+ const parent = outer.parent;
5013
+ return !((ts.isPropertyAccessExpression(parent) ||
5014
+ ts.isElementAccessExpression(parent) ||
5015
+ ts.isCallExpression(parent) ||
5016
+ ts.isTaggedTemplateExpression(parent)) &&
5017
+ (ts.isTaggedTemplateExpression(parent) ? parent.tag : parent.expression) === outer);
5018
+ },
5019
+ readMayRunAccessor(node) {
5020
+ const property = typeChecker().getSymbolAtLocation(node.name);
5021
+ return (property?.declarations ?? []).some((one) => own.has(toTypeScriptPath(one.getSourceFile().fileName)) &&
5022
+ (ts.isGetAccessorDeclaration(one) || ts.isSetAccessorDeclaration(one)) &&
5023
+ one.body !== undefined);
5024
+ },
5025
+ isPlatformName(node) {
5026
+ const found = typeChecker().getSymbolAtLocation(node);
5027
+ if (found === undefined)
5028
+ return false;
5029
+ const symbol = found.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(found) : found;
5030
+ const declarations = symbol.declarations ?? [];
5031
+ return (declarations.length > 0 && declarations.every((one) => isPlatformFile(one.getSourceFile())));
5032
+ },
5033
+ globalPackagesOf(node) {
5034
+ const found = typeChecker().getSymbolAtLocation(node);
5035
+ if (found === undefined || found.flags & ts.SymbolFlags.Alias)
5036
+ return [];
5037
+ const declarations = found.declarations ?? [];
5038
+ if (!declarations.every(isGlobalDeclaration))
5039
+ return [];
5040
+ const packages = new Set();
5041
+ for (const one of declarations) {
5042
+ const file = one.getSourceFile();
5043
+ if (isPlatformFile(file))
5044
+ continue;
5045
+ const name = packageOf(toTypeScriptPath(file.fileName));
5046
+ if (name !== undefined)
5047
+ packages.add(name);
5048
+ }
5049
+ return [...packages].sort();
5050
+ },
5051
+ isPlainClass(node) {
5052
+ const checker = typeChecker();
5053
+ const type = checker.getTypeAtLocation(node);
5054
+ if (platformNameOf(type)?.endsWith("Constructor") === true)
5055
+ return true;
5056
+ const found = checker.getSymbolAtLocation(node);
5057
+ if (found === undefined)
5058
+ return false;
5059
+ const symbol = found.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(found) : found;
5060
+ const declarations = symbol.declarations ?? [];
5061
+ const ownFile = (one) => own.has(toTypeScriptPath(one.getSourceFile().fileName));
5062
+ // A static `Symbol.hasInstance` of the class or a class it extends runs code.
5063
+ const runsCode = checker
5064
+ .getPropertiesOfType(type)
5065
+ .some((property) => property.getName().includes("hasInstance") &&
5066
+ (property.declarations ?? []).some(ownFile));
5067
+ return (!runsCode &&
5068
+ declarations.length > 0 &&
5069
+ declarations.every((one) => ts.isClassDeclaration(one) && ownFile(one)));
5070
+ },
1943
5071
  isLibraryType(node) {
1944
5072
  const inLibrary = (declaration) => {
1945
5073
  const file = declaration.getSourceFile();
@@ -2011,6 +5139,59 @@ root, packageOf, isEntry, dependenciesOf) {
2011
5139
  const to = body.getStart(sourceFile);
2012
5140
  return starts.some((start) => start >= from && start < to);
2013
5141
  },
5142
+ genericBaseOf(node, pkg, names) {
5143
+ const checker = typeChecker();
5144
+ const inPackage = (symbol) => (symbol.declarations ?? []).some((declaration) => packageOf(toTypeScriptPath(declaration.getSourceFile().fileName)) === pkg);
5145
+ return genericBaseOfType(checker, checker.getTypeAtLocation(node), inPackage, names);
5146
+ },
5147
+ isOrExtends(node, classes) {
5148
+ return isOrExtendsType(typeChecker(), typeChecker().getTypeAtLocation(node), classes);
5149
+ },
5150
+ instanceClassesOf(node, depth) {
5151
+ return instanceClassesOfType(typeChecker(), typeChecker().getTypeAtLocation(node), depth);
5152
+ },
5153
+ propertyTypesOf(node) {
5154
+ const checker = typeChecker();
5155
+ const type = widened(checker, checker.getTypeAtLocation(node));
5156
+ if (type === undefined || !(type.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection))) {
5157
+ return undefined;
5158
+ }
5159
+ return checker
5160
+ .getPropertiesOfType(type)
5161
+ .map((property) => {
5162
+ const own = checker.getTypeOfSymbol(property);
5163
+ const members = own.isUnion() ? own.types : [own];
5164
+ return {
5165
+ name: property.getName(),
5166
+ text: checker.typeToString(own).replace(/\s+/g, " ").trim(),
5167
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
5168
+ open: (own.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0,
5169
+ platform: platformNameOf(own) ?? null,
5170
+ nullish: members.some((one) => (one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0),
5171
+ };
5172
+ })
5173
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
5174
+ },
5175
+ parameterTakesUnknown(call, argumentIndex) {
5176
+ return takesUnknown(typeChecker(), call, argumentIndex);
5177
+ },
5178
+ typeShapeOf(node, from) {
5179
+ const checker = typeChecker();
5180
+ const type = from === "type"
5181
+ ? ts.isTypeNode(node)
5182
+ ? checker.getTypeFromTypeNode(node)
5183
+ : checker.getTypeAtLocation(node)
5184
+ : ts.isExpression(node)
5185
+ ? checker.getContextualType(node)
5186
+ : undefined;
5187
+ return type === undefined ? undefined : typeShape(isPlatformFile, checker, type, []);
5188
+ },
5189
+ metadataTypeOf(node) {
5190
+ return decoratorMetadata(program.getCompilerOptions(), {
5191
+ checker: typeChecker(),
5192
+ refOf: (symbol) => refOfSymbol(symbol),
5193
+ }, node);
5194
+ },
2014
5195
  narrowedBy(reference, test) {
2015
5196
  return narrowedMembers(program, typeChecker(), reference, test);
2016
5197
  },
@@ -2023,14 +5204,45 @@ root, packageOf, isEntry, dependenciesOf) {
2023
5204
  isErrorType(node) {
2024
5205
  return isErrorTypeOf(typeChecker().getTypeAtLocation(node));
2025
5206
  },
5207
+ hasNoType(node) {
5208
+ return (typeChecker().getTypeAtLocation(node).flags & ts.TypeFlags.Any) !== 0;
5209
+ },
5210
+ isOpenType(node) {
5211
+ const checker = typeChecker();
5212
+ const type = ts.isTypeNode(node)
5213
+ ? checker.getTypeFromTypeNode(node)
5214
+ : checker.getTypeAtLocation(node);
5215
+ return (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
5216
+ },
5217
+ builtinTypeOf(node, read) {
5218
+ const checker = typeChecker();
5219
+ const type = ts.isTypeNode(node)
5220
+ ? checker.getTypeFromTypeNode(node)
5221
+ : checker.getTypeAtLocation(node);
5222
+ return builtinOf(read === "awaited" ? (checker.getAwaitedType(type) ?? type) : type);
5223
+ },
2026
5224
  isPromiseLike(node) {
2027
5225
  return isPromiseType(typeChecker(), typeChecker().getTypeAtLocation(node));
2028
5226
  },
5227
+ methodReturnsPromiseLike(node, name) {
5228
+ const checker = typeChecker();
5229
+ const property = checker.getTypeAtLocation(node).getProperty(name);
5230
+ if (property === undefined)
5231
+ return false;
5232
+ const signatures = checker.getTypeOfSymbol(property).getCallSignatures();
5233
+ return (signatures.length > 0 &&
5234
+ signatures.every((signature) => isPromiseType(checker, checker.getReturnTypeOfSignature(signature))));
5235
+ },
2029
5236
  returnsPromiseLike(fn) {
2030
5237
  const signature = typeChecker().getSignatureFromDeclaration(fn);
2031
5238
  return (signature !== undefined &&
2032
5239
  isPromiseType(typeChecker(), typeChecker().getReturnTypeOfSignature(signature)));
2033
5240
  },
5241
+ mayReturnPromise(fn) {
5242
+ const signature = typeChecker().getSignatureFromDeclaration(fn);
5243
+ return (signature === undefined ||
5244
+ mayBePromiseType(typeChecker(), typeChecker().getReturnTypeOfSignature(signature)));
5245
+ },
2034
5246
  hasDefinedProperty(node, name) {
2035
5247
  const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
2036
5248
  if (type === undefined)
@@ -2132,7 +5344,7 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2132
5344
  /** What the last `open` found: the projects, their own files, and every own file of all of them. */
2133
5345
  let last;
2134
5346
  /** The program of one project, built now, as a unit; recorded for the next run when it can be. */
2135
- const buildUnit = ({ tsconfigPath, parsed, own, shared }, claimed, overlays, trustCache) => {
5347
+ const buildUnit = ({ tsconfigPath, parsed, own, shared, unreadTestConfigs }, claimed, overlays, trustCache) => {
2136
5348
  const sources = caches.get(tsconfigPath) ?? new Map();
2137
5349
  caches.set(tsconfigPath, sources);
2138
5350
  const oldProgram = previous.get(tsconfigPath);
@@ -2168,6 +5380,24 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2168
5380
  let fingerprints;
2169
5381
  /** The text hashes of read files asked for, kept in the record so a replayed program answers them. */
2170
5382
  const readPrints = {};
5383
+ /** What the config's facts keys resolve to, by digest, kept in the record the same way. */
5384
+ const factChecks = {};
5385
+ let imports;
5386
+ /** The package modules the own files import (`importedModules`), sorted. */
5387
+ const importsOf = () => {
5388
+ if (imports !== undefined)
5389
+ return imports;
5390
+ const all = new Set();
5391
+ for (const file of files) {
5392
+ const sourceFile = program.getSourceFile(file);
5393
+ if (sourceFile === undefined)
5394
+ continue;
5395
+ for (const name of importedModules(sourceFile, parsed.options))
5396
+ all.add(name);
5397
+ }
5398
+ imports = [...all].sort();
5399
+ return imports;
5400
+ };
2171
5401
  const fingerprintsOf = () => {
2172
5402
  if (fingerprints !== undefined)
2173
5403
  return fingerprints;
@@ -2180,6 +5410,8 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2180
5410
  files,
2181
5411
  fingerprints: Object.fromEntries(files.map((file) => [file, known.get(file) ?? ""])),
2182
5412
  reads: readPrints,
5413
+ imports: importsOf(),
5414
+ facts: factChecks,
2183
5415
  });
2184
5416
  cache.changed = true;
2185
5417
  }
@@ -2187,7 +5419,7 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2187
5419
  };
2188
5420
  /** What each file's rules were handed, by file: read ids, with the file each one is in. */
2189
5421
  const reads = new Map();
2190
- const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf);
5422
+ const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf, config.platform);
2191
5423
  const idFileName = idFileNames(cwd);
2192
5424
  const fileId = (fileName) => `${idFileName(fileName)}#`;
2193
5425
  /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
@@ -2252,7 +5484,14 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2252
5484
  syntaxError: (file) => firstSyntaxError(program, file),
2253
5485
  unresolvedImports: (file) => unresolvedImportsOf(program, file),
2254
5486
  strictNullChecks: checksNulls(parsed.options),
5487
+ unreadTestConfigs,
2255
5488
  typesResolve: typesResolver(tsconfigPath, parsed.options),
5489
+ factKeys: (facts) => {
5490
+ const checks = checkFactKeys(facts, types);
5491
+ factChecks[factKeysDigest(facts)] = JSON.stringify(checks);
5492
+ return checks;
5493
+ },
5494
+ importsModule: (module) => importsModuleIn(importsOf(), module),
2256
5495
  bind: () => {
2257
5496
  program.getTypeChecker();
2258
5497
  },
@@ -2291,7 +5530,21 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2291
5530
  syntaxError: (file) => real().syntaxError(file),
2292
5531
  unresolvedImports: (file) => real().unresolvedImports(file),
2293
5532
  strictNullChecks: checksNulls(project.parsed.options),
5533
+ unreadTestConfigs: project.unreadTestConfigs,
2294
5534
  typesResolve: typesResolver(project.tsconfigPath, project.parsed.options),
5535
+ factKeys: (facts) => {
5536
+ const digest = factKeysDigest(facts);
5537
+ const kept = record.facts[digest];
5538
+ const known = kept === undefined ? undefined : readFactKeyChecks(kept);
5539
+ if (known !== undefined)
5540
+ return known;
5541
+ const checks = real().factKeys(facts);
5542
+ record.facts[digest] = JSON.stringify(checks);
5543
+ if (cache !== undefined)
5544
+ cache.changed = true;
5545
+ return checks;
5546
+ },
5547
+ importsModule: (module) => importsModuleIn(record.imports, module),
2295
5548
  bind: () => {
2296
5549
  real().bind();
2297
5550
  },
@@ -2331,10 +5584,14 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2331
5584
  const collected = collectConfigs(roots);
2332
5585
  const shared = collected.length > 1 ? listedTwice(collected) : new Set();
2333
5586
  const projects = collected.map(({ path: tsconfigPath, parsed }) => {
2334
- const own = ownFileNames(parsed, config, cwd, claimed);
5587
+ // The test runner's own test files join the default `exclude`, unless the config replaced it.
5588
+ const tests = config.replacesDefaultExclude
5589
+ ? { matches: () => false, unread: [] }
5590
+ : testRunnerFiles([path.dirname(tsconfigPath), config.configDir]);
5591
+ const own = ownFileNames(parsed, config, cwd, claimed, tests.matches);
2335
5592
  for (const file of own)
2336
5593
  claimed.add(file);
2337
- return { tsconfigPath, parsed, own, shared };
5594
+ return { tsconfigPath, parsed, own, shared, unreadTestConfigs: tests.unread };
2338
5595
  });
2339
5596
  if (claimed.size === 0)
2340
5597
  throw new NothingToCheckError(named);
@@ -2350,15 +5607,6 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
2350
5607
  reopen: (overlays) => last === undefined ? open(overlays) : build(last.projects, last.claimed, overlays, true),
2351
5608
  };
2352
5609
  }
2353
- // ---- package sources ----------------------------------------
2354
- function isSymbol(value) {
2355
- return typeof value === "object" && value !== null && "flags" in value && "escapedName" in value;
2356
- }
2357
- /**
2358
- * The module symbol of a file: the checker answers for an ES module; a CommonJS file (`exports.x
2359
- * = …`) has one only on the file itself, which TypeScript keeps without a public type, so it is
2360
- * read through reflection and checked at run time.
2361
- */
2362
5610
  /** The type alias a module exports under `name`, aliases resolved; undefined when it exports none. */
2363
5611
  function exportedAlias(checker, sourceFile, name) {
2364
5612
  const module = moduleSymbolOf(checker, sourceFile);
@@ -2405,6 +5653,28 @@ function relativeSpecifier(program, importer, file) {
2405
5653
  }
2406
5654
  }
2407
5655
  }
5656
+ // ---- facts keys ---------------------------------------------------------------------------------
5657
+ /**
5658
+ * The names a `facts` key is written in, resolved by the type checker (0041): a module as the
5659
+ * project would import it, then a dotted path through its exports and their members
5660
+ * (`"typeorm": { "Repository.find": … }`). A key names the declarations of the symbol it resolves
5661
+ * to, so it does not depend on how the module's declarations are written: two module names that
5662
+ * resolve to one symbol (an alias module that re-exports another) name the same declarations.
5663
+ */
5664
+ /** How deep `names` lists a module's paths (`Repository.find` is two). */
5665
+ const LISTED_DEPTH = 2;
5666
+ /** At most this many paths are listed per module. */
5667
+ const MAX_LISTED = 50_000;
5668
+ /** How many `export =` a module is followed through. */
5669
+ const MAX_EXPORT_EQUALS = 4;
5670
+ function isSymbol(value) {
5671
+ return typeof value === "object" && value !== null && "flags" in value && "escapedName" in value;
5672
+ }
5673
+ /**
5674
+ * The module symbol of a file: the checker answers for an ES module; a CommonJS file (`exports.x
5675
+ * = …`) has one only on the file itself, which TypeScript keeps without a public type, so it is
5676
+ * read through reflection and checked at run time.
5677
+ */
2408
5678
  function moduleSymbolOf(checker, sourceFile) {
2409
5679
  const found = checker.getSymbolAtLocation(sourceFile);
2410
5680
  if (found !== undefined)
@@ -2412,105 +5682,476 @@ function moduleSymbolOf(checker, sourceFile) {
2412
5682
  const own = Reflect.get(sourceFile, "symbol");
2413
5683
  return isSymbol(own) ? own : undefined;
2414
5684
  }
2415
- const PACKAGE_JAVASCRIPT = /\.(?:js|mjs|cjs)$/;
2416
- const PACKAGE_OPTIONS = {
2417
- allowJs: true,
2418
- checkJs: false,
2419
- noEmit: true,
2420
- target: ts.ScriptTarget.ES2022,
2421
- module: ts.ModuleKind.Preserve,
2422
- moduleResolution: ts.ModuleResolutionKind.Bundler,
2423
- lib: ["lib.es2022.d.ts"],
2424
- types: [],
2425
- skipLibCheck: true,
2426
- };
2427
- function isRelativeSpecifier(specifier) {
2428
- return specifier.startsWith("./") || specifier.startsWith("../");
5685
+ function createFactNames(checker, program,
5686
+ /** The package of a file (`TypeQueries.packageOf`). */
5687
+ packageOf,
5688
+ /** A file in the project's folder that module names are resolved from (it need not exist). */
5689
+ resolveFrom,
5690
+ /** The project's own files. */
5691
+ own) {
5692
+ let ambient;
5693
+ let imported;
5694
+ const modules = new Map();
5695
+ const children = new Map();
5696
+ const targets = new Map();
5697
+ const listed = new Map();
5698
+ const resolved = (symbol) => symbol.flags & ts.SymbolFlags.Alias ? checker().getAliasedSymbol(symbol) : symbol;
5699
+ /** Whether a value can be called: a function, a class, or a value whose type has a signature. */
5700
+ const isCallable = (symbol) => (symbol.flags & (ts.SymbolFlags.Function | ts.SymbolFlags.Class)) !== 0 ||
5701
+ checker().getTypeOfSymbol(symbol).getCallSignatures().length > 0;
5702
+ /** The modules `declare module "x"` declares, by the name it is written with. */
5703
+ const ambientModules = () => {
5704
+ if (ambient !== undefined)
5705
+ return ambient;
5706
+ ambient = new Map();
5707
+ for (const symbol of checker().getAmbientModules()) {
5708
+ for (const declaration of symbol.declarations ?? []) {
5709
+ if (ts.isModuleDeclaration(declaration) &&
5710
+ ts.isStringLiteral(declaration.name) &&
5711
+ !ambient.has(declaration.name.text)) {
5712
+ ambient.set(declaration.name.text, symbol);
5713
+ }
5714
+ }
5715
+ }
5716
+ return ambient;
5717
+ };
5718
+ /**
5719
+ * The module symbols the own files' imports and re-exports reach, by the name they write: the
5720
+ * checker resolves each in its file's own mode, as the project's imports resolve.
5721
+ */
5722
+ const importedModules = () => {
5723
+ if (imported !== undefined)
5724
+ return imported;
5725
+ imported = new Map();
5726
+ for (const file of program.getSourceFiles()) {
5727
+ if (!own.has(file.fileName))
5728
+ continue;
5729
+ for (const specifier of specifiersOf(file)) {
5730
+ const found = checker().getSymbolAtLocation(specifier);
5731
+ if (found === undefined)
5732
+ continue;
5733
+ const list = imported.get(specifier.text) ?? [];
5734
+ if (!list.includes(found))
5735
+ list.push(found);
5736
+ imported.set(specifier.text, list);
5737
+ }
5738
+ }
5739
+ return imported;
5740
+ };
5741
+ /** The module symbol of the file `module` resolves to from the project's folder in `mode`. */
5742
+ const resolvedIn = (module, mode) => {
5743
+ const file = ts.resolveModuleName(module, resolveFrom, program.getCompilerOptions(), ts.sys, undefined, undefined, mode).resolvedModule?.resolvedFileName;
5744
+ const sourceFile = file === undefined ? undefined : program.getSourceFile(file);
5745
+ return sourceFile === undefined ? undefined : moduleSymbolOf(checker(), sourceFile);
5746
+ };
5747
+ const modulesNamed = (module) => {
5748
+ const known = modules.get(module);
5749
+ if (known !== undefined)
5750
+ return known;
5751
+ // As TypeScript resolves an import: a module `declare module` declares, else the files the
5752
+ // project's imports of it reach, and those it resolves to in either mode.
5753
+ const declared = ambientModules().get(module);
5754
+ const found = declared !== undefined
5755
+ ? [declared]
5756
+ : [
5757
+ ...new Set([
5758
+ ...(importedModules().get(module) ?? []),
5759
+ resolvedIn(module, ts.ModuleKind.ESNext),
5760
+ resolvedIn(module, ts.ModuleKind.CommonJS),
5761
+ ].flatMap((one) => (one === undefined ? [] : [resolved(one)]))),
5762
+ ];
5763
+ modules.set(module, found);
5764
+ return found;
5765
+ };
5766
+ /**
5767
+ * The names one step below a symbol: a module's exports (with what its `export =` gives), a
5768
+ * class's or interface's members, and the properties of a value's type (`const path:
5769
+ * PlatformPath` gives `join`).
5770
+ */
5771
+ const childrenOf = (symbol, depth = 0) => {
5772
+ const target = resolved(symbol);
5773
+ const known = children.get(target);
5774
+ if (known !== undefined)
5775
+ return known;
5776
+ const found = new Map();
5777
+ const add = (name, one) => {
5778
+ if (one.escapedName === ts.InternalSymbolName.ExportEquals)
5779
+ return;
5780
+ const list = found.get(name) ?? [];
5781
+ if (!list.includes(one))
5782
+ list.push(one);
5783
+ found.set(name, list);
5784
+ };
5785
+ const flags = target.flags;
5786
+ if (flags & ts.SymbolFlags.Module) {
5787
+ for (const one of checker().getExportsOfModule(target))
5788
+ add(one.getName(), one);
5789
+ const whole = target.exports?.get(ts.InternalSymbolName.ExportEquals);
5790
+ if (whole !== undefined && depth < MAX_EXPORT_EQUALS) {
5791
+ for (const [name, list] of childrenOf(whole, depth + 1)) {
5792
+ for (const one of list)
5793
+ add(name, one);
5794
+ }
5795
+ // A module whose value is itself callable (`export =` of a function or a class) is
5796
+ // named by `default`, the name a default import gives it.
5797
+ const value = resolved(whole);
5798
+ if (!found.has("default") && isCallable(value))
5799
+ add("default", value);
5800
+ }
5801
+ }
5802
+ if (flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)) {
5803
+ for (const one of checker().getDeclaredTypeOfSymbol(target).getProperties()) {
5804
+ add(one.getName(), one);
5805
+ }
5806
+ }
5807
+ if (flags &
5808
+ (ts.SymbolFlags.Variable |
5809
+ ts.SymbolFlags.Property |
5810
+ ts.SymbolFlags.Accessor |
5811
+ ts.SymbolFlags.Function |
5812
+ ts.SymbolFlags.Class)) {
5813
+ for (const one of checker().getTypeOfSymbol(target).getProperties()) {
5814
+ add(one.getName(), one);
5815
+ }
5816
+ }
5817
+ children.set(target, found);
5818
+ return found;
5819
+ };
5820
+ const declarationsOf = (symbols) => new Set(symbols.flatMap((one) => resolved(one).declarations ?? []));
5821
+ /**
5822
+ * The declarations a class or a value is known by as a receiver: its own (a class, an interface,
5823
+ * an alias), and for a value (`export const client: Client`) those of its type.
5824
+ */
5825
+ const ownerDeclarationsOf = (symbol) => {
5826
+ const target = resolved(symbol);
5827
+ const own = target.declarations ?? [];
5828
+ if ((target.flags & (ts.SymbolFlags.Variable | ts.SymbolFlags.Property)) === 0)
5829
+ return own;
5830
+ const typed = checker().getTypeOfSymbol(target).getSymbol();
5831
+ return [...own, ...(typed?.declarations ?? [])];
5832
+ };
5833
+ /** Whether a member's declaration is written in one of `owners` (`class Store { save(): void }`). */
5834
+ const declaredIn = (declaration, owners) => {
5835
+ const container = declaration.parent;
5836
+ return (owners.has(container) || (ts.isTypeLiteralNode(container) && owners.has(container.parent)));
5837
+ };
5838
+ /**
5839
+ * The members one step below `owners` (`"Store.*"`): each member written in an owner is stated
5840
+ * on any call; a member an owner inherits (`find` of its `Base`) only through a receiver that is
5841
+ * the owner, or extends it. `keep` leaves members out (a package line keeps its own package's).
5842
+ */
5843
+ const membersOf = (owners, declarations, throughReceiver, keep) => {
5844
+ for (const owner of owners) {
5845
+ const ownerDeclarations = new Set(ownerDeclarationsOf(owner));
5846
+ for (const member of [...childrenOf(owner).values()].flat()) {
5847
+ for (const declaration of resolved(member).declarations ?? []) {
5848
+ if (!keep(declaration))
5849
+ continue;
5850
+ if (declaredIn(declaration, ownerDeclarations)) {
5851
+ declarations.add(declaration);
5852
+ continue;
5853
+ }
5854
+ const classes = throughReceiver.get(declaration) ?? new Set();
5855
+ for (const one of ownerDeclarations)
5856
+ classes.add(one);
5857
+ throughReceiver.set(declaration, classes);
5858
+ }
5859
+ }
5860
+ }
5861
+ };
5862
+ /** The target: a declaration stated on any call needs no receiver as well. */
5863
+ const foundTarget = (declarations, throughReceiver) => {
5864
+ for (const declaration of declarations)
5865
+ throughReceiver.delete(declaration);
5866
+ return { kind: "found", declarations, throughReceiver };
5867
+ };
5868
+ /** `"Store.*"`: the methods and properties of the class, the inherited ones by their receiver. */
5869
+ const classTarget = (owners) => {
5870
+ const declarations = new Set();
5871
+ const throughReceiver = new Map();
5872
+ membersOf(owners, declarations, throughReceiver, () => true);
5873
+ return foundTarget(declarations, throughReceiver);
5874
+ };
5875
+ /**
5876
+ * `"*"`: what the module exports, and the members of what it exports that its own package
5877
+ * declares; a member of another package (`on` of an `EventEmitter` a class extends) is never
5878
+ * stated by it.
5879
+ */
5880
+ const packageTarget = (moduleSymbols) => {
5881
+ const packages = new Set(moduleSymbols.flatMap((one) => (resolved(one).declarations ?? []).map((declaration) => packageOf(toTypeScriptPath(declaration.getSourceFile().fileName)))));
5882
+ const exported = moduleSymbols.flatMap((one) => [...childrenOf(one).values()].flat());
5883
+ const declarations = declarationsOf(exported);
5884
+ const throughReceiver = new Map();
5885
+ membersOf(exported, declarations, throughReceiver, (declaration) => packages.has(packageOf(toTypeScriptPath(declaration.getSourceFile().fileName))));
5886
+ return foundTarget(declarations, throughReceiver);
5887
+ };
5888
+ const target = (module, name) => {
5889
+ const key = `${module}\u0000${name}`;
5890
+ const known = targets.get(key);
5891
+ if (known !== undefined)
5892
+ return known;
5893
+ const moduleSymbols = modulesNamed(module);
5894
+ let found;
5895
+ if (moduleSymbols.length === 0) {
5896
+ found = { kind: "no-module" };
5897
+ }
5898
+ else {
5899
+ const grain = factGrainOf(name);
5900
+ // A grain names the members one step below what its path reaches: a class's methods and
5901
+ // properties (with the inherited ones its type has), or the module's exports and theirs.
5902
+ const path = grain.kind === "function" ? name : grain.kind === "class" ? grain.owner : "";
5903
+ let current = moduleSymbols;
5904
+ for (const part of path === "" ? [] : path.split(".")) {
5905
+ const next = [...new Set(current.flatMap((one) => childrenOf(one).get(part) ?? []))];
5906
+ current = next;
5907
+ if (next.length === 0)
5908
+ break;
5909
+ }
5910
+ found =
5911
+ current.length === 0
5912
+ ? { kind: "no-name" }
5913
+ : grain.kind === "function"
5914
+ ? { kind: "found", declarations: declarationsOf(current), throughReceiver: new Map() }
5915
+ : grain.kind === "class"
5916
+ ? classTarget(current)
5917
+ : packageTarget(moduleSymbols);
5918
+ }
5919
+ targets.set(key, found);
5920
+ return found;
5921
+ };
5922
+ /** The paths of a module up to `LISTED_DEPTH`, shortest first, each with its symbols. */
5923
+ const listedOf = (module) => {
5924
+ const known = listed.get(module);
5925
+ if (known !== undefined)
5926
+ return known;
5927
+ const found = new Map();
5928
+ let level = modulesNamed(module).flatMap((one) => [
5929
+ ...childrenOf(one),
5930
+ ]);
5931
+ for (let depth = 1; depth <= LISTED_DEPTH && level.length > 0; depth++) {
5932
+ const next = [];
5933
+ for (const [name, symbols] of level) {
5934
+ if (found.size >= MAX_LISTED)
5935
+ break;
5936
+ found.set(name, symbols);
5937
+ if (depth === LISTED_DEPTH)
5938
+ continue;
5939
+ for (const symbol of symbols) {
5940
+ for (const [child, list] of childrenOf(symbol))
5941
+ next.push([`${name}.${child}`, list]);
5942
+ }
5943
+ }
5944
+ level = next;
5945
+ }
5946
+ listed.set(module, found);
5947
+ return found;
5948
+ };
5949
+ /**
5950
+ * The shortest name in `module` that resolves to `declaration`: the declaration's own path in
5951
+ * its types (`["path", "PlatformPath", "join"]`), its last names first (`join`, then
5952
+ * `PlatformPath.join`), each resolved forward as a key is, then `default`, then the
5953
+ * declaration's own name under each of the module's exports (`Buffer.from`, where the module
5954
+ * exports a value whose type has the method), shortest export first. Nothing is listed: a hint
5955
+ * asks this for every unknown call.
5956
+ */
5957
+ const nameOf = (module, declaration) => {
5958
+ const names = pathOf(declaration);
5959
+ const resolves = (name) => {
5960
+ const found = target(module, name);
5961
+ return found.kind === "found" && found.declarations.has(declaration);
5962
+ };
5963
+ const own = [...names.map((_, at) => names.slice(names.length - 1 - at).join(".")), "default"];
5964
+ const direct = own.find(resolves);
5965
+ const last = names.at(-1);
5966
+ const moduleSymbols = modulesNamed(module);
5967
+ if (direct !== undefined || last === undefined || moduleSymbols.length === 0)
5968
+ return direct;
5969
+ const exports = [...new Set(moduleSymbols.flatMap((one) => [...childrenOf(one).keys()]))].sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
5970
+ return exports.map((name) => `${name}.${last}`).find(resolves);
5971
+ };
5972
+ return {
5973
+ modulesNamed,
5974
+ target,
5975
+ // Only the name the hint gives for a declaration, so "did you mean" and the hint agree
5976
+ // (`join`, not `posix.join` for the same function).
5977
+ names: (module) => [...listedOf(module)].flatMap(([name, symbols]) => [...declarationsOf(symbols)].some((node) => nameOf(module, node) === name) ? [name] : []),
5978
+ nameOf,
5979
+ };
5980
+ }
5981
+ /** How many aliases (imports, re-exports) a reference is followed through to its module. */
5982
+ const MAX_ALIAS_STEPS = 8;
5983
+ function unwrappedReference(node) {
5984
+ let current = node;
5985
+ while (ts.isParenthesizedExpression(current) ||
5986
+ ts.isNonNullExpression(current) ||
5987
+ ts.isAsExpression(current) ||
5988
+ ts.isSatisfiesExpression(current)) {
5989
+ current = current.expression;
5990
+ }
5991
+ return current;
5992
+ }
5993
+ /** The leftmost name of a reference: `db` of `db.users.watch`, `make` of `make().run`. */
5994
+ function referenceRoot(node) {
5995
+ const bare = unwrappedReference(node);
5996
+ if (ts.isIdentifier(bare))
5997
+ return bare;
5998
+ if (ts.isPropertyAccessExpression(bare) ||
5999
+ ts.isElementAccessExpression(bare) ||
6000
+ ts.isCallExpression(bare) ||
6001
+ ts.isNewExpression(bare)) {
6002
+ return referenceRoot(bare.expression);
6003
+ }
6004
+ return undefined;
6005
+ }
6006
+ /** The module an import or re-export declaration names (`"kit"` of `import { a } from "kit"`). */
6007
+ function specifierOf(declaration) {
6008
+ if (ts.isImportEqualsDeclaration(declaration) &&
6009
+ ts.isExternalModuleReference(declaration.moduleReference) &&
6010
+ ts.isStringLiteral(declaration.moduleReference.expression)) {
6011
+ return declaration.moduleReference.expression;
6012
+ }
6013
+ const statement = ts.findAncestor(declaration, (node) => ts.isImportDeclaration(node) || ts.isExportDeclaration(node));
6014
+ const specifier = statement !== undefined &&
6015
+ (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement))
6016
+ ? statement.moduleSpecifier
6017
+ : undefined;
6018
+ return specifier !== undefined && ts.isStringLiteral(specifier) ? specifier : undefined;
6019
+ }
6020
+ /** The module specifiers a file's top-level imports and re-exports write, in file order. */
6021
+ function specifiersOf(file) {
6022
+ return file.statements.flatMap((statement) => {
6023
+ const specifier = ts.isImportDeclaration(statement) ||
6024
+ ts.isExportDeclaration(statement) ||
6025
+ ts.isImportEqualsDeclaration(statement)
6026
+ ? specifierOf(statement)
6027
+ : undefined;
6028
+ return specifier === undefined ? [] : [specifier];
6029
+ });
2429
6030
  }
2430
6031
  /**
2431
- * Opens the package at `root` from `entry` (a JavaScript file in it). Its files are parsed with
2432
- * the library files' cache, so a later package or project shares TypeScript's lib files.
6032
+ * The module a `facts` key for a declaration outside the project is written from
6033
+ * (`TypeQueries.factModuleOf`), and the name in it, by the first module that names the
6034
+ * declaration (`FactNames.nameOf`) of these:
6035
+ *
6036
+ * 1. the module the reference's leftmost name is imported from, as the project writes it, after
6037
+ * following re-exports and aliases out of the project's files;
6038
+ * 2. the modules the files on that way, and the reference's own file, import or re-export;
6039
+ * 3. the module the declaration is declared in (`declare module "x"`), else its package;
6040
+ * 4. the modules of the declaration's own package the program loads: the ambient modules its files
6041
+ * declare, and the modules the program's files import from it, by name.
6042
+ *
6043
+ * A module of the project's own files is never one: a key names code outside the project.
2433
6044
  */
2434
- export function openPackageSource(root, entry) {
2435
- const packageRoot = toTypeScriptPath(root);
2436
- const inPackage = (file) => file.startsWith(`${packageRoot}/`) &&
2437
- !file.slice(packageRoot.length).includes("/node_modules/");
2438
- const base = hostWithOverlays(PACKAGE_OPTIONS, new Map(), new Map(), false, false, isTypeScriptLib);
2439
- const host = {
2440
- ...base,
2441
- // Relative specifiers inside the package only: another package is not followed (its calls
2442
- // stay unknown), and nothing here is an "external library" TypeScript would skip.
2443
- resolveModuleNameLiterals: (literals, containingFile) => literals.map((literal) => {
2444
- if (!isRelativeSpecifier(literal.text))
2445
- return { resolvedModule: undefined };
2446
- const found = ts.resolveModuleName(literal.text, containingFile, PACKAGE_OPTIONS, base);
2447
- const resolved = found.resolvedModule;
2448
- if (resolved === undefined ||
2449
- !PACKAGE_JAVASCRIPT.test(resolved.resolvedFileName) ||
2450
- !inPackage(toTypeScriptPath(resolved.resolvedFileName))) {
2451
- return { resolvedModule: undefined };
2452
- }
2453
- return { resolvedModule: { ...resolved, isExternalLibraryImport: false } };
2454
- }),
2455
- };
2456
- const program = ts.createProgram({
2457
- rootNames: [toTypeScriptPath(entry)],
2458
- options: PACKAGE_OPTIONS,
2459
- host,
2460
- });
2461
- const files = program
2462
- .getSourceFiles()
2463
- .map((file) => file.fileName)
2464
- .filter((file) => inPackage(file) && PACKAGE_JAVASCRIPT.test(file))
2465
- .sort();
2466
- const own = new Set(files);
2467
- const types = createTypeQueries(program, own, packageRoot, packageNames(host), packageEntries(host), packageDependencies(host));
2468
- // Plugins walk the nodes with parents: the binder sets them.
2469
- const checker = program.getTypeChecker();
2470
- const idFileName = idFileNames(packageRoot);
2471
- const refOf = (symbol) => {
2472
- const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
2473
- const declaration = resolved.valueDeclaration ?? resolved.declarations?.[0];
2474
- if (declaration === undefined)
2475
- return undefined;
2476
- const file = declaration.getSourceFile().fileName;
2477
- return { id: `${idFileName(file)}#${declarationPath(declaration)}`, name: resolved.getName() };
6045
+ function createFactModules(input) {
6046
+ const { checker, program, names, own, isPlatformFile, packageOf } = input;
6047
+ const known = new WeakMap();
6048
+ let byPackage;
6049
+ const isOwn = (file) => own.has(file.fileName);
6050
+ /** Whether a specifier names a module outside the project, as a key can be resolved from it. */
6051
+ const leavesProject = (specifier) => {
6052
+ const text = specifier.text;
6053
+ if (text.startsWith(".") || path.isAbsolute(text))
6054
+ return false;
6055
+ const declarations = checker().getSymbolAtLocation(specifier)?.declarations ?? [];
6056
+ return declarations.length > 0 && declarations.every((one) => !isOwn(one.getSourceFile()));
2478
6057
  };
2479
- const member = (symbol, name) => {
2480
- const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
2481
- const escaped = ts.escapeLeadingUnderscores(name);
2482
- return (resolved.members?.get(escaped) ??
2483
- resolved.exports?.get(escaped) ??
2484
- checker.getTypeOfSymbol(resolved).getProperty(name));
6058
+ /** The modules of each package the program loads, by name: ambient ones and imported ones. */
6059
+ const modulesByPackage = () => {
6060
+ if (byPackage !== undefined)
6061
+ return byPackage;
6062
+ const found = new Map();
6063
+ const add = (file, module) => {
6064
+ const owner = packageOf(file.fileName);
6065
+ if (owner === undefined || isOwn(file))
6066
+ return;
6067
+ found.set(owner, (found.get(owner) ?? new Set()).add(module));
6068
+ };
6069
+ for (const symbol of checker().getAmbientModules()) {
6070
+ for (const declaration of symbol.declarations ?? []) {
6071
+ if (ts.isModuleDeclaration(declaration) && ts.isStringLiteral(declaration.name)) {
6072
+ add(declaration.getSourceFile(), declaration.name.text);
6073
+ }
6074
+ }
6075
+ }
6076
+ for (const file of program.getSourceFiles()) {
6077
+ for (const specifier of specifiersOf(file)) {
6078
+ if (!leavesProject(specifier))
6079
+ continue;
6080
+ const target = checker().getSymbolAtLocation(specifier)?.declarations?.[0];
6081
+ if (target !== undefined)
6082
+ add(target.getSourceFile(), specifier.text);
6083
+ }
6084
+ }
6085
+ byPackage = new Map([...found].map(([owner, modules]) => [owner, [...modules].sort()]));
6086
+ return byPackage;
2485
6087
  };
2486
- return {
2487
- files,
2488
- sourceFile: (file) => program.getSourceFile(toTypeScriptPath(file)),
2489
- types,
2490
- exported(file, names) {
2491
- const sourceFile = program.getSourceFile(toTypeScriptPath(file));
2492
- const moduleSymbol = sourceFile === undefined ? undefined : moduleSymbolOf(checker, sourceFile);
2493
- const [first, ...rest] = names;
2494
- if (moduleSymbol === undefined || first === undefined)
2495
- return undefined;
2496
- let symbol = checker.getExportsOfModule(moduleSymbol).find((one) => one.getName() === first);
2497
- if (symbol === undefined) {
2498
- // `module.exports = fn`: the module is the function.
2499
- const assigned = moduleSymbol.exports?.get(ts.InternalSymbolName.ExportEquals);
2500
- const whole = assigned === undefined || !(assigned.flags & ts.SymbolFlags.Alias)
2501
- ? assigned
2502
- : checker.getAliasedSymbol(assigned);
2503
- if (whole !== undefined && (first === "default" || whole.getName() === first)) {
2504
- symbol = whole;
6088
+ /** Step 1 and the files it passes: the module the reference is imported from, followed out. */
6089
+ const imported = (reference) => {
6090
+ const files = [reference.getSourceFile()];
6091
+ const root = referenceRoot(reference);
6092
+ let symbol = root === undefined ? undefined : checker().getSymbolAtLocation(root);
6093
+ for (let step = 0; step < MAX_ALIAS_STEPS && symbol !== undefined; step++) {
6094
+ if ((symbol.flags & ts.SymbolFlags.Alias) === 0)
6095
+ break;
6096
+ for (const declaration of symbol.declarations ?? []) {
6097
+ const file = declaration.getSourceFile();
6098
+ if (!isOwn(file))
6099
+ continue;
6100
+ if (!files.includes(file))
6101
+ files.push(file);
6102
+ const specifier = specifierOf(declaration);
6103
+ if (specifier !== undefined && leavesProject(specifier)) {
6104
+ return { module: specifier.text, files };
2505
6105
  }
2506
6106
  }
2507
- for (const name of rest) {
2508
- if (symbol === undefined)
2509
- return undefined;
2510
- symbol = member(symbol, name);
6107
+ symbol = checker().getImmediateAliasedSymbol(symbol);
6108
+ }
6109
+ return { files };
6110
+ };
6111
+ const isPlatformModule = (module) => {
6112
+ const declarations = names.modulesNamed(module).flatMap((one) => one.declarations ?? []);
6113
+ return (declarations.length > 0 && declarations.every((one) => isPlatformFile(one.getSourceFile())));
6114
+ };
6115
+ const search = (declaration, reference) => {
6116
+ const way = imported(reference);
6117
+ const file = declaration.getSourceFile();
6118
+ const owner = packageOf(file.fileName);
6119
+ const candidates = [
6120
+ way.module,
6121
+ ...way.files.flatMap((one) => specifiersOf(one).flatMap((specifier) => leavesProject(specifier) ? [specifier.text] : [])),
6122
+ declaredPackageOf({ packageOf }, { file: file.fileName, node: declaration }),
6123
+ ...(owner === undefined ? [] : (modulesByPackage().get(owner) ?? [])),
6124
+ ];
6125
+ for (const module of new Set(candidates)) {
6126
+ if (module === undefined)
6127
+ continue;
6128
+ const name = names.nameOf(module, declaration);
6129
+ if (name !== undefined) {
6130
+ return { kind: "named", module, name, platform: isPlatformModule(module) };
2511
6131
  }
2512
- return symbol === undefined ? undefined : refOf(symbol);
2513
- },
6132
+ }
6133
+ return way.module === undefined
6134
+ ? { kind: "unnamed" }
6135
+ : { kind: "unnamed", through: way.module };
6136
+ };
6137
+ return (declaration, reference) => {
6138
+ const root = referenceRoot(reference);
6139
+ const symbol = root === undefined ? undefined : checker().getSymbolAtLocation(root);
6140
+ // The answer depends on the import the reference comes through, else on its file's imports.
6141
+ const key = symbol !== undefined && (symbol.flags & ts.SymbolFlags.Alias) !== 0
6142
+ ? symbol
6143
+ : reference.getSourceFile();
6144
+ let answers = known.get(declaration);
6145
+ if (answers === undefined) {
6146
+ answers = new Map();
6147
+ known.set(declaration, answers);
6148
+ }
6149
+ const cached = answers.get(key);
6150
+ if (cached !== undefined)
6151
+ return cached;
6152
+ const found = search(declaration, reference);
6153
+ answers.set(key, found);
6154
+ return found;
2514
6155
  };
2515
6156
  }
2516
6157
  /**