@stateward/core 1.0.1 → 1.2.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 (49) hide show
  1. package/dist/backend/fingerprints.d.ts +22 -2
  2. package/dist/backend/fingerprints.js +160 -18
  3. package/dist/backend/program-record.d.ts +1 -1
  4. package/dist/backend/qualified-ids.d.ts +6 -0
  5. package/dist/backend/qualified-ids.js +66 -10
  6. package/dist/backend/typescript6.d.ts +28 -9
  7. package/dist/backend/typescript6.js +564 -28
  8. package/dist/baseline.js +10 -0
  9. package/dist/cache.d.ts +5 -4
  10. package/dist/cache.js +2 -2
  11. package/dist/checker.d.ts +14 -2
  12. package/dist/checker.js +40 -12
  13. package/dist/config-file.d.ts +6 -0
  14. package/dist/config-file.js +21 -2
  15. package/dist/config.d.ts +3 -1
  16. package/dist/config.js +164 -17
  17. package/dist/define.d.ts +2 -1
  18. package/dist/disk-cache.d.ts +24 -2
  19. package/dist/disk-cache.js +43 -5
  20. package/dist/engine.d.ts +27 -3
  21. package/dist/engine.js +224 -57
  22. package/dist/guarantee-markers.d.ts +10 -0
  23. package/dist/guarantee-markers.js +66 -0
  24. package/dist/guarantees.d.ts +44 -0
  25. package/dist/guarantees.js +84 -0
  26. package/dist/hint-lines.d.ts +24 -0
  27. package/dist/hint-lines.js +36 -0
  28. package/dist/ignores.d.ts +2 -4
  29. package/dist/ignores.js +31 -16
  30. package/dist/implementation.js +2 -1
  31. package/dist/index.d.ts +5 -1
  32. package/dist/index.js +4 -0
  33. package/dist/internal.d.ts +8 -3
  34. package/dist/internal.js +6 -3
  35. package/dist/package-facts.d.ts +52 -0
  36. package/dist/package-facts.js +213 -0
  37. package/dist/plan.d.ts +17 -0
  38. package/dist/plan.js +22 -5
  39. package/dist/release.d.ts +68 -0
  40. package/dist/release.js +172 -0
  41. package/dist/renamed.d.ts +29 -0
  42. package/dist/renamed.js +48 -0
  43. package/dist/rollout.js +3 -1
  44. package/dist/testing-tsc.d.ts +11 -0
  45. package/dist/testing-tsc.js +125 -0
  46. package/dist/testing.d.ts +1 -0
  47. package/dist/testing.js +61 -8
  48. package/dist/types.d.ts +261 -2
  49. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
1
  import path from "node:path";
2
2
  import picomatch from "picomatch";
3
3
  import ts from "typescript";
4
- import { computeFingerprints, packageDependencies, packageEntries, packageManifests, packageNames, textHash, } from "./fingerprints.js";
4
+ import { computeFingerprints, declarationTextHash, packageDependencies, packageEntries, packageManifests, packageNames, } from "./fingerprints.js";
5
5
  import { markedComments } from "./comments.js";
6
6
  import { recordInputs, recordingHost, replays } from "./program-record.js";
7
- import { declarationPath } from "./qualified-ids.js";
7
+ import { declarationAtPath, declarationPath } from "./qualified-ids.js";
8
8
  import { displayPath } from "../display-path.js";
9
9
  import { expandTsconfigs } from "../tsconfigs.js";
10
10
  /** The tsconfig could not be read or is invalid. */
@@ -300,9 +300,16 @@ function tryEditsOn(program, host, candidates) {
300
300
  const ranges = new Map();
301
301
  /** Per edited file, the edits placed in it and how an offset of the old text moves. */
302
302
  const moves = new Map();
303
+ /** Files a fix creates: edits at the start of a file that does not exist yet. */
304
+ const created = new Set();
303
305
  for (const [file, placed] of byFile) {
304
306
  const sourceFile = program.getSourceFile(file);
305
- const text = sourceFile?.text;
307
+ const creates = sourceFile === undefined &&
308
+ !host.fileExists(file) &&
309
+ placed.every(({ edit: { location } }) => location.start === 0 && location.end === 0);
310
+ if (creates)
311
+ created.add(file);
312
+ const text = creates ? "" : sourceFile?.text;
306
313
  const fits = placed.every(({ edit: { location } }) => text !== undefined &&
307
314
  location.start >= 0 &&
308
315
  location.start <= location.end &&
@@ -378,6 +385,18 @@ function tryEditsOn(program, host, candidates) {
378
385
  for (const [file, spans] of ranges) {
379
386
  const before = program.getSourceFile(file);
380
387
  const after = copy.getSourceFile(file);
388
+ if (created.has(file) && after !== undefined) {
389
+ // Every error in a file the fix writes is the fix's own.
390
+ const [error] = errorsOf(copy, after);
391
+ if (error === undefined)
392
+ continue;
393
+ for (const { candidate } of spans) {
394
+ if (verdicts[candidate]?.kind === "compiles") {
395
+ verdicts[candidate] = { kind: "breaks", error: firstLine(error) };
396
+ }
397
+ }
398
+ continue;
399
+ }
381
400
  if (before === undefined || after === undefined)
382
401
  continue;
383
402
  // A fix that changes a declaration's type answers for every line of the files it edits.
@@ -474,6 +493,34 @@ function unresolvedImportsOf(program, file) {
474
493
  }
475
494
  return found;
476
495
  }
496
+ /** Whether a project with these options checks with `strictNullChecks` (TypeScript 6: on unless turned off). */
497
+ export function checksNulls(options) {
498
+ return options.strictNullChecks ?? options.strict ?? true;
499
+ }
500
+ const TYPED_EXTENSIONS = new Set([
501
+ ts.Extension.Dts,
502
+ ts.Extension.Dmts,
503
+ ts.Extension.Dcts,
504
+ ts.Extension.Ts,
505
+ ts.Extension.Tsx,
506
+ ts.Extension.Mts,
507
+ ts.Extension.Cts,
508
+ ]);
509
+ /** `ProjectUnit.typesResolve` for a project, remembered by module name. */
510
+ function typesResolver(tsconfig, options) {
511
+ const known = new Map();
512
+ // A file that need not exist: resolution only looks at its folder and above.
513
+ const from = path.join(path.dirname(tsconfig), "__stateward_types__.ts");
514
+ return (module) => {
515
+ const before = known.get(module);
516
+ if (before !== undefined)
517
+ return before;
518
+ const resolved = ts.resolveModuleName(module, from, options, ts.sys).resolvedModule;
519
+ const typed = resolved !== undefined && TYPED_EXTENSIONS.has(resolved.extension);
520
+ known.set(module, typed);
521
+ return typed;
522
+ };
523
+ }
477
524
  function firstSyntaxError(program, file) {
478
525
  const sourceFile = program.getSourceFile(file);
479
526
  if (sourceFile === undefined)
@@ -625,6 +672,21 @@ shared = isLibraryFile) {
625
672
  },
626
673
  };
627
674
  }
675
+ /**
676
+ * The host a recorded program is replayed against: the disk, with `overlays` in front of it as
677
+ * `hostWithOverlays` serves them (an overlay exists, and its text is what is read), so a replay
678
+ * answers as the build it stands for would have.
679
+ */
680
+ function replayHost(options, overlays) {
681
+ const base = ts.createCompilerHost(options, false);
682
+ if (overlays.size === 0)
683
+ return base;
684
+ return {
685
+ ...base,
686
+ fileExists: (fileName) => overlays.has(fileName) || base.fileExists(fileName),
687
+ readFile: (fileName) => overlays.get(fileName) ?? base.readFile(fileName),
688
+ };
689
+ }
628
690
  function matcher(patterns) {
629
691
  if (patterns.length === 0)
630
692
  return () => false;
@@ -667,7 +729,8 @@ function compareLabels(a, b) {
667
729
  return -1;
668
730
  return a.label > b.label ? 1 : 0;
669
731
  }
670
- function literalOf(checker, member) {
732
+ function literalOf(checker, found) {
733
+ const member = withoutMarkers(checker, found);
671
734
  const label = checker.typeToString(member);
672
735
  if (member.isStringLiteral() || member.isNumberLiteral())
673
736
  return { value: member.value, label };
@@ -679,6 +742,14 @@ function literalOf(checker, member) {
679
742
  return { value: undefined, label };
680
743
  return undefined;
681
744
  }
745
+ /** The literal of `"paid" & { "__guarantee:open-union"?: true }`; any other type as it is. */
746
+ function withoutMarkers(checker, type) {
747
+ if (!type.isIntersection())
748
+ return type;
749
+ const rest = type.types.filter((part) => !isMarkerOnly(checker, part));
750
+ const [only] = rest;
751
+ return rest.length === 1 && only !== undefined && rest.length < type.types.length ? only : type;
752
+ }
682
753
  /** The types compared by value: `===` on two of them never tells apart equal values. */
683
754
  const PRIMITIVE_FLAGS = ts.TypeFlags.StringLike |
684
755
  ts.TypeFlags.NumberLike |
@@ -731,6 +802,239 @@ function isPromiseType(checker, type) {
731
802
  return awaited !== undefined && awaited !== type;
732
803
  }
733
804
  const NULLISH = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
805
+ /** The property a stated guarantee is written in by 1.1.0 (`__guarantee?: "owned"`). */
806
+ const GUARANTEE_PROPERTY = "__guarantee";
807
+ /** The prefix of the property each trait is written in from 1.2 (`"__guarantee:owned"?: true`). */
808
+ const GUARANTEE_PREFIX = "__guarantee:";
809
+ /** Whether `file` declares a property named `marker` (`"__guarantee:opaque"?: …`) in a type or class. */
810
+ function declaresMarkerProperty(file, marker) {
811
+ let found = false;
812
+ const visit = (node) => {
813
+ if (found)
814
+ return;
815
+ if ((ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) &&
816
+ (ts.isStringLiteral(node.name) || ts.isIdentifier(node.name)) &&
817
+ node.name.text === marker) {
818
+ found = true;
819
+ return;
820
+ }
821
+ ts.forEachChild(node, visit);
822
+ };
823
+ visit(file);
824
+ return found;
825
+ }
826
+ /** Adds the `as` names a file's import and export specifiers give: `onSnapshot` → `listen`. */
827
+ function addRenamed(file, renamed) {
828
+ const add = (specifier) => {
829
+ const from = specifier.propertyName;
830
+ if (from === undefined || !ts.isIdentifier(from))
831
+ return;
832
+ const names = renamed.get(from.text) ?? new Set();
833
+ names.add(specifier.name.text);
834
+ renamed.set(from.text, names);
835
+ };
836
+ const addName = (from, to) => {
837
+ if (from === to)
838
+ return;
839
+ const names = renamed.get(from) ?? new Set();
840
+ names.add(to);
841
+ renamed.set(from, names);
842
+ };
843
+ for (const statement of file.statements) {
844
+ if (ts.isImportDeclaration(statement)) {
845
+ const bindings = statement.importClause?.namedBindings;
846
+ if (bindings !== undefined && ts.isNamedImports(bindings))
847
+ bindings.elements.forEach(add);
848
+ }
849
+ else if (ts.isExportDeclaration(statement) &&
850
+ statement.exportClause !== undefined &&
851
+ ts.isNamedExports(statement.exportClause)) {
852
+ statement.exportClause.elements.forEach(add);
853
+ }
854
+ }
855
+ // `const listen = onSnapshot`, `const listen = db.onSnapshot` and
856
+ // `const { onSnapshot: listen } = db`, anywhere in the file.
857
+ const visit = (node) => {
858
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
859
+ let value = node.initializer;
860
+ while (ts.isParenthesizedExpression(value) ||
861
+ ts.isAsExpression(value) ||
862
+ ts.isSatisfiesExpression(value) ||
863
+ ts.isNonNullExpression(value)) {
864
+ value = value.expression;
865
+ }
866
+ if (ts.isIdentifier(value))
867
+ addName(value.text, node.name.text);
868
+ else if (ts.isPropertyAccessExpression(value))
869
+ addName(value.name.text, node.name.text);
870
+ }
871
+ else if (ts.isBindingElement(node) &&
872
+ node.propertyName !== undefined &&
873
+ ts.isIdentifier(node.propertyName) &&
874
+ ts.isIdentifier(node.name)) {
875
+ addName(node.propertyName.text, node.name.text);
876
+ }
877
+ ts.forEachChild(node, visit);
878
+ };
879
+ visit(file);
880
+ }
881
+ /** Whether a file declares a member named `[Symbol.dispose]` or `[Symbol.asyncDispose]`. */
882
+ function declaresDisposeMember(file) {
883
+ let found = false;
884
+ const visit = (node) => {
885
+ if (found)
886
+ return;
887
+ if (ts.isComputedPropertyName(node) &&
888
+ ts.isPropertyAccessExpression(node.expression) &&
889
+ ts.isIdentifier(node.expression.expression) &&
890
+ node.expression.expression.text === "Symbol" &&
891
+ (node.expression.name.text === "dispose" || node.expression.name.text === "asyncDispose")) {
892
+ found = true;
893
+ return;
894
+ }
895
+ ts.forEachChild(node, visit);
896
+ };
897
+ visit(file);
898
+ return found;
899
+ }
900
+ /**
901
+ * The guarantee names of one type that is not a union: one per optional `"__guarantee:<name>"`
902
+ * property, and the string literals of an optional `__guarantee` property (the 1.1.0 form).
903
+ */
904
+ function memberGuarantees(checker, type) {
905
+ const names = [];
906
+ for (const property of checker.getPropertiesOfType(type)) {
907
+ const name = property.getName();
908
+ if (!name.startsWith(GUARANTEE_PREFIX) || !(property.flags & ts.SymbolFlags.Optional))
909
+ continue;
910
+ const trait = name.slice(GUARANTEE_PREFIX.length);
911
+ if (trait !== "")
912
+ names.push(trait);
913
+ }
914
+ return [...names, ...legacyGuarantees(checker, type)];
915
+ }
916
+ /** The names of the 1.1.0 form, `__guarantee?: "owned"`; none when it is required or not literals (a brand). */
917
+ function legacyGuarantees(checker, type) {
918
+ const property = checker.getPropertyOfType(type, GUARANTEE_PROPERTY);
919
+ if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
920
+ return [];
921
+ const value = checker.getTypeOfSymbol(property);
922
+ const names = [];
923
+ for (const part of value.isUnion() ? value.types : [value]) {
924
+ if (part.flags & NULLISH)
925
+ continue;
926
+ if (!part.isStringLiteral())
927
+ return [];
928
+ names.push(part.value);
929
+ }
930
+ return names;
931
+ }
932
+ /**
933
+ * Whether an object type only states guarantees: every property is a guarantee marker. A literal
934
+ * intersected with one (`"paid" & { "__guarantee:open-union"?: true }`, what `OpenUnion<T>` gives
935
+ * each member) is still that literal.
936
+ */
937
+ function isMarkerOnly(checker, type) {
938
+ if (!(type.flags & ts.TypeFlags.Object))
939
+ return false;
940
+ const properties = checker.getPropertiesOfType(type);
941
+ return (properties.length > 0 &&
942
+ properties.every((property) => {
943
+ const name = property.getName();
944
+ return ((name === GUARANTEE_PROPERTY || name.startsWith(GUARANTEE_PREFIX)) &&
945
+ (property.flags & ts.SymbolFlags.Optional) !== 0);
946
+ }));
947
+ }
948
+ /**
949
+ * The guarantees every member of `type` states (`null` and `undefined` left out), sorted. A
950
+ * member that states none makes the whole type state none.
951
+ */
952
+ function guaranteesOfType(checker, found) {
953
+ const type = widened(checker, found);
954
+ if (type === undefined)
955
+ return [];
956
+ const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0);
957
+ let shared;
958
+ for (const member of members) {
959
+ const names = memberGuarantees(checker, member);
960
+ shared = shared === undefined ? [...names] : shared.filter((name) => names.includes(name));
961
+ if (shared.length === 0)
962
+ return [];
963
+ }
964
+ return [...new Set(shared ?? [])].sort();
965
+ }
966
+ /**
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.
969
+ */
970
+ function guaranteeValuesOfType(checker, found, name) {
971
+ const type = widened(checker, found);
972
+ if (type === undefined)
973
+ return undefined;
974
+ for (const member of type.isUnion() ? type.types : [type]) {
975
+ if (member.flags & NULLISH)
976
+ continue;
977
+ const property = checker.getPropertyOfType(member, `${GUARANTEE_PREFIX}${name}`);
978
+ if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
979
+ continue;
980
+ const value = checker.getTypeOfSymbol(property);
981
+ const literals = [];
982
+ for (const part of value.isUnion() ? value.types : [value]) {
983
+ if (part.flags & ts.TypeFlags.Undefined)
984
+ continue;
985
+ const literal = literalOf(checker, part);
986
+ if (literal === undefined)
987
+ return "not-finite";
988
+ literals.push(literal);
989
+ }
990
+ return literals.sort(compareLabels);
991
+ }
992
+ return undefined;
993
+ }
994
+ /**
995
+ * How a value of `type` is disposed, read from its well-known symbol methods: `[Symbol.dispose]`
996
+ * (`"sync"`), `[Symbol.asyncDispose]` (`"async"`), with the file that declares the method. Every
997
+ * member but `null` and `undefined` must have the same. `any` and `unknown` have neither.
998
+ */
999
+ function disposeOfType(checker, found) {
1000
+ const type = widened(checker, found);
1001
+ if (type === undefined || type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
1002
+ return undefined;
1003
+ }
1004
+ const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0);
1005
+ const kindOf = (member) => {
1006
+ const properties = checker.getPropertiesOfType(member);
1007
+ for (const [prefix, kind] of [
1008
+ ["__@dispose@", "sync"],
1009
+ ["__@asyncDispose@", "async"],
1010
+ ]) {
1011
+ const property = properties.find((one) => String(one.escapedName).startsWith(prefix));
1012
+ const file = property?.declarations?.[0]?.getSourceFile().fileName;
1013
+ if (file !== undefined)
1014
+ return { kind, file };
1015
+ }
1016
+ return undefined;
1017
+ };
1018
+ const found2 = members.map(kindOf);
1019
+ const [first] = found2;
1020
+ if (first === undefined)
1021
+ return undefined;
1022
+ return found2.every((one) => one?.kind === first.kind && one.file === first.file)
1023
+ ? first
1024
+ : undefined;
1025
+ }
1026
+ /** The declared type of a declaration: a variable's or property's type, or a type alias's. */
1027
+ function declaredTypeOf(checker, declaration) {
1028
+ const name = ts.isDeclarationStatement(declaration) || ts.isVariableDeclaration(declaration)
1029
+ ? ts.getNameOfDeclaration(declaration)
1030
+ : undefined;
1031
+ const symbol = name === undefined ? undefined : checker.getSymbolAtLocation(name);
1032
+ if (symbol === undefined)
1033
+ return checker.getTypeAtLocation(declaration);
1034
+ return symbol.flags & ts.SymbolFlags.Value
1035
+ ? checker.getTypeOfSymbol(symbol)
1036
+ : checker.getDeclaredTypeOfSymbol(symbol);
1037
+ }
734
1038
  /** A string, number or boolean literal, or an enum member: a type with exactly one value. */
735
1039
  function isUnitLiteral(type) {
736
1040
  return (type.isStringLiteral() ||
@@ -761,6 +1065,37 @@ function hasGenericKeys(checker, type) {
761
1065
  checker.getPropertiesOfType(part).length === 0 &&
762
1066
  checker.getIndexInfosOfType(part).length === 0);
763
1067
  }
1068
+ /**
1069
+ * Whether a mapped part of `type` takes its keys from a type that does not resolve:
1070
+ * `{ [k in keyof typeof NAMES]: … }` where `NAMES` comes from a package that is not installed.
1071
+ * TypeScript then gives it index signatures for every key, which says nothing about its keys.
1072
+ */
1073
+ function hasUnresolvedKeys(checker, type) {
1074
+ const parts = type.isIntersection() ? type.types : [type];
1075
+ return parts.some((part) => (part.getSymbol()?.declarations ?? []).some((declaration) => {
1076
+ if (!ts.isMappedTypeNode(declaration))
1077
+ return false;
1078
+ const constraint = declaration.typeParameter.constraint;
1079
+ if (constraint === undefined)
1080
+ return false;
1081
+ let unresolved = false;
1082
+ const visit = (node) => {
1083
+ if (unresolved)
1084
+ return;
1085
+ if (ts.isTypeNode(node) && isErrorTypeOf(checker.getTypeFromTypeNode(node))) {
1086
+ unresolved = true;
1087
+ return;
1088
+ }
1089
+ ts.forEachChild(node, visit);
1090
+ };
1091
+ visit(constraint);
1092
+ return unresolved;
1093
+ }));
1094
+ }
1095
+ /** TypeScript's error type: an `any` whose intrinsic name is "error"; it has no public flag. */
1096
+ function isErrorTypeOf(type) {
1097
+ return !!(type.flags & ts.TypeFlags.Any) && Reflect.get(type, "intrinsicName") === "error";
1098
+ }
764
1099
  function includesUndefined(type) {
765
1100
  const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Undefined | ts.TypeFlags.Void;
766
1101
  return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0);
@@ -985,6 +1320,49 @@ function isReadonlyProperty(owner, property) {
985
1320
  return (declarations.length > 0 &&
986
1321
  declarations.every((declaration) => (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0));
987
1322
  }
1323
+ /** An object type with an `aborted: boolean` property: `AbortSignal`, or a library's own signal type. */
1324
+ function isSignal(checker, type) {
1325
+ const members = withoutNullish(type);
1326
+ return (members.length > 0 &&
1327
+ members.every((member) => {
1328
+ if (!(member.flags & ts.TypeFlags.Object))
1329
+ return false;
1330
+ const aborted = checker.getPropertyOfType(member, "aborted");
1331
+ if (aborted === undefined)
1332
+ return false;
1333
+ const value = checker.getTypeOfSymbol(aborted);
1334
+ return withoutNullish(value).every((part) => (part.flags & ts.TypeFlags.BooleanLike) !== 0);
1335
+ }));
1336
+ }
1337
+ /** Where the callee takes a signal: a parameter that is one, or an options object holding one. */
1338
+ function signalParameter(checker, call) {
1339
+ const signature = checker.getResolvedSignature(call);
1340
+ if (signature === undefined)
1341
+ return undefined;
1342
+ for (const [index, parameter] of signature.parameters.entries()) {
1343
+ const declared = parameter.valueDeclaration;
1344
+ if (declared !== undefined &&
1345
+ ts.isParameter(declared) &&
1346
+ declared.dotDotDotToken !== undefined) {
1347
+ return undefined;
1348
+ }
1349
+ const type = widened(checker, checker.getTypeOfSymbol(parameter));
1350
+ if (type === undefined)
1351
+ continue;
1352
+ if (isSignal(checker, type))
1353
+ return { index, property: undefined };
1354
+ // An options object you fill in; a `Request`, which carries its own readonly signal, is not one.
1355
+ const holds = withoutNullish(type).some((member) => {
1356
+ const signal = checker.getPropertyOfType(member, "signal");
1357
+ return (signal !== undefined &&
1358
+ !isReadonlyProperty(member, signal) &&
1359
+ isSignal(checker, checker.getTypeOfSymbol(signal)));
1360
+ });
1361
+ if (holds)
1362
+ return { index, property: "signal" };
1363
+ }
1364
+ return undefined;
1365
+ }
988
1366
  function withoutNullish(type) {
989
1367
  const nothing = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
990
1368
  return (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & nothing));
@@ -1121,6 +1499,11 @@ export function idFileNames(root) {
1121
1499
  return name;
1122
1500
  };
1123
1501
  }
1502
+ /**
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`).
1505
+ */
1506
+ const REACHABLE_END_CODES = new Set([2366, 2355, 2534, 7030]);
1124
1507
  export function createTypeQueries(program, own,
1125
1508
  /** The project folder qualified ids are relative to. */
1126
1509
  root, packageOf, isEntry, dependenciesOf) {
@@ -1129,6 +1512,11 @@ root, packageOf, isEntry, dependenciesOf) {
1129
1512
  let created;
1130
1513
  const typeChecker = () => (created ??= program.getTypeChecker());
1131
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;
1132
1520
  const idFileName = idFileNames(root);
1133
1521
  // symbolAt is asked about the same node by several rules (on excalidraw 570,000 questions about
1134
1522
  // 170,000 nodes, 52,000 symbols): the program does not change under these queries, so each
@@ -1193,8 +1581,9 @@ root, packageOf, isEntry, dependenciesOf) {
1193
1581
  }
1194
1582
  if (isArrayLike(typeChecker(), type))
1195
1583
  return "not-object";
1196
- if (hasGenericKeys(typeChecker(), type))
1584
+ if (hasGenericKeys(typeChecker(), type) || hasUnresolvedKeys(typeChecker(), type)) {
1197
1585
  return "generic";
1586
+ }
1198
1587
  const required = [];
1199
1588
  const optional = [];
1200
1589
  for (const property of typeChecker().getPropertiesOfType(type)) {
@@ -1312,6 +1701,98 @@ root, packageOf, isEntry, dependenciesOf) {
1312
1701
  }
1313
1702
  return [...files].sort();
1314
1703
  },
1704
+ guaranteesOf(target) {
1705
+ const checker = typeChecker();
1706
+ if ("kind" in target)
1707
+ return guaranteesOfType(checker, checker.getTypeAtLocation(target));
1708
+ const declaration = declarations.get(target.id);
1709
+ const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
1710
+ return type === undefined ? [] : guaranteesOfType(checker, type);
1711
+ },
1712
+ contextualGuaranteesOf(node) {
1713
+ const checker = typeChecker();
1714
+ const type = checker.getContextualType(node);
1715
+ return type === undefined ? [] : guaranteesOfType(checker, type);
1716
+ },
1717
+ guaranteeValuesOf(target, name, contextual = false) {
1718
+ const checker = typeChecker();
1719
+ if ("kind" in target) {
1720
+ const type = contextual && ts.isExpression(target)
1721
+ ? checker.getContextualType(target)
1722
+ : checker.getTypeAtLocation(target);
1723
+ return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
1724
+ }
1725
+ const declaration = declarations.get(target.id);
1726
+ const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
1727
+ return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
1728
+ },
1729
+ contextualAliasOf(node) {
1730
+ const checker = typeChecker();
1731
+ const found = checker.getContextualType(node);
1732
+ const type = found === undefined ? undefined : widened(checker, found);
1733
+ if (type === undefined)
1734
+ return undefined;
1735
+ const aliasOf = (member) => member.aliasSymbol?.declarations?.some(ts.isTypeAliasDeclaration) === true &&
1736
+ (member.aliasTypeArguments?.length ?? 0) === 0
1737
+ ? member.aliasSymbol
1738
+ : undefined;
1739
+ const whole = aliasOf(type);
1740
+ if (whole !== undefined)
1741
+ return refOfSymbol(whole);
1742
+ const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0);
1743
+ const aliases = new Set(members.map(aliasOf));
1744
+ const [only] = aliases;
1745
+ return aliases.size === 1 && only !== undefined ? refOfSymbol(only) : undefined;
1746
+ },
1747
+ bindingPropertyOf(element) {
1748
+ const pattern = element.parent;
1749
+ if (!ts.isObjectBindingPattern(pattern) || element.dotDotDotToken !== undefined) {
1750
+ return undefined;
1751
+ }
1752
+ const key = element.propertyName ?? element.name;
1753
+ if (!ts.isIdentifier(key) && !ts.isStringLiteral(key))
1754
+ return undefined;
1755
+ const checker = typeChecker();
1756
+ const property = checker.getTypeAtLocation(pattern).getProperty(key.text);
1757
+ return property === undefined ? undefined : refOfSymbol(property);
1758
+ },
1759
+ declaresDispose() {
1760
+ // The text is only a quick filter, as for markers: the member must be declared.
1761
+ declaredDispose ??= program
1762
+ .getSourceFiles()
1763
+ .some((file) => own.has(toTypeScriptPath(file.fileName)) &&
1764
+ (file.text.includes("Symbol.dispose") || file.text.includes("Symbol.asyncDispose")) &&
1765
+ declaresDisposeMember(file));
1766
+ return declaredDispose;
1767
+ },
1768
+ renamedBindings() {
1769
+ if (renamedNames === undefined) {
1770
+ const found = new Map();
1771
+ for (const file of program.getSourceFiles()) {
1772
+ if (own.has(toTypeScriptPath(file.fileName)))
1773
+ addRenamed(file, found);
1774
+ }
1775
+ renamedNames = found;
1776
+ }
1777
+ return renamedNames;
1778
+ },
1779
+ declaresTrait(name) {
1780
+ const known = declaredTraits.get(name);
1781
+ if (known !== undefined)
1782
+ return known;
1783
+ const text = `${GUARANTEE_PREFIX}${name}`;
1784
+ // The text is only a quick filter: the marker counts as a property of a type, never inside a
1785
+ // string or a comment (stateward's own packages quote it, and a project's program can
1786
+ // include them through its config file).
1787
+ const found = program
1788
+ .getSourceFiles()
1789
+ .some((file) => file.text.includes(text) && declaresMarkerProperty(file, text));
1790
+ declaredTraits.set(name, found);
1791
+ return found;
1792
+ },
1793
+ disposeOf(node) {
1794
+ return disposeOfType(typeChecker(), typeChecker().getTypeAtLocation(node));
1795
+ },
1315
1796
  awaitedAliasOf(node) {
1316
1797
  return aliasOfType(typeChecker(), typeChecker().getTypeAtLocation(node));
1317
1798
  },
@@ -1329,7 +1810,7 @@ root, packageOf, isEntry, dependenciesOf) {
1329
1810
  return undefined;
1330
1811
  if ((type?.aliasTypeArguments?.length ?? 0) > 0)
1331
1812
  return undefined;
1332
- return { name: alias.getName(), file: declaration.getSourceFile().fileName };
1813
+ return { name: alias.getName(), file: declaration.getSourceFile().fileName, declaration };
1333
1814
  },
1334
1815
  importSpecifierFor(alias, fromFile) {
1335
1816
  const from = toTypeScriptPath(fromFile);
@@ -1478,6 +1959,26 @@ root, packageOf, isEntry, dependenciesOf) {
1478
1959
  calleeTags(call) {
1479
1960
  return calleeTags(typeChecker(), call);
1480
1961
  },
1962
+ signalParameterOf(call) {
1963
+ return signalParameter(typeChecker(), call);
1964
+ },
1965
+ reportsReachableEnd(fn) {
1966
+ const body = fn.body;
1967
+ if (body === undefined)
1968
+ return false;
1969
+ const sourceFile = fn.getSourceFile();
1970
+ let starts = reachableEndErrors.get(sourceFile);
1971
+ if (starts === undefined) {
1972
+ starts = program
1973
+ .getSemanticDiagnostics(sourceFile)
1974
+ .filter((diagnostic) => REACHABLE_END_CODES.has(diagnostic.code))
1975
+ .flatMap((diagnostic) => (diagnostic.start === undefined ? [] : [diagnostic.start]));
1976
+ reachableEndErrors.set(sourceFile, starts);
1977
+ }
1978
+ const from = fn.getStart(sourceFile);
1979
+ const to = body.getStart(sourceFile);
1980
+ return starts.some((start) => start >= from && start < to);
1981
+ },
1481
1982
  narrowedBy(reference, test) {
1482
1983
  return narrowedMembers(program, typeChecker(), reference, test);
1483
1984
  },
@@ -1488,9 +1989,7 @@ root, packageOf, isEntry, dependenciesOf) {
1488
1989
  return predicate === undefined ? undefined : call.arguments[predicate.parameterIndex];
1489
1990
  },
1490
1991
  isErrorType(node) {
1491
- // TypeScript's error type is an `any` whose intrinsic name is "error"; it has no public flag.
1492
- const type = typeChecker().getTypeAtLocation(node);
1493
- return !!(type.flags & ts.TypeFlags.Any) && Reflect.get(type, "intrinsicName") === "error";
1992
+ return isErrorTypeOf(typeChecker().getTypeAtLocation(node));
1494
1993
  },
1495
1994
  isPromiseLike(node) {
1496
1995
  return isPromiseType(typeChecker(), typeChecker().getTypeAtLocation(node));
@@ -1609,8 +2108,10 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1609
2108
  if (missingLib !== undefined)
1610
2109
  throw new TypeScriptLibMissingError(missingLib);
1611
2110
  // Only a program built from nothing asks the host every question; one built on an old
1612
- // program, or on unsaved text, is not recorded.
1613
- const queries = cache !== undefined && oldProgram === undefined && overlays.size === 0 && !trustCache
2111
+ // program is not recorded. One built on unsaved text is: its answers are the overlays', and a
2112
+ // replay serves the overlays of its own run the same way (`replayHost`), so the record holds
2113
+ // exactly while the open documents have that text (an editor's next start).
2114
+ const queries = cache !== undefined && oldProgram === undefined && !trustCache
1614
2115
  ? new Map()
1615
2116
  : undefined;
1616
2117
  const plainHost = hostWithOverlays(parsed.options, overlays, sources, trustCache, jsDoc);
@@ -1652,9 +2153,26 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1652
2153
  }
1653
2154
  return fingerprints;
1654
2155
  };
1655
- /** What each file's rules were handed, by file. */
2156
+ /** What each file's rules were handed, by file: read ids, with the file each one is in. */
1656
2157
  const reads = new Map();
1657
2158
  const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf);
2159
+ const idFileName = idFileNames(cwd);
2160
+ const fileId = (fileName) => `${idFileName(fileName)}#`;
2161
+ /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
2162
+ const readId = (symbol, found) => {
2163
+ if (!types.isOwnFile(found.file) || ts.isSourceFile(found.node))
2164
+ return fileId(found.file);
2165
+ const sourceFile = program.getSourceFile(found.file);
2166
+ const at = symbol.id.indexOf("#");
2167
+ return sourceFile !== undefined &&
2168
+ at >= 0 &&
2169
+ symbol.id.slice(0, at + 1) === fileId(found.file) &&
2170
+ declarationAtPath(sourceFile, symbol.id.slice(at + 1)) === found.node
2171
+ ? symbol.id
2172
+ : fileId(found.file);
2173
+ };
2174
+ /** Read prints computed in this program, by read id. */
2175
+ const prints = new Map();
1658
2176
  const unit = {
1659
2177
  tsconfig: tsconfigPath,
1660
2178
  files,
@@ -1663,29 +2181,46 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1663
2181
  types,
1664
2182
  fingerprint: (file) => fingerprintsOf().get(file),
1665
2183
  typesFor: (file) => {
1666
- const read = reads.get(file) ?? new Set();
2184
+ const read = reads.get(file) ?? new Map();
1667
2185
  reads.set(file, read);
1668
2186
  return {
1669
2187
  ...types,
1670
2188
  declarationOf(symbol) {
1671
2189
  const found = types.declarationOf(symbol);
1672
- if (found !== undefined && found.file !== file)
1673
- read.add(found.file);
2190
+ if (found !== undefined && found.file !== file) {
2191
+ read.set(readId(symbol, found), found.file);
2192
+ }
1674
2193
  return found;
1675
2194
  },
1676
2195
  };
1677
2196
  },
1678
- readsOf: (file) => [...(reads.get(file) ?? [])].sort(),
1679
- readFingerprint: (file) => {
1680
- const sourceFile = program.getSourceFile(file);
1681
- if (sourceFile === undefined)
1682
- return undefined;
1683
- const print = textHash(sourceFile);
1684
- readPrints[file] = print;
2197
+ readsOf: (file, mentioned) => {
2198
+ const ids = new Set();
2199
+ for (const [id, readFile] of reads.get(file) ?? []) {
2200
+ ids.add(mentioned(readFile) ? fileId(readFile) : id);
2201
+ }
2202
+ return [...ids].sort();
2203
+ },
2204
+ readFingerprint: (read) => {
2205
+ if (prints.has(read))
2206
+ return prints.get(read);
2207
+ const at = read.indexOf("#");
2208
+ const sourceFile = at < 0
2209
+ ? undefined
2210
+ : program.getSourceFile(toTypeScriptPath(path.resolve(cwd, read.slice(0, at))));
2211
+ const node = sourceFile === undefined ? undefined : declarationAtPath(sourceFile, read.slice(at + 1));
2212
+ const print = sourceFile === undefined || node === undefined
2213
+ ? undefined
2214
+ : declarationTextHash(sourceFile, node);
2215
+ prints.set(read, print);
2216
+ if (print !== undefined)
2217
+ readPrints[read] = print;
1685
2218
  return print;
1686
2219
  },
1687
2220
  syntaxError: (file) => firstSyntaxError(program, file),
1688
2221
  unresolvedImports: (file) => unresolvedImportsOf(program, file),
2222
+ strictNullChecks: checksNulls(parsed.options),
2223
+ typesResolve: typesResolver(tsconfigPath, parsed.options),
1689
2224
  bind: () => {
1690
2225
  program.getTypeChecker();
1691
2226
  },
@@ -1705,9 +2240,9 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1705
2240
  * now: its files and fingerprints come from the record, and the program is built only if
1706
2241
  * something asks for a node or a type.
1707
2242
  */
1708
- const recordedUnit = (project, claimed, record) => {
2243
+ const recordedUnit = (project, claimed, record, overlays) => {
1709
2244
  let built;
1710
- const real = () => (built ??= buildUnit(project, claimed, new Map(), false));
2245
+ const real = () => (built ??= buildUnit(project, claimed, overlays, false));
1711
2246
  return {
1712
2247
  tsconfig: project.tsconfigPath,
1713
2248
  files: record.files,
@@ -1718,11 +2253,13 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1718
2253
  },
1719
2254
  fingerprint: (file) => record.fingerprints[file],
1720
2255
  typesFor: (file) => real().typesFor(file),
1721
- readsOf: (file) => (built === undefined ? [] : built.readsOf(file)),
2256
+ readsOf: (file, mentioned) => (built === undefined ? [] : built.readsOf(file, mentioned)),
1722
2257
  // The program is the recorded one: a text hash it recorded is the answer.
1723
2258
  readFingerprint: (file) => record.reads[file] ?? real().readFingerprint(file),
1724
2259
  syntaxError: (file) => real().syntaxError(file),
1725
2260
  unresolvedImports: (file) => real().unresolvedImports(file),
2261
+ strictNullChecks: checksNulls(project.parsed.options),
2262
+ typesResolve: typesResolver(project.tsconfigPath, project.parsed.options),
1726
2263
  bind: () => {
1727
2264
  real().bind();
1728
2265
  },
@@ -1738,13 +2275,12 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1738
2275
  const record = cache?.programs.get(project.tsconfigPath);
1739
2276
  const replayable = record !== undefined &&
1740
2277
  !previous.has(project.tsconfigPath) &&
1741
- normalized.size === 0 &&
1742
2278
  !trustCache &&
1743
2279
  record.inputs ===
1744
2280
  recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
1745
- replays(record.queries, ts.createCompilerHost(project.parsed.options, false));
2281
+ replays(record.queries, replayHost(project.parsed.options, normalized));
1746
2282
  return replayable
1747
- ? recordedUnit(project, claimed, record)
2283
+ ? recordedUnit(project, claimed, record, normalized)
1748
2284
  : buildUnit(project, claimed, normalized, trustCache);
1749
2285
  });
1750
2286
  };