typescript 4.6.0-dev.20220210 → 4.7.0-dev.20220216

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.
package/lib/typescript.js CHANGED
@@ -290,11 +290,11 @@ var ts;
290
290
  (function (ts) {
291
291
  // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
292
292
  // If changing the text in this section, be sure to test `configurePrerelease` too.
293
- ts.versionMajorMinor = "4.6";
293
+ ts.versionMajorMinor = "4.7";
294
294
  // The following is baselined as a literal template type without intervention
295
295
  /** The version of the TypeScript compiler release */
296
296
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
297
- ts.version = ts.versionMajorMinor + ".0-dev.20220210";
297
+ ts.version = ts.versionMajorMinor + ".0-dev.20220216";
298
298
  /* @internal */
299
299
  var Comparison;
300
300
  (function (Comparison) {
@@ -5034,6 +5034,8 @@ var ts;
5034
5034
  TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
5035
5035
  TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
5036
5036
  /* @internal */
5037
+ TypeFlags[TypeFlags["DefinitelyNonNullable"] = 470302716] = "DefinitelyNonNullable";
5038
+ /* @internal */
5037
5039
  TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains";
5038
5040
  TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
5039
5041
  TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
@@ -5766,6 +5768,8 @@ var ts;
5766
5768
  BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
5767
5769
  BundleFileSectionKind["Reference"] = "reference";
5768
5770
  BundleFileSectionKind["Type"] = "type";
5771
+ BundleFileSectionKind["TypeResolutionModeRequire"] = "type-require";
5772
+ BundleFileSectionKind["TypeResolutionModeImport"] = "type-import";
5769
5773
  BundleFileSectionKind["Lib"] = "lib";
5770
5774
  BundleFileSectionKind["Prepend"] = "prepend";
5771
5775
  BundleFileSectionKind["Text"] = "text";
@@ -5882,7 +5886,8 @@ var ts;
5882
5886
  { name: "types", optional: true, captureSpan: true },
5883
5887
  { name: "lib", optional: true, captureSpan: true },
5884
5888
  { name: "path", optional: true, captureSpan: true },
5885
- { name: "no-default-lib", optional: true }
5889
+ { name: "no-default-lib", optional: true },
5890
+ { name: "resolution-mode", optional: true }
5886
5891
  ],
5887
5892
  kind: 1 /* TripleSlashXML */
5888
5893
  },
@@ -7830,18 +7835,6 @@ var ts;
7830
7835
  return getCanonicalFileName(nonCanonicalizedPath);
7831
7836
  }
7832
7837
  ts.toPath = toPath;
7833
- function normalizePathAndParts(path) {
7834
- path = normalizeSlashes(path);
7835
- var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
7836
- if (parts.length) {
7837
- var joinedParts = root + parts.join(ts.directorySeparator);
7838
- return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
7839
- }
7840
- else {
7841
- return { path: root, parts: parts };
7842
- }
7843
- }
7844
- ts.normalizePathAndParts = normalizePathAndParts;
7845
7838
  function removeTrailingDirectorySeparator(path) {
7846
7839
  if (hasTrailingDirectorySeparator(path)) {
7847
7840
  return path.substr(0, path.length - 1);
@@ -8274,6 +8267,9 @@ var ts;
8274
8267
  An_optional_element_cannot_follow_a_rest_element: diag(1266, ts.DiagnosticCategory.Error, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."),
8275
8268
  Property_0_cannot_have_an_initializer_because_it_is_marked_abstract: diag(1267, ts.DiagnosticCategory.Error, "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267", "Property '{0}' cannot have an initializer because it is marked abstract."),
8276
8269
  An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type: diag(1268, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268", "An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type."),
8270
+ Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided: diag(1269, ts.DiagnosticCategory.Error, "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided_1269", "Cannot use 'export import' on a type or type-only namespace when the '--isolatedModules' flag is provided."),
8271
+ Decorator_function_return_type_0_is_not_assignable_to_type_1: diag(1270, ts.DiagnosticCategory.Error, "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270", "Decorator function return type '{0}' is not assignable to type '{1}'."),
8272
+ Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any: diag(1271, ts.DiagnosticCategory.Error, "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271", "Decorator function return type is '{0}' but is expected to be 'void' or 'any'."),
8277
8273
  with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."),
8278
8274
  await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."),
8279
8275
  Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."),
@@ -8407,6 +8403,8 @@ var ts;
8407
8403
  Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed: diag(1449, ts.DiagnosticCategory.Message, "Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed_1449", "Preserve unused imported values in the JavaScript output that would otherwise be removed."),
8408
8404
  Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments: diag(1450, ts.DiagnosticCategory.Message, "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450", "Dynamic imports can only accept a module specifier and an optional assertion as arguments"),
8409
8405
  Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"),
8406
+ Resolution_modes_are_only_supported_when_moduleResolution_is_node12_or_nodenext: diag(1452, ts.DiagnosticCategory.Error, "Resolution_modes_are_only_supported_when_moduleResolution_is_node12_or_nodenext_1452", "Resolution modes are only supported when `moduleResolution` is `node12` or `nodenext`."),
8407
+ resolution_mode_should_be_either_require_or_import: diag(1453, ts.DiagnosticCategory.Error, "resolution_mode_should_be_either_require_or_import_1453", "`resolution-mode` should be either `require` or `import`."),
8410
8408
  The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."),
8411
8409
  Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."),
8412
8410
  catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."),
@@ -9832,6 +9830,9 @@ var ts;
9832
9830
  Add_all_missing_attributes: diag(95168, ts.DiagnosticCategory.Message, "Add_all_missing_attributes_95168", "Add all missing attributes"),
9833
9831
  Add_undefined_to_optional_property_type: diag(95169, ts.DiagnosticCategory.Message, "Add_undefined_to_optional_property_type_95169", "Add 'undefined' to optional property type"),
9834
9832
  Convert_named_imports_to_default_import: diag(95170, ts.DiagnosticCategory.Message, "Convert_named_imports_to_default_import_95170", "Convert named imports to default import"),
9833
+ Delete_unused_param_tag_0: diag(95171, ts.DiagnosticCategory.Message, "Delete_unused_param_tag_0_95171", "Delete unused '@param' tag '{0}'"),
9834
+ Delete_all_unused_param_tags: diag(95172, ts.DiagnosticCategory.Message, "Delete_all_unused_param_tags_95172", "Delete all unused '@param' tags"),
9835
+ Rename_param_tag_name_0_to_1: diag(95173, ts.DiagnosticCategory.Message, "Rename_param_tag_name_0_to_1_95173", "Rename '@param' tag name '{0}' to '{1}'"),
9835
9836
  No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."),
9836
9837
  Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."),
9837
9838
  JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"),
@@ -14287,7 +14288,11 @@ var ts;
14287
14288
  ts.Debug.assert(names.length === newResolutions.length);
14288
14289
  for (var i = 0; i < names.length; i++) {
14289
14290
  var newResolution = newResolutions[i];
14290
- var oldResolution = oldResolutions && oldResolutions.get(names[i], oldSourceFile && ts.getModeForResolutionAtIndex(oldSourceFile, i));
14291
+ var entry = names[i];
14292
+ // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
14293
+ var name = !ts.isString(entry) ? entry.fileName.toLowerCase() : entry;
14294
+ var mode = !ts.isString(entry) ? ts.getModeForFileReference(entry, oldSourceFile === null || oldSourceFile === void 0 ? void 0 : oldSourceFile.impliedNodeFormat) : oldSourceFile && ts.getModeForResolutionAtIndex(oldSourceFile, i);
14295
+ var oldResolution = oldResolutions && oldResolutions.get(name, mode);
14291
14296
  var changed = oldResolution
14292
14297
  ? !newResolution || !comparer(oldResolution, newResolution)
14293
14298
  : newResolution;
@@ -26882,7 +26887,13 @@ var ts;
26882
26887
  referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
26883
26888
  break;
26884
26889
  case "type" /* Type */:
26885
- typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
26890
+ typeReferenceDirectives = ts.append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
26891
+ break;
26892
+ case "type-import" /* TypeResolutionModeImport */:
26893
+ typeReferenceDirectives = ts.append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: ts.ModuleKind.ESNext });
26894
+ break;
26895
+ case "type-require" /* TypeResolutionModeRequire */:
26896
+ typeReferenceDirectives = ts.append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: ts.ModuleKind.CommonJS });
26886
26897
  break;
26887
26898
  case "lib" /* Lib */:
26888
26899
  libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
@@ -26941,6 +26952,8 @@ var ts;
26941
26952
  case "no-default-lib" /* NoDefaultLib */:
26942
26953
  case "reference" /* Reference */:
26943
26954
  case "type" /* Type */:
26955
+ case "type-import" /* TypeResolutionModeImport */:
26956
+ case "type-require" /* TypeResolutionModeRequire */:
26944
26957
  case "lib" /* Lib */:
26945
26958
  syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
26946
26959
  break;
@@ -30854,7 +30867,7 @@ var ts;
30854
30867
  initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
30855
30868
  // Prime the scanner.
30856
30869
  nextToken();
30857
- var entityName = parseEntityName(/*allowReservedWords*/ true);
30870
+ var entityName = parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ false);
30858
30871
  var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
30859
30872
  clearState();
30860
30873
  return isInvalid ? entityName : undefined;
@@ -32431,7 +32444,7 @@ var ts;
32431
32444
  }
32432
32445
  return createMissingList();
32433
32446
  }
32434
- function parseEntityName(allowReservedWords, diagnosticMessage) {
32447
+ function parseEntityName(allowReservedWords, allowPrivateIdentifiers, diagnosticMessage) {
32435
32448
  var pos = getNodePos();
32436
32449
  var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
32437
32450
  var dotPos = getNodePos();
@@ -32442,7 +32455,7 @@ var ts;
32442
32455
  break;
32443
32456
  }
32444
32457
  dotPos = getNodePos();
32445
- entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
32458
+ entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, allowPrivateIdentifiers)), pos);
32446
32459
  }
32447
32460
  return entity;
32448
32461
  }
@@ -32575,7 +32588,7 @@ var ts;
32575
32588
  }
32576
32589
  // TYPES
32577
32590
  function parseEntityNameOfTypeReference() {
32578
- return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
32591
+ return parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ false, ts.Diagnostics.Type_expected);
32579
32592
  }
32580
32593
  function parseTypeArgumentsOfTypeReference() {
32581
32594
  if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
@@ -32708,7 +32721,7 @@ var ts;
32708
32721
  function parseTypeQuery() {
32709
32722
  var pos = getNodePos();
32710
32723
  parseExpected(112 /* TypeOfKeyword */);
32711
- return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
32724
+ return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ true)), pos);
32712
32725
  }
32713
32726
  function parseTypeParameter() {
32714
32727
  var pos = getNodePos();
@@ -35279,11 +35292,12 @@ var ts;
35279
35292
  }
35280
35293
  function parseCaseClause() {
35281
35294
  var pos = getNodePos();
35295
+ var hasJSDoc = hasPrecedingJSDocComment();
35282
35296
  parseExpected(82 /* CaseKeyword */);
35283
35297
  var expression = allowInAnd(parseExpression);
35284
35298
  parseExpected(58 /* ColonToken */);
35285
35299
  var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
35286
- return finishNode(factory.createCaseClause(expression, statements), pos);
35300
+ return withJSDoc(finishNode(factory.createCaseClause(expression, statements), pos), hasJSDoc);
35287
35301
  }
35288
35302
  function parseDefaultClause() {
35289
35303
  var pos = getNodePos();
@@ -36446,7 +36460,7 @@ var ts;
36446
36460
  function parseModuleReference() {
36447
36461
  return isExternalModuleReference()
36448
36462
  ? parseExternalModuleReference()
36449
- : parseEntityName(/*allowReservedWords*/ false);
36463
+ : parseEntityName(/*allowReservedWords*/ false, /*allowPrivateIdentifiers*/ false);
36450
36464
  }
36451
36465
  function parseExternalModuleReference() {
36452
36466
  var pos = getNodePos();
@@ -36728,7 +36742,7 @@ var ts;
36728
36742
  var pos = getNodePos();
36729
36743
  var hasBrace = parseOptional(18 /* OpenBraceToken */);
36730
36744
  var p2 = getNodePos();
36731
- var entityName = parseEntityName(/* allowReservedWords*/ false);
36745
+ var entityName = parseEntityName(/* allowReservedWords*/ false, /*allowPrivateIdentifiers*/ false);
36732
36746
  while (token() === 80 /* PrivateIdentifier */) {
36733
36747
  reScanHashToken(); // rescan #id as # id
36734
36748
  nextTokenJSDoc(); // then skip the #
@@ -37171,7 +37185,7 @@ var ts;
37171
37185
  // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error
37172
37186
  var p2 = getNodePos();
37173
37187
  var name = ts.tokenIsIdentifierOrKeyword(token())
37174
- ? parseEntityName(/*allowReservedWords*/ true)
37188
+ ? parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ false)
37175
37189
  : undefined;
37176
37190
  if (name) {
37177
37191
  while (token() === 80 /* PrivateIdentifier */) {
@@ -37196,11 +37210,13 @@ var ts;
37196
37210
  && nextTokenJSDoc() === 59 /* AtToken */
37197
37211
  && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc())) {
37198
37212
  var kind = scanner.getTokenValue();
37199
- if (kind === "link" || kind === "linkcode" || kind === "linkplain") {
37213
+ if (isJSDocLinkTag(kind))
37200
37214
  return kind;
37201
- }
37202
37215
  }
37203
37216
  }
37217
+ function isJSDocLinkTag(kind) {
37218
+ return kind === "link" || kind === "linkcode" || kind === "linkplain";
37219
+ }
37204
37220
  function parseUnknownTag(start, tagName, indent, indentText) {
37205
37221
  return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
37206
37222
  }
@@ -37306,7 +37322,7 @@ var ts;
37306
37322
  }
37307
37323
  function parseSeeTag(start, tagName, indent, indentText) {
37308
37324
  var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */
37309
- || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; });
37325
+ || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner.getTokenValue()); });
37310
37326
  var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference();
37311
37327
  var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined;
37312
37328
  return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start);
@@ -38173,6 +38189,19 @@ var ts;
38173
38189
  return ts.fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */]);
38174
38190
  }
38175
38191
  ts.isDeclarationFileName = isDeclarationFileName;
38192
+ function parseResolutionMode(mode, pos, end, reportDiagnostic) {
38193
+ if (!mode) {
38194
+ return undefined;
38195
+ }
38196
+ if (mode === "import") {
38197
+ return ts.ModuleKind.ESNext;
38198
+ }
38199
+ if (mode === "require") {
38200
+ return ts.ModuleKind.CommonJS;
38201
+ }
38202
+ reportDiagnostic(pos, end - pos, ts.Diagnostics.resolution_mode_should_be_either_require_or_import);
38203
+ return undefined;
38204
+ }
38176
38205
  /*@internal*/
38177
38206
  function processCommentPragmas(context, sourceText) {
38178
38207
  var pragmas = [];
@@ -38215,12 +38244,13 @@ var ts;
38215
38244
  var typeReferenceDirectives_1 = context.typeReferenceDirectives;
38216
38245
  var libReferenceDirectives_1 = context.libReferenceDirectives;
38217
38246
  ts.forEach(ts.toArray(entryOrList), function (arg) {
38218
- var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
38247
+ var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path, res = _a["resolution-mode"];
38219
38248
  if (arg.arguments["no-default-lib"]) {
38220
38249
  context.hasNoDefaultLib = true;
38221
38250
  }
38222
38251
  else if (types) {
38223
- typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
38252
+ var parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic);
38253
+ typeReferenceDirectives_1.push(__assign({ pos: types.pos, end: types.end, fileName: types.value }, (parsed ? { resolutionMode: parsed } : {})));
38224
38254
  }
38225
38255
  else if (lib) {
38226
38256
  libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
@@ -41798,14 +41828,14 @@ var ts;
41798
41828
  * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
41799
41829
  * is assumed to be the same as root directory of the project.
41800
41830
  */
41801
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) {
41831
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache, resolutionMode) {
41802
41832
  var traceEnabled = isTraceEnabled(options, host);
41803
41833
  if (redirectedReference) {
41804
41834
  options = redirectedReference.commandLine.options;
41805
41835
  }
41806
41836
  var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined;
41807
41837
  var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined;
41808
- var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName, /*mode*/ undefined);
41838
+ var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName, /*mode*/ resolutionMode);
41809
41839
  if (result) {
41810
41840
  if (traceEnabled) {
41811
41841
  trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile);
@@ -41840,7 +41870,18 @@ var ts;
41840
41870
  }
41841
41871
  var failedLookupLocations = [];
41842
41872
  var features = getDefaultNodeResolutionFeatures(options);
41843
- var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: features, conditions: ["node", "require", "types"] };
41873
+ // Unlike `import` statements, whose mode-calculating APIs are all guaranteed to return `undefined` if we're in an un-mode-ed module resolution
41874
+ // setting, type references will return their target mode regardless of options because of how the parser works, so we guard against the mode being
41875
+ // set in a non-modal module resolution setting here. Do note that our behavior is not particularly well defined when these mode-overriding imports
41876
+ // are present in a non-modal project; while in theory we'd like to either ignore the mode or provide faithful modern resolution, depending on what we feel is best,
41877
+ // in practice, not every cache has the options available to intelligently make the choice to ignore the mode request, and it's unclear how modern "faithful modern
41878
+ // resolution" should be (`node12`? `nodenext`?). As such, witnessing a mode-overriding triple-slash reference in a non-modal module resolution
41879
+ // context should _probably_ be an error - and that should likely be handled by the `Program` (which is what we do).
41880
+ if (resolutionMode === ts.ModuleKind.ESNext && (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext)) {
41881
+ features |= NodeResolutionFeatures.EsmMode;
41882
+ }
41883
+ var conditions = features & NodeResolutionFeatures.Exports ? features & NodeResolutionFeatures.EsmMode ? ["node", "import", "types"] : ["node", "require", "types"] : [];
41884
+ var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: features, conditions: conditions };
41844
41885
  var resolved = primaryLookup();
41845
41886
  var primary = true;
41846
41887
  if (!resolved) {
@@ -41860,7 +41901,7 @@ var ts;
41860
41901
  };
41861
41902
  }
41862
41903
  result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
41863
- perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ undefined, result);
41904
+ perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result);
41864
41905
  if (traceEnabled)
41865
41906
  traceResult(result);
41866
41907
  return result;
@@ -41911,7 +41952,7 @@ var ts;
41911
41952
  result_4 = searchResult && searchResult.value;
41912
41953
  }
41913
41954
  else {
41914
- var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
41955
+ var candidate = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName).path;
41915
41956
  result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
41916
41957
  }
41917
41958
  return resolvedTypeScriptOnly(result_4);
@@ -42146,7 +42187,11 @@ var ts;
42146
42187
  ts.Debug.assert(keys.length === values.length);
42147
42188
  var map = createModeAwareCache();
42148
42189
  for (var i = 0; i < keys.length; ++i) {
42149
- map.set(keys[i], ts.getModeForResolutionAtIndex(file, i), values[i]);
42190
+ var entry = keys[i];
42191
+ // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
42192
+ var name = !ts.isString(entry) ? entry.fileName.toLowerCase() : entry;
42193
+ var mode = !ts.isString(entry) ? entry.resolutionMode || file.impliedNodeFormat : ts.getModeForResolutionAtIndex(file, i);
42194
+ map.set(name, mode, values[i]);
42150
42195
  }
42151
42196
  return map;
42152
42197
  }
@@ -42614,13 +42659,25 @@ var ts;
42614
42659
  return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
42615
42660
  }
42616
42661
  else {
42617
- var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
42662
+ var _a = normalizePathForCJSResolution(containingDirectory, moduleName), candidate = _a.path, parts = _a.parts;
42618
42663
  var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
42619
42664
  // Treat explicit "node_modules" import as an external library import.
42620
42665
  return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
42621
42666
  }
42622
42667
  }
42623
42668
  }
42669
+ // If you import from "." inside a containing directory "/foo", the result of `normalizePath`
42670
+ // would be "/foo", but this loses the information that `foo` is a directory and we intended
42671
+ // to look inside of it. The Node CommonJS resolution algorithm doesn't call this out
42672
+ // (https://nodejs.org/api/modules.html#all-together), but it seems that module paths ending
42673
+ // in `.` are actually normalized to `./` before proceeding with the resolution algorithm.
42674
+ function normalizePathForCJSResolution(containingDirectory, moduleName) {
42675
+ var combined = ts.combinePaths(containingDirectory, moduleName);
42676
+ var parts = ts.getPathComponents(combined);
42677
+ var lastPart = ts.lastOrUndefined(parts);
42678
+ var path = lastPart === "." || lastPart === ".." ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(combined)) : ts.normalizePath(combined);
42679
+ return { path: path, parts: parts };
42680
+ }
42624
42681
  function realPath(path, host, traceEnabled) {
42625
42682
  if (!host.realpath) {
42626
42683
  return path;
@@ -42662,7 +42719,13 @@ var ts;
42662
42719
  onlyRecordFailures = true;
42663
42720
  }
42664
42721
  }
42665
- return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
42722
+ // esm mode relative imports shouldn't do any directory lookups (either inside `package.json`
42723
+ // files or implicit `index.js`es). This is a notable depature from cjs norms, where `./foo/pkg`
42724
+ // could have been redirected by `./foo/pkg/package.json` to an arbitrary location!
42725
+ if (!(state.features & NodeResolutionFeatures.EsmMode)) {
42726
+ return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
42727
+ }
42728
+ return undefined;
42666
42729
  }
42667
42730
  /*@internal*/
42668
42731
  ts.nodeModulesPathPart = "/node_modules/";
@@ -43029,7 +43092,16 @@ var ts;
43029
43092
  // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
43030
43093
  var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
43031
43094
  // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
43032
- return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
43095
+ // Disable `EsmMode` for the resolution of the package path for cjs-mode packages (so the `main` field can omit extensions)
43096
+ // (technically it only emits a deprecation warning in esm packages right now, but that's probably
43097
+ // enough to mean we don't need to support it)
43098
+ var features = state.features;
43099
+ if ((jsonContent === null || jsonContent === void 0 ? void 0 : jsonContent.type) !== "module") {
43100
+ state.features &= ~NodeResolutionFeatures.EsmMode;
43101
+ }
43102
+ var result = nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
43103
+ state.features = features;
43104
+ return result;
43033
43105
  };
43034
43106
  var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
43035
43107
  var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
@@ -43374,6 +43446,14 @@ var ts;
43374
43446
  }
43375
43447
  var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
43376
43448
  loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
43449
+ if (!pathAndExtension && packageInfo
43450
+ && packageInfo.packageJsonContent.exports === undefined
43451
+ && packageInfo.packageJsonContent.main === undefined
43452
+ && state.features & NodeResolutionFeatures.EsmMode) {
43453
+ // EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume
43454
+ // a default `index.js` entrypoint if no `main` or `exports` are present
43455
+ pathAndExtension = loadModuleFromFile(extensions, ts.combinePaths(candidate, "index.js"), onlyRecordFailures, state);
43456
+ }
43377
43457
  return withPackageId(packageInfo, pathAndExtension);
43378
43458
  };
43379
43459
  if (rest !== "") { // If "rest" is empty, we just did this search above.
@@ -47131,8 +47211,7 @@ var ts;
47131
47211
  IntersectionState[IntersectionState["Source"] = 1] = "Source";
47132
47212
  IntersectionState[IntersectionState["Target"] = 2] = "Target";
47133
47213
  IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
47134
- IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck";
47135
- IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck";
47214
+ IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
47136
47215
  })(IntersectionState || (IntersectionState = {}));
47137
47216
  var RecursionFlags;
47138
47217
  (function (RecursionFlags) {
@@ -50591,8 +50670,15 @@ var ts;
50591
50670
  return res;
50592
50671
  }
50593
50672
  var candidates = ts.mapDefined(symbol.declarations, function (d) {
50594
- if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
50595
- return getSymbolOfNode(d.parent);
50673
+ if (!ts.isAmbientModule(d) && d.parent) {
50674
+ // direct children of a module
50675
+ if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
50676
+ return getSymbolOfNode(d.parent);
50677
+ }
50678
+ // export ='d member of an ambient module
50679
+ if (ts.isModuleBlock(d.parent) && d.parent.parent && resolveExternalModuleSymbol(getSymbolOfNode(d.parent.parent)) === symbol) {
50680
+ return getSymbolOfNode(d.parent.parent);
50681
+ }
50596
50682
  }
50597
50683
  if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 63 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
50598
50684
  if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
@@ -54829,12 +54915,9 @@ var ts;
54829
54915
  }
54830
54916
  }
54831
54917
  if (ts.isInJSFile(declaration)) {
54832
- var typeTag = ts.getJSDocType(func);
54833
- if (typeTag && ts.isFunctionTypeNode(typeTag)) {
54834
- var signature = getSignatureFromDeclaration(typeTag);
54835
- var pos = func.parameters.indexOf(declaration);
54836
- return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
54837
- }
54918
+ var type_1 = getParameterTypeOfTypeTag(func, declaration);
54919
+ if (type_1)
54920
+ return type_1;
54838
54921
  }
54839
54922
  // Use contextual parameter type if one is available
54840
54923
  var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
@@ -55401,9 +55484,9 @@ var ts;
55401
55484
  if (typeNode === undefined) {
55402
55485
  return useUnknownInCatchVariables ? unknownType : anyType;
55403
55486
  }
55404
- var type_1 = getTypeOfNode(typeNode);
55487
+ var type_2 = getTypeOfNode(typeNode);
55405
55488
  // an errorType will make `checkTryStatement` issue an error
55406
- return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType;
55489
+ return isTypeAny(type_2) || type_2 === unknownType ? type_2 : errorType;
55407
55490
  }
55408
55491
  // Handle export default expressions
55409
55492
  if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
@@ -55632,11 +55715,11 @@ var ts;
55632
55715
  return errorType;
55633
55716
  }
55634
55717
  var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
55635
- var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
55718
+ var type_3 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
55636
55719
  if (!popTypeResolution()) {
55637
55720
  return reportCircularityError(symbol);
55638
55721
  }
55639
- return type_2;
55722
+ return type_3;
55640
55723
  }
55641
55724
  }
55642
55725
  var type = createObjectType(16 /* Anonymous */, symbol);
@@ -57868,10 +57951,10 @@ var ts;
57868
57951
  var baseTypes = [];
57869
57952
  var different = false;
57870
57953
  for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
57871
- var type_3 = types_7[_i];
57872
- var baseType = getBaseConstraint(type_3);
57954
+ var type_4 = types_7[_i];
57955
+ var baseType = getBaseConstraint(type_4);
57873
57956
  if (baseType) {
57874
- if (baseType !== type_3) {
57957
+ if (baseType !== type_4) {
57875
57958
  different = true;
57876
57959
  }
57877
57960
  baseTypes.push(baseType);
@@ -58584,6 +58667,13 @@ var ts;
58584
58667
  var typeTag = ts.getJSDocTypeTag(node);
58585
58668
  return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
58586
58669
  }
58670
+ function getParameterTypeOfTypeTag(func, parameter) {
58671
+ var signature = getSignatureOfTypeTag(func);
58672
+ if (!signature)
58673
+ return undefined;
58674
+ var pos = func.parameters.indexOf(parameter);
58675
+ return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
58676
+ }
58587
58677
  function getReturnTypeOfTypeTag(node) {
58588
58678
  var signature = getSignatureOfTypeTag(node);
58589
58679
  return signature && getReturnTypeOfSignature(signature);
@@ -58842,13 +58932,15 @@ var ts;
58842
58932
  return signature;
58843
58933
  }
58844
58934
  function getOrCreateTypeFromSignature(signature) {
58935
+ var _a;
58845
58936
  // There are two ways to declare a construct signature, one is by declaring a class constructor
58846
58937
  // using the constructor keyword, and the other is declaring a bare construct signature in an
58847
58938
  // object type literal or interface (using the new keyword). Each way of declaring a constructor
58848
58939
  // will result in a different declaration kind.
58849
58940
  if (!signature.isolatedSignatureType) {
58850
- var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
58851
- var isConstructor = kind === 170 /* Constructor */ || kind === 174 /* ConstructSignature */ || kind === 179 /* ConstructorType */;
58941
+ var kind = (_a = signature.declaration) === null || _a === void 0 ? void 0 : _a.kind;
58942
+ // If declaration is undefined, it is likely to be the signature of the default constructor.
58943
+ var isConstructor = kind === undefined || kind === 170 /* Constructor */ || kind === 174 /* ConstructSignature */ || kind === 179 /* ConstructorType */;
58852
58944
  var type = createObjectType(16 /* Anonymous */);
58853
58945
  type.members = emptySymbols;
58854
58946
  type.properties = ts.emptyArray;
@@ -59776,7 +59868,7 @@ var ts;
59776
59868
  }
59777
59869
  }
59778
59870
  var fixedLength = properties.length;
59779
- var lengthSymbol = createSymbol(4 /* Property */, "length");
59871
+ var lengthSymbol = createSymbol(4 /* Property */, "length", readonly ? 8 /* Readonly */ : 0);
59780
59872
  if (combinedFlags & 12 /* Variable */) {
59781
59873
  lengthSymbol.type = numberType;
59782
59874
  }
@@ -63323,9 +63415,11 @@ var ts;
63323
63415
  isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
63324
63416
  return true;
63325
63417
  }
63326
- if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
63418
+ // In non-strictNullChecks mode, `undefined` and `null` are assignable to anything except `never`.
63419
+ // Since unions and intersections may reduce to `never`, we exclude them here.
63420
+ if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */)))
63327
63421
  return true;
63328
- if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
63422
+ if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */))
63329
63423
  return true;
63330
63424
  if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
63331
63425
  return true;
@@ -63414,11 +63508,11 @@ var ts;
63414
63508
  var overflow = false;
63415
63509
  var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
63416
63510
  var lastSkippedInfo;
63417
- var incompatibleStack = [];
63511
+ var incompatibleStack;
63418
63512
  var inPropertyCheck = false;
63419
63513
  ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
63420
63514
  var result = isRelatedTo(source, target, 3 /* Both */, /*reportErrors*/ !!errorNode, headMessage);
63421
- if (incompatibleStack.length) {
63515
+ if (incompatibleStack) {
63422
63516
  reportIncompatibleStack();
63423
63517
  }
63424
63518
  if (overflow) {
@@ -63475,19 +63569,19 @@ var ts;
63475
63569
  return {
63476
63570
  errorInfo: errorInfo,
63477
63571
  lastSkippedInfo: lastSkippedInfo,
63478
- incompatibleStack: incompatibleStack.slice(),
63572
+ incompatibleStack: incompatibleStack === null || incompatibleStack === void 0 ? void 0 : incompatibleStack.slice(),
63479
63573
  overrideNextErrorInfo: overrideNextErrorInfo,
63480
- relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
63574
+ relatedInfo: relatedInfo === null || relatedInfo === void 0 ? void 0 : relatedInfo.slice(),
63481
63575
  };
63482
63576
  }
63483
63577
  function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
63484
63578
  overrideNextErrorInfo++; // Suppress the next relation error
63485
63579
  lastSkippedInfo = undefined; // Reset skipped info cache
63486
- incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
63580
+ (incompatibleStack || (incompatibleStack = [])).push([message, arg0, arg1, arg2, arg3]);
63487
63581
  }
63488
63582
  function reportIncompatibleStack() {
63489
- var stack = incompatibleStack;
63490
- incompatibleStack = [];
63583
+ var stack = incompatibleStack || [];
63584
+ incompatibleStack = undefined;
63491
63585
  var info = lastSkippedInfo;
63492
63586
  lastSkippedInfo = undefined;
63493
63587
  if (stack.length === 1) {
@@ -63593,7 +63687,7 @@ var ts;
63593
63687
  }
63594
63688
  function reportError(message, arg0, arg1, arg2, arg3) {
63595
63689
  ts.Debug.assert(!!errorNode);
63596
- if (incompatibleStack.length)
63690
+ if (incompatibleStack)
63597
63691
  reportIncompatibleStack();
63598
63692
  if (message.elidedInCompatabilityPyramid)
63599
63693
  return;
@@ -63609,7 +63703,7 @@ var ts;
63609
63703
  }
63610
63704
  }
63611
63705
  function reportRelationError(message, source, target) {
63612
- if (incompatibleStack.length)
63706
+ if (incompatibleStack)
63613
63707
  reportIncompatibleStack();
63614
63708
  var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
63615
63709
  var generalizedSource = source;
@@ -63721,7 +63815,9 @@ var ts;
63721
63815
  if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
63722
63816
  return -1 /* True */;
63723
63817
  }
63724
- reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */));
63818
+ if (reportErrors) {
63819
+ reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage);
63820
+ }
63725
63821
  return 0 /* False */;
63726
63822
  }
63727
63823
  // Normalize the source and target types: Turn fresh literal types into regular literal types,
@@ -63733,7 +63829,12 @@ var ts;
63733
63829
  if (source === target)
63734
63830
  return -1 /* True */;
63735
63831
  if (relation === identityRelation) {
63736
- return isIdenticalTo(source, target, recursionFlags);
63832
+ if (source.flags !== target.flags)
63833
+ return 0 /* False */;
63834
+ if (source.flags & 67358815 /* Singleton */)
63835
+ return -1 /* True */;
63836
+ traceUnionsOrIntersectionsTooLarge(source, target);
63837
+ return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags);
63737
63838
  }
63738
63839
  // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
63739
63840
  // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
@@ -63743,163 +63844,130 @@ var ts;
63743
63844
  if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
63744
63845
  return -1 /* True */;
63745
63846
  }
63746
- // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
63747
- // If so, reporting the `null` and `undefined` in the type is hardly useful.
63748
- // First, see if we're even relating an object type to a union.
63749
- // Then see if the target is stripped down to a single non-union type.
63750
- // Note
63751
- // * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
63752
- // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
63753
- // when dealing with generics.
63754
- // * We also don't deal with primitive source types, since we already halt elaboration below.
63755
- if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
63756
- target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
63757
- var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
63758
- if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
63759
- target = getNormalizedType(nullStrippedTarget, /*writing*/ true);
63760
- }
63761
- if (source === nullStrippedTarget)
63762
- return -1 /* True */;
63847
+ // See if we're relating a definitely non-nullable type to a union that includes null and/or undefined
63848
+ // plus a single non-nullable type. If so, remove null and/or undefined from the target type.
63849
+ if (source.flags & 470302716 /* DefinitelyNonNullable */ && target.flags & 1048576 /* Union */) {
63850
+ var types = target.types;
63851
+ var candidate = types.length === 2 && types[0].flags & 98304 /* Nullable */ ? types[1] :
63852
+ types.length === 3 && types[0].flags & 98304 /* Nullable */ && types[1].flags & 98304 /* Nullable */ ? types[2] :
63853
+ undefined;
63854
+ if (candidate && !(candidate.flags & 98304 /* Nullable */)) {
63855
+ target = getNormalizedType(candidate, /*writing*/ true);
63856
+ if (source === target)
63857
+ return -1 /* True */;
63858
+ }
63763
63859
  }
63764
63860
  if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
63765
63861
  isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
63766
63862
  return -1 /* True */;
63767
- var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */);
63768
- var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */);
63769
- if (isPerformingExcessPropertyChecks) {
63770
- if (hasExcessProperties(source, target, reportErrors)) {
63863
+ if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) {
63864
+ var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */);
63865
+ if (isPerformingExcessPropertyChecks) {
63866
+ if (hasExcessProperties(source, target, reportErrors)) {
63867
+ if (reportErrors) {
63868
+ reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target);
63869
+ }
63870
+ return 0 /* False */;
63871
+ }
63872
+ }
63873
+ var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
63874
+ source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
63875
+ target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
63876
+ (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
63877
+ var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */);
63878
+ if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
63771
63879
  if (reportErrors) {
63772
- reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target);
63880
+ var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source);
63881
+ var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target);
63882
+ var calls = getSignaturesOfType(source, 0 /* Call */);
63883
+ var constructs = getSignaturesOfType(source, 1 /* Construct */);
63884
+ if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) ||
63885
+ constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) {
63886
+ reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString);
63887
+ }
63888
+ else {
63889
+ reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString);
63890
+ }
63773
63891
  }
63774
63892
  return 0 /* False */;
63775
63893
  }
63776
- }
63777
- var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
63778
- source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
63779
- target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
63780
- (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
63781
- if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
63782
- if (reportErrors) {
63783
- var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source);
63784
- var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target);
63785
- var calls = getSignaturesOfType(source, 0 /* Call */);
63786
- var constructs = getSignaturesOfType(source, 1 /* Construct */);
63787
- if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) ||
63788
- constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) {
63789
- reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString);
63790
- }
63791
- else {
63792
- reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString);
63793
- }
63894
+ traceUnionsOrIntersectionsTooLarge(source, target);
63895
+ var skipCaching = source.flags & 1048576 /* Union */ && source.types.length < 4 && !(target.flags & 1048576 /* Union */) ||
63896
+ target.flags & 1048576 /* Union */ && target.types.length < 4 && !(source.flags & 469499904 /* StructuredOrInstantiable */);
63897
+ var result_7 = skipCaching ?
63898
+ unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) :
63899
+ recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags);
63900
+ // For certain combinations involving intersections and optional, excess, or mismatched properties we need
63901
+ // an extra property check where the intersection is viewed as a single object. The following are motivating
63902
+ // examples that all should be errors, but aren't without this extra property check:
63903
+ //
63904
+ // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property
63905
+ //
63906
+ // declare let wrong: { a: { y: string } };
63907
+ // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type
63908
+ //
63909
+ // function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
63910
+ // x = y; // Mismatched property in source intersection
63911
+ // }
63912
+ //
63913
+ // We suppress recursive intersection property checks because they can generate lots of work when relating
63914
+ // recursive intersections that are structurally similar but not exactly identical. See #37854.
63915
+ if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
63916
+ isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) {
63917
+ inPropertyCheck = true;
63918
+ result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags);
63919
+ inPropertyCheck = false;
63920
+ }
63921
+ if (result_7) {
63922
+ return result_7;
63794
63923
  }
63795
- return 0 /* False */;
63796
- }
63797
- traceUnionsOrIntersectionsTooLarge(source, target);
63798
- var result = 0 /* False */;
63799
- var saveErrorInfo = captureErrorCalculationState();
63800
- if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) {
63801
- // We skip caching when source or target is a union with no more than three constituents.
63802
- result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */);
63803
63924
  }
63804
- else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) {
63805
- result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags);
63925
+ if (reportErrors) {
63926
+ reportErrorResults(originalSource, originalTarget, source, target, headMessage);
63806
63927
  }
63807
- if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) {
63808
- if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) {
63809
- resetErrorInfo(saveErrorInfo);
63928
+ return 0 /* False */;
63929
+ }
63930
+ function reportErrorResults(originalSource, originalTarget, source, target, headMessage) {
63931
+ var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource);
63932
+ var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget);
63933
+ source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source;
63934
+ target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target;
63935
+ var maybeSuppress = overrideNextErrorInfo > 0;
63936
+ if (maybeSuppress) {
63937
+ overrideNextErrorInfo--;
63938
+ }
63939
+ if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
63940
+ var currentError = errorInfo;
63941
+ tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ true);
63942
+ if (errorInfo !== currentError) {
63943
+ maybeSuppress = !!errorInfo;
63944
+ }
63945
+ }
63946
+ if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
63947
+ tryElaborateErrorsForPrimitivesAndObjects(source, target);
63948
+ }
63949
+ else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
63950
+ reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
63951
+ }
63952
+ else if (ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && target.flags & 2097152 /* Intersection */) {
63953
+ var targetTypes = target.types;
63954
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
63955
+ var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
63956
+ if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) &&
63957
+ (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
63958
+ // do not report top error
63959
+ return;
63810
63960
  }
63811
63961
  }
63812
- if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
63813
- // The combined constraint of an intersection type is the intersection of the constraints of
63814
- // the constituents. When an intersection type contains instantiable types with union type
63815
- // constraints, there are situations where we need to examine the combined constraint. One is
63816
- // when the target is a union type. Another is when the intersection contains types belonging
63817
- // to one of the disjoint domains. For example, given type variables T and U, each with the
63818
- // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
63819
- // we need to check this constraint against a union on the target side. Also, given a type
63820
- // variable V constrained to 'string | number', 'V & number' has a combined constraint of
63821
- // 'string & number | number & number' which reduces to just 'number'.
63822
- // This also handles type parameters, as a type parameter with a union constraint compared against a union
63823
- // needs to have its constraint hoisted into an intersection with said type parameter, this way
63824
- // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
63825
- // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
63826
- var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
63827
- if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
63828
- if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
63829
- // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
63830
- if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
63831
- resetErrorInfo(saveErrorInfo);
63832
- }
63833
- }
63834
- }
63962
+ else {
63963
+ errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
63835
63964
  }
63836
- // For certain combinations involving intersections and optional, excess, or mismatched properties we need
63837
- // an extra property check where the intersection is viewed as a single object. The following are motivating
63838
- // examples that all should be errors, but aren't without this extra property check:
63839
- //
63840
- // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property
63841
- //
63842
- // declare let wrong: { a: { y: string } };
63843
- // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type
63844
- //
63845
- // function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
63846
- // x = y; // Mismatched property in source intersection
63847
- // }
63848
- //
63849
- // We suppress recursive intersection property checks because they can generate lots of work when relating
63850
- // recursive intersections that are structurally similar but not exactly identical. See #37854.
63851
- if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
63852
- isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) {
63853
- inPropertyCheck = true;
63854
- result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags);
63855
- inPropertyCheck = false;
63856
- }
63857
- reportErrorResults(source, target, result, isComparingJsxAttributes);
63858
- return result;
63859
- function reportErrorResults(source, target, result, isComparingJsxAttributes) {
63860
- if (!result && reportErrors) {
63861
- var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource);
63862
- var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget);
63863
- source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source;
63864
- target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target;
63865
- var maybeSuppress = overrideNextErrorInfo > 0;
63866
- if (maybeSuppress) {
63867
- overrideNextErrorInfo--;
63868
- }
63869
- if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
63870
- var currentError = errorInfo;
63871
- tryElaborateArrayLikeErrors(source, target, reportErrors);
63872
- if (errorInfo !== currentError) {
63873
- maybeSuppress = !!errorInfo;
63874
- }
63875
- }
63876
- if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
63877
- tryElaborateErrorsForPrimitivesAndObjects(source, target);
63878
- }
63879
- else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
63880
- reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
63881
- }
63882
- else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
63883
- var targetTypes = target.types;
63884
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
63885
- var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
63886
- if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) &&
63887
- (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
63888
- // do not report top error
63889
- return result;
63890
- }
63891
- }
63892
- else {
63893
- errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
63894
- }
63895
- if (!headMessage && maybeSuppress) {
63896
- lastSkippedInfo = [source, target];
63897
- // Used by, eg, missing property checking to replace the top-level message with a more informative one
63898
- return result;
63899
- }
63900
- reportRelationError(headMessage, source, target);
63901
- }
63965
+ if (!headMessage && maybeSuppress) {
63966
+ lastSkippedInfo = [source, target];
63967
+ // Used by, eg, missing property checking to replace the top-level message with a more informative one
63968
+ return;
63902
63969
  }
63970
+ reportRelationError(headMessage, source, target);
63903
63971
  }
63904
63972
  function traceUnionsOrIntersectionsTooLarge(source, target) {
63905
63973
  if (!ts.tracing) {
@@ -63926,21 +63994,6 @@ var ts;
63926
63994
  }
63927
63995
  }
63928
63996
  }
63929
- function isIdenticalTo(source, target, recursionFlags) {
63930
- if (source.flags !== target.flags)
63931
- return 0 /* False */;
63932
- if (source.flags & 67358815 /* Singleton */)
63933
- return -1 /* True */;
63934
- traceUnionsOrIntersectionsTooLarge(source, target);
63935
- if (source.flags & 3145728 /* UnionOrIntersection */) {
63936
- var result_7 = eachTypeRelatedToSomeType(source, target);
63937
- if (result_7) {
63938
- result_7 &= eachTypeRelatedToSomeType(target, source);
63939
- }
63940
- return result_7;
63941
- }
63942
- return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags);
63943
- }
63944
63997
  function getTypeOfPropertyInTypes(types, name) {
63945
63998
  var appendPropType = function (propTypes, type) {
63946
63999
  var _a;
@@ -64039,6 +64092,41 @@ var ts;
64039
64092
  function shouldCheckAsExcessProperty(prop, container) {
64040
64093
  return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
64041
64094
  }
64095
+ function unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) {
64096
+ // Note that these checks are specifically ordered to produce correct results. In particular,
64097
+ // we need to deconstruct unions before intersections (because unions are always at the top),
64098
+ // and we need to handle "each" relations before "some" relations for the same kind of type.
64099
+ if (source.flags & 1048576 /* Union */) {
64100
+ return relation === comparableRelation ?
64101
+ someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
64102
+ eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
64103
+ }
64104
+ if (target.flags & 1048576 /* Union */) {
64105
+ return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
64106
+ }
64107
+ if (target.flags & 2097152 /* Intersection */) {
64108
+ return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
64109
+ }
64110
+ // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the
64111
+ // constraints of all non-primitive types in the source into a new intersection. We do this because the
64112
+ // intersection may further constrain the constraints of the non-primitive types. For example, given a type
64113
+ // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't
64114
+ // appear to be comparable to '2'.
64115
+ if (relation === comparableRelation && target.flags & 131068 /* Primitive */) {
64116
+ var constraints = ts.sameMap(source.types, getBaseConstraintOrType);
64117
+ if (constraints !== source.types) {
64118
+ source = getIntersectionType(constraints);
64119
+ if (!(source.flags & 2097152 /* Intersection */)) {
64120
+ return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false);
64121
+ }
64122
+ }
64123
+ }
64124
+ // Check to see if any constituents of the intersection are immediately related to the target.
64125
+ // Don't report errors though. Elaborating on whether a source constituent is related to the target is
64126
+ // not actually useful and leads to some confusing error messages. Instead, we rely on the caller
64127
+ // checking whether the full intersection viewed as an object is related to the target.
64128
+ return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
64129
+ }
64042
64130
  function eachTypeRelatedToSomeType(source, target) {
64043
64131
  var result = -1 /* True */;
64044
64132
  var sourceTypes = source.types;
@@ -64074,8 +64162,11 @@ var ts;
64074
64162
  }
64075
64163
  }
64076
64164
  if (reportErrors) {
64165
+ // Elaborate only if we can find a best matching type in the target union
64077
64166
  var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
64078
- isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], 2 /* Target */, /*reportErrors*/ true);
64167
+ if (bestMatchingType) {
64168
+ isRelatedTo(source, bestMatchingType, 2 /* Target */, /*reportErrors*/ true);
64169
+ }
64079
64170
  }
64080
64171
  return 0 /* False */;
64081
64172
  }
@@ -64211,7 +64302,7 @@ var ts;
64211
64302
  if (overflow) {
64212
64303
  return 0 /* False */;
64213
64304
  }
64214
- var keyIntersectionState = intersectionState | (inPropertyCheck ? 16 /* InPropertyCheck */ : 0);
64305
+ var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0);
64215
64306
  var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false);
64216
64307
  var entry = relation.get(id);
64217
64308
  if (entry !== undefined) {
@@ -64279,6 +64370,7 @@ var ts;
64279
64370
  return originalHandler(onlyUnreliable);
64280
64371
  };
64281
64372
  }
64373
+ var result;
64282
64374
  if (expandingFlags === 3 /* Both */) {
64283
64375
  ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", {
64284
64376
  sourceId: source.id,
@@ -64288,8 +64380,13 @@ var ts;
64288
64380
  depth: sourceDepth,
64289
64381
  targetDepth: targetDepth
64290
64382
  });
64383
+ result = 3 /* Maybe */;
64384
+ }
64385
+ else {
64386
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
64387
+ result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState);
64388
+ ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
64291
64389
  }
64292
- var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */;
64293
64390
  if (outofbandVarianceMarkerHandler) {
64294
64391
  outofbandVarianceMarkerHandler = originalHandler;
64295
64392
  }
@@ -64321,98 +64418,97 @@ var ts;
64321
64418
  return result;
64322
64419
  }
64323
64420
  function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
64324
- ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
64325
- var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState);
64326
- ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
64327
- return result;
64328
- }
64329
- function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) {
64330
64421
  if (intersectionState & 4 /* PropertyCheck */) {
64331
64422
  return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
64332
64423
  }
64333
- if (intersectionState & 8 /* UnionIntersectionCheck */) {
64334
- // Note that these checks are specifically ordered to produce correct results. In particular,
64335
- // we need to deconstruct unions before intersections (because unions are always at the top),
64336
- // and we need to handle "each" relations before "some" relations for the same kind of type.
64337
- if (source.flags & 1048576 /* Union */) {
64338
- return relation === comparableRelation ?
64339
- someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */) :
64340
- eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */);
64341
- }
64342
- if (target.flags & 1048576 /* Union */) {
64343
- return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
64344
- }
64345
- if (target.flags & 2097152 /* Intersection */) {
64346
- return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
64347
- }
64348
- // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the
64349
- // constraints of all non-primitive types in the source into a new intersection. We do this because the
64350
- // intersection may further constrain the constraints of the non-primitive types. For example, given a type
64351
- // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't
64352
- // appear to be comparable to '2'.
64353
- if (relation === comparableRelation && target.flags & 131068 /* Primitive */) {
64354
- var constraints = ts.sameMap(source.types, getBaseConstraintOrType);
64355
- if (constraints !== source.types) {
64356
- source = getIntersectionType(constraints);
64357
- if (!(source.flags & 2097152 /* Intersection */)) {
64358
- return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false);
64359
- }
64424
+ var result;
64425
+ var originalErrorInfo;
64426
+ var varianceCheckFailed = false;
64427
+ var saveErrorInfo = captureErrorCalculationState();
64428
+ var sourceFlags = source.flags;
64429
+ var targetFlags = target.flags;
64430
+ if (relation === identityRelation) {
64431
+ // We've already checked that source.flags and target.flags are identical
64432
+ if (sourceFlags & 3145728 /* UnionOrIntersection */) {
64433
+ var result_8 = eachTypeRelatedToSomeType(source, target);
64434
+ if (result_8) {
64435
+ result_8 &= eachTypeRelatedToSomeType(target, source);
64360
64436
  }
64437
+ return result_8;
64361
64438
  }
64362
- // Check to see if any constituents of the intersection are immediately related to the target.
64363
- //
64364
- // Don't report errors though. Checking whether a constituent is related to the source is not actually
64365
- // useful and leads to some confusing error messages. Instead it is better to let the below checks
64366
- // take care of this, or to not elaborate at all. For instance,
64367
- //
64368
- // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
64369
- //
64370
- // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
64371
- // than to report that 'D' is not assignable to 'A' or 'B'.
64372
- //
64373
- // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
64374
- // breaking the intersection apart.
64375
- return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
64376
- }
64377
- var flags = source.flags & target.flags;
64378
- if (relation === identityRelation && !(flags & 524288 /* Object */)) {
64379
- if (flags & 4194304 /* Index */) {
64439
+ if (sourceFlags & 4194304 /* Index */) {
64380
64440
  return isRelatedTo(source.type, target.type, 3 /* Both */, /*reportErrors*/ false);
64381
64441
  }
64382
- var result_8 = 0 /* False */;
64383
- if (flags & 8388608 /* IndexedAccess */) {
64384
- if (result_8 = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) {
64385
- if (result_8 &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) {
64386
- return result_8;
64442
+ if (sourceFlags & 8388608 /* IndexedAccess */) {
64443
+ if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) {
64444
+ if (result &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) {
64445
+ return result;
64387
64446
  }
64388
64447
  }
64389
64448
  }
64390
- if (flags & 16777216 /* Conditional */) {
64449
+ if (sourceFlags & 16777216 /* Conditional */) {
64391
64450
  if (source.root.isDistributive === target.root.isDistributive) {
64392
- if (result_8 = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) {
64393
- if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) {
64394
- if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) {
64395
- if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) {
64396
- return result_8;
64451
+ if (result = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) {
64452
+ if (result &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) {
64453
+ if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) {
64454
+ if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) {
64455
+ return result;
64397
64456
  }
64398
64457
  }
64399
64458
  }
64400
64459
  }
64401
64460
  }
64402
64461
  }
64403
- if (flags & 33554432 /* Substitution */) {
64462
+ if (sourceFlags & 33554432 /* Substitution */) {
64404
64463
  return isRelatedTo(source.substitute, target.substitute, 3 /* Both */, /*reportErrors*/ false);
64405
64464
  }
64406
- return 0 /* False */;
64465
+ if (!(sourceFlags & 524288 /* Object */)) {
64466
+ return 0 /* False */;
64467
+ }
64468
+ }
64469
+ else if (sourceFlags & 3145728 /* UnionOrIntersection */ || targetFlags & 3145728 /* UnionOrIntersection */) {
64470
+ if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) {
64471
+ return result;
64472
+ }
64473
+ if (source.flags & 2097152 /* Intersection */ || source.flags & 262144 /* TypeParameter */ && target.flags & 1048576 /* Union */) {
64474
+ // The combined constraint of an intersection type is the intersection of the constraints of
64475
+ // the constituents. When an intersection type contains instantiable types with union type
64476
+ // constraints, there are situations where we need to examine the combined constraint. One is
64477
+ // when the target is a union type. Another is when the intersection contains types belonging
64478
+ // to one of the disjoint domains. For example, given type variables T and U, each with the
64479
+ // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
64480
+ // we need to check this constraint against a union on the target side. Also, given a type
64481
+ // variable V constrained to 'string | number', 'V & number' has a combined constraint of
64482
+ // 'string & number | number & number' which reduces to just 'number'.
64483
+ // This also handles type parameters, as a type parameter with a union constraint compared against a union
64484
+ // needs to have its constraint hoisted into an intersection with said type parameter, this way
64485
+ // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
64486
+ // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
64487
+ var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
64488
+ if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
64489
+ // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
64490
+ if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
64491
+ resetErrorInfo(saveErrorInfo);
64492
+ return result;
64493
+ }
64494
+ }
64495
+ }
64496
+ // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle:
64497
+ // Source is instantiable (e.g. source has union or intersection constraint).
64498
+ // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }).
64499
+ // Source is an intersection, target is an object (e.g. { a } & { b } <=> { a, b }).
64500
+ // Source is an intersection, target is a union (e.g. { a } & { b: boolean } <=> { a, b: true } | { a, b: false }).
64501
+ // Source is an intersection, target instantiable (e.g. string & { tag } <=> T["a"] constrained to string & { tag }).
64502
+ if (!(sourceFlags & 465829888 /* Instantiable */ ||
64503
+ sourceFlags & 524288 /* Object */ && targetFlags & 1048576 /* Union */ ||
64504
+ sourceFlags & 2097152 /* Intersection */ && targetFlags & (524288 /* Object */ | 1048576 /* Union */ | 465829888 /* Instantiable */))) {
64505
+ return 0 /* False */;
64506
+ }
64407
64507
  }
64408
- var result;
64409
- var originalErrorInfo;
64410
- var varianceCheckFailed = false;
64411
- var saveErrorInfo = captureErrorCalculationState();
64412
64508
  // We limit alias variance probing to only object and conditional types since their alias behavior
64413
64509
  // is more predictable than other, interned types, which may or may not have an alias depending on
64414
64510
  // the order in which things were checked.
64415
- if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
64511
+ if (sourceFlags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
64416
64512
  source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
64417
64513
  !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
64418
64514
  var variances = getAliasVariances(source.aliasSymbol);
@@ -64430,7 +64526,7 @@ var ts;
64430
64526
  isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0], 2 /* Target */))) {
64431
64527
  return result;
64432
64528
  }
64433
- if (target.flags & 262144 /* TypeParameter */) {
64529
+ if (targetFlags & 262144 /* TypeParameter */) {
64434
64530
  // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
64435
64531
  if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source), 3 /* Both */)) {
64436
64532
  if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
@@ -64442,10 +64538,10 @@ var ts;
64442
64538
  }
64443
64539
  }
64444
64540
  }
64445
- else if (target.flags & 4194304 /* Index */) {
64541
+ else if (targetFlags & 4194304 /* Index */) {
64446
64542
  var targetType_1 = target.type;
64447
64543
  // A keyof S is related to a keyof T if T is related to S.
64448
- if (source.flags & 4194304 /* Index */) {
64544
+ if (sourceFlags & 4194304 /* Index */) {
64449
64545
  if (result = isRelatedTo(targetType_1, source.type, 3 /* Both */, /*reportErrors*/ false)) {
64450
64546
  return result;
64451
64547
  }
@@ -64496,8 +64592,8 @@ var ts;
64496
64592
  }
64497
64593
  }
64498
64594
  }
64499
- else if (target.flags & 8388608 /* IndexedAccess */) {
64500
- if (source.flags & 8388608 /* IndexedAccess */) {
64595
+ else if (targetFlags & 8388608 /* IndexedAccess */) {
64596
+ if (sourceFlags & 8388608 /* IndexedAccess */) {
64501
64597
  // Relate components directly before falling back to constraint relationships
64502
64598
  // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
64503
64599
  if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, reportErrors)) {
@@ -64603,7 +64699,7 @@ var ts;
64603
64699
  }
64604
64700
  }
64605
64701
  }
64606
- else if (target.flags & 16777216 /* Conditional */) {
64702
+ else if (targetFlags & 16777216 /* Conditional */) {
64607
64703
  // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive
64608
64704
  // conditional type and bail out with a Ternary.Maybe result.
64609
64705
  if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) {
@@ -64628,8 +64724,8 @@ var ts;
64628
64724
  }
64629
64725
  }
64630
64726
  }
64631
- else if (target.flags & 134217728 /* TemplateLiteral */) {
64632
- if (source.flags & 134217728 /* TemplateLiteral */) {
64727
+ else if (targetFlags & 134217728 /* TemplateLiteral */) {
64728
+ if (sourceFlags & 134217728 /* TemplateLiteral */) {
64633
64729
  if (relation === comparableRelation) {
64634
64730
  return templateLiteralTypesDefinitelyUnrelated(source, target) ? 0 /* False */ : -1 /* True */;
64635
64731
  }
@@ -64641,11 +64737,11 @@ var ts;
64641
64737
  return -1 /* True */;
64642
64738
  }
64643
64739
  }
64644
- if (source.flags & 8650752 /* TypeVariable */) {
64645
- // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch
64646
- if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) {
64740
+ if (sourceFlags & 8650752 /* TypeVariable */) {
64741
+ // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch
64742
+ if (!(sourceFlags & 8388608 /* IndexedAccess */ && targetFlags & 8388608 /* IndexedAccess */)) {
64647
64743
  var constraint = getConstraintOfType(source);
64648
- if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
64744
+ if (!constraint || (sourceFlags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
64649
64745
  // A type variable with no constraint is not related to the non-primitive object type.
64650
64746
  if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */), 3 /* Both */)) {
64651
64747
  resetErrorInfo(saveErrorInfo);
@@ -64658,7 +64754,7 @@ var ts;
64658
64754
  return result;
64659
64755
  }
64660
64756
  // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
64661
- else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) {
64757
+ else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) {
64662
64758
  resetErrorInfo(saveErrorInfo);
64663
64759
  return result;
64664
64760
  }
@@ -64675,14 +64771,14 @@ var ts;
64675
64771
  }
64676
64772
  }
64677
64773
  }
64678
- else if (source.flags & 4194304 /* Index */) {
64774
+ else if (sourceFlags & 4194304 /* Index */) {
64679
64775
  if (result = isRelatedTo(keyofConstraintType, target, 1 /* Source */, reportErrors)) {
64680
64776
  resetErrorInfo(saveErrorInfo);
64681
64777
  return result;
64682
64778
  }
64683
64779
  }
64684
- else if (source.flags & 134217728 /* TemplateLiteral */ && !(target.flags & 524288 /* Object */)) {
64685
- if (!(target.flags & 134217728 /* TemplateLiteral */)) {
64780
+ else if (sourceFlags & 134217728 /* TemplateLiteral */ && !(targetFlags & 524288 /* Object */)) {
64781
+ if (!(targetFlags & 134217728 /* TemplateLiteral */)) {
64686
64782
  var constraint = getBaseConstraintOfType(source);
64687
64783
  if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* Source */, reportErrors))) {
64688
64784
  resetErrorInfo(saveErrorInfo);
@@ -64690,8 +64786,8 @@ var ts;
64690
64786
  }
64691
64787
  }
64692
64788
  }
64693
- else if (source.flags & 268435456 /* StringMapping */) {
64694
- if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) {
64789
+ else if (sourceFlags & 268435456 /* StringMapping */) {
64790
+ if (targetFlags & 268435456 /* StringMapping */ && source.symbol === target.symbol) {
64695
64791
  if (result = isRelatedTo(source.type, target.type, 3 /* Both */, reportErrors)) {
64696
64792
  resetErrorInfo(saveErrorInfo);
64697
64793
  return result;
@@ -64705,14 +64801,14 @@ var ts;
64705
64801
  }
64706
64802
  }
64707
64803
  }
64708
- else if (source.flags & 16777216 /* Conditional */) {
64804
+ else if (sourceFlags & 16777216 /* Conditional */) {
64709
64805
  // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive
64710
64806
  // conditional type and bail out with a Ternary.Maybe result.
64711
64807
  if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) {
64712
64808
  resetErrorInfo(saveErrorInfo);
64713
64809
  return 3 /* Maybe */;
64714
64810
  }
64715
- if (target.flags & 16777216 /* Conditional */) {
64811
+ if (targetFlags & 16777216 /* Conditional */) {
64716
64812
  // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
64717
64813
  // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
64718
64814
  // and Y1 is related to Y2.
@@ -64772,15 +64868,21 @@ var ts;
64772
64868
  }
64773
64869
  return 0 /* False */;
64774
64870
  }
64775
- var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
64871
+ var sourceIsPrimitive = !!(sourceFlags & 131068 /* Primitive */);
64776
64872
  if (relation !== identityRelation) {
64777
64873
  source = getApparentType(source);
64874
+ sourceFlags = source.flags;
64778
64875
  }
64779
64876
  else if (isGenericMappedType(source)) {
64780
64877
  return 0 /* False */;
64781
64878
  }
64782
64879
  if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
64783
64880
  !isTupleType(source) && !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) {
64881
+ // When strictNullChecks is disabled, the element type of the empty array literal is undefinedWideningType,
64882
+ // and an empty array literal wouldn't be assignable to a `never[]` without this check.
64883
+ if (isEmptyArrayLiteralType(source)) {
64884
+ return -1 /* True */;
64885
+ }
64784
64886
  // We have type references to the same generic type, and the type references are not marker
64785
64887
  // type references (which are intended by be compared structurally). Obtain the variance
64786
64888
  // information for the type parameters and relate the type arguments accordingly.
@@ -64816,7 +64918,7 @@ var ts;
64816
64918
  // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
64817
64919
  // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
64818
64920
  // relates to X. Thus, we include intersection types on the source side here.
64819
- if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
64921
+ if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 524288 /* Object */) {
64820
64922
  // Report structural errors only if we haven't reported any errors yet
64821
64923
  var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
64822
64924
  result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
@@ -64840,7 +64942,7 @@ var ts;
64840
64942
  // there exists a constituent of T for every combination of the discriminants of S
64841
64943
  // with respect to T. We do not report errors here, as we will use the existing
64842
64944
  // error result from checking each constituent of the union.
64843
- if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
64945
+ if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 1048576 /* Union */) {
64844
64946
  var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
64845
64947
  if (objectOnlyTarget.flags & 1048576 /* Union */) {
64846
64948
  var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
@@ -65087,6 +65189,15 @@ var ts;
65087
65189
  }
65088
65190
  return 0 /* False */;
65089
65191
  }
65192
+ // Ensure {readonly a: whatever} is not a subtype of {a: whatever},
65193
+ // while {a: whatever} is a subtype of {readonly a: whatever}.
65194
+ // This ensures the subtype relationship is ordered, and preventing declaration order
65195
+ // from deciding which type "wins" in union subtype reduction.
65196
+ // They're still assignable to one another, since `readonly` doesn't affect assignability.
65197
+ if ((relation === subtypeRelation || relation === strictSubtypeRelation) &&
65198
+ !!(sourcePropFlags & 64 /* Readonly */) && !(targetPropFlags & 64 /* Readonly */)) {
65199
+ return 0 /* False */;
65200
+ }
65090
65201
  // If the target comes from a partial union prop, allow `undefined` in the target type
65091
65202
  var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
65092
65203
  if (!related) {
@@ -65355,7 +65466,6 @@ var ts;
65355
65466
  }
65356
65467
  }
65357
65468
  var result = -1 /* True */;
65358
- var saveErrorInfo = captureErrorCalculationState();
65359
65469
  var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
65360
65470
  var sourceObjectFlags = ts.getObjectFlags(source);
65361
65471
  var targetObjectFlags = ts.getObjectFlags(target);
@@ -65396,6 +65506,7 @@ var ts;
65396
65506
  else {
65397
65507
  outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
65398
65508
  var t = targetSignatures_1[_i];
65509
+ var saveErrorInfo = captureErrorCalculationState();
65399
65510
  // Only elaborate errors from the first failure
65400
65511
  var shouldElaborateErrors = reportErrors;
65401
65512
  for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) {
@@ -68566,9 +68677,6 @@ var ts;
68566
68677
  getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) :
68567
68678
  mapType(type, mapper);
68568
68679
  }
68569
- function getConstituentCount(type) {
68570
- return type.flags & 1048576 /* Union */ ? type.types.length : 1;
68571
- }
68572
68680
  function extractTypesOfKind(type, kind) {
68573
68681
  return filterType(type, function (t) { return (t.flags & kind) !== 0; });
68574
68682
  }
@@ -73289,6 +73397,9 @@ var ts;
73289
73397
  if (compilerOptions.noPropertyAccessFromIndexSignature && ts.isPropertyAccessExpression(node)) {
73290
73398
  error(right, ts.Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, ts.unescapeLeadingUnderscores(right.escapedText));
73291
73399
  }
73400
+ if (indexInfo.declaration && ts.getCombinedNodeFlags(indexInfo.declaration) & 134217728 /* Deprecated */) {
73401
+ addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText);
73402
+ }
73292
73403
  }
73293
73404
  else {
73294
73405
  if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) {
@@ -75773,8 +75884,8 @@ var ts;
75773
75884
  if (hasDefaultOnly && type && !isErrorType(type)) {
75774
75885
  var synthType = type;
75775
75886
  if (!synthType.defaultOnlyType) {
75776
- var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol);
75777
- synthType.defaultOnlyType = type_4;
75887
+ var type_5 = createDefaultPropertyWrapperForModule(symbol, originalSymbol);
75888
+ synthType.defaultOnlyType = type_5;
75778
75889
  }
75779
75890
  return synthType.defaultOnlyType;
75780
75891
  }
@@ -76234,21 +76345,22 @@ var ts;
76234
76345
  if (links.type === unknownType) {
76235
76346
  links.type = getTypeFromBindingPattern(declaration.name);
76236
76347
  }
76237
- assignBindingElementTypes(declaration.name);
76348
+ assignBindingElementTypes(declaration.name, links.type);
76238
76349
  }
76239
76350
  }
76240
76351
  }
76241
76352
  // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
76242
76353
  // the destructured type into the contained binding elements.
76243
- function assignBindingElementTypes(pattern) {
76354
+ function assignBindingElementTypes(pattern, parentType) {
76244
76355
  for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
76245
76356
  var element = _a[_i];
76246
76357
  if (!ts.isOmittedExpression(element)) {
76358
+ var type = getBindingElementTypeFromParentType(element, parentType);
76247
76359
  if (element.name.kind === 79 /* Identifier */) {
76248
- getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
76360
+ getSymbolLinks(getSymbolOfNode(element)).type = type;
76249
76361
  }
76250
76362
  else {
76251
- assignBindingElementTypes(element.name);
76363
+ assignBindingElementTypes(element.name, type);
76252
76364
  }
76253
76365
  }
76254
76366
  }
@@ -76501,12 +76613,12 @@ var ts;
76501
76613
  var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
76502
76614
  // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
76503
76615
  var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
76504
- var type_5 = getBaseConstraintOfType(operandType) || operandType;
76616
+ var type_6 = getBaseConstraintOfType(operandType) || operandType;
76505
76617
  // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types.
76506
- if (type_5.flags & 3 /* AnyOrUnknown */) {
76618
+ if (type_6.flags & 3 /* AnyOrUnknown */) {
76507
76619
  return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */;
76508
76620
  }
76509
- return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
76621
+ return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
76510
76622
  }
76511
76623
  var type = getTypeOfExpression(node.expression);
76512
76624
  if (!isLiteralType(type)) {
@@ -78628,6 +78740,7 @@ var ts;
78628
78740
  }
78629
78741
  }
78630
78742
  checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
78743
+ checkUnmatchedJSDocParameters(node);
78631
78744
  ts.forEach(node.parameters, checkParameter);
78632
78745
  // TODO(rbuckton): Should we start checking JSDoc types?
78633
78746
  if (node.type) {
@@ -79988,28 +80101,24 @@ var ts;
79988
80101
  if (returnType.flags & 1 /* Any */) {
79989
80102
  return;
79990
80103
  }
80104
+ var headMessage;
79991
80105
  var expectedReturnType;
79992
- var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
79993
- var errorInfo;
79994
80106
  switch (node.parent.kind) {
79995
80107
  case 256 /* ClassDeclaration */:
80108
+ headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
79996
80109
  var classSymbol = getSymbolOfNode(node.parent);
79997
80110
  var classConstructorType = getTypeOfSymbol(classSymbol);
79998
80111
  expectedReturnType = getUnionType([classConstructorType, voidType]);
79999
80112
  break;
80113
+ case 166 /* PropertyDeclaration */:
80000
80114
  case 163 /* Parameter */:
80115
+ headMessage = ts.Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any;
80001
80116
  expectedReturnType = voidType;
80002
- errorInfo = ts.chainDiagnosticMessages(
80003
- /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
80004
- break;
80005
- case 166 /* PropertyDeclaration */:
80006
- expectedReturnType = voidType;
80007
- errorInfo = ts.chainDiagnosticMessages(
80008
- /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
80009
80117
  break;
80010
80118
  case 168 /* MethodDeclaration */:
80011
80119
  case 171 /* GetAccessor */:
80012
80120
  case 172 /* SetAccessor */:
80121
+ headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
80013
80122
  var methodType = getTypeOfNode(node.parent);
80014
80123
  var descriptorType = createTypedPropertyDescriptorType(methodType);
80015
80124
  expectedReturnType = getUnionType([descriptorType, voidType]);
@@ -80017,7 +80126,7 @@ var ts;
80017
80126
  default:
80018
80127
  return ts.Debug.fail();
80019
80128
  }
80020
- checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
80129
+ checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage);
80021
80130
  }
80022
80131
  /**
80023
80132
  * If a TypeNode can be resolved to a value symbol imported from an external module, it is
@@ -80199,31 +80308,6 @@ var ts;
80199
80308
  }
80200
80309
  function checkJSDocParameterTag(node) {
80201
80310
  checkSourceElement(node.typeExpression);
80202
- if (!ts.getParameterSymbolFromJSDoc(node)) {
80203
- var decl = ts.getHostSignatureFromJSDoc(node);
80204
- // don't issue an error for invalid hosts -- just functions --
80205
- // and give a better error message when the host function mentions `arguments`
80206
- // but the tag doesn't have an array type
80207
- if (decl) {
80208
- var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
80209
- if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
80210
- return;
80211
- }
80212
- if (!containsArgumentsReference(decl)) {
80213
- if (ts.isQualifiedName(node.name)) {
80214
- error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left));
80215
- }
80216
- else {
80217
- error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
80218
- }
80219
- }
80220
- else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
80221
- node.typeExpression && node.typeExpression.type &&
80222
- !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
80223
- error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 160 /* QualifiedName */ ? node.name.right : node.name));
80224
- }
80225
- }
80226
- }
80227
80311
  }
80228
80312
  function checkJSDocPropertyTag(node) {
80229
80313
  checkSourceElement(node.typeExpression);
@@ -82296,6 +82380,45 @@ var ts;
82296
82380
  error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494
82297
82381
  }
82298
82382
  }
82383
+ function checkUnmatchedJSDocParameters(node) {
82384
+ var jsdocParameters = ts.filter(ts.getJSDocTags(node), ts.isJSDocParameterTag);
82385
+ if (!ts.length(jsdocParameters))
82386
+ return;
82387
+ var isJs = ts.isInJSFile(node);
82388
+ var parameters = new ts.Set();
82389
+ var excludedParameters = new ts.Set();
82390
+ ts.forEach(node.parameters, function (_a, index) {
82391
+ var name = _a.name;
82392
+ if (ts.isIdentifier(name)) {
82393
+ parameters.add(name.escapedText);
82394
+ }
82395
+ if (ts.isBindingPattern(name)) {
82396
+ excludedParameters.add(index);
82397
+ }
82398
+ });
82399
+ var containsArguments = containsArgumentsReference(node);
82400
+ if (containsArguments) {
82401
+ var lastJSDocParam = ts.lastOrUndefined(jsdocParameters);
82402
+ if (lastJSDocParam && ts.isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression &&
82403
+ lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) {
82404
+ errorOrSuggestion(isJs, lastJSDocParam.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(lastJSDocParam.name));
82405
+ }
82406
+ }
82407
+ else {
82408
+ ts.forEach(jsdocParameters, function (_a, index) {
82409
+ var name = _a.name;
82410
+ if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) {
82411
+ return;
82412
+ }
82413
+ if (ts.isQualifiedName(name)) {
82414
+ errorOrSuggestion(isJs, name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(name), ts.entityNameToString(name.left));
82415
+ }
82416
+ else {
82417
+ errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name));
82418
+ }
82419
+ });
82420
+ }
82421
+ }
82299
82422
  /**
82300
82423
  * Check each type parameter and check that type parameters have no duplicate type parameter declarations
82301
82424
  */
@@ -83504,6 +83627,9 @@ var ts;
83504
83627
  var name = ts.idText(node.kind === 269 /* ImportSpecifier */ ? node.propertyName || node.name : node.name);
83505
83628
  addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? undefined : typeOnlyAlias, name);
83506
83629
  }
83630
+ if (isType && node.kind === 264 /* ImportEqualsDeclaration */ && ts.hasEffectiveModifier(node, 1 /* Export */)) {
83631
+ error(node, ts.Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided);
83632
+ }
83507
83633
  break;
83508
83634
  }
83509
83635
  case 274 /* ExportSpecifier */: {
@@ -85548,7 +85674,7 @@ var ts;
85548
85674
  if (resolvedTypeReferenceDirectives) {
85549
85675
  // populate reverse mapping: file path -> type reference directive that was resolved to this file
85550
85676
  fileToDirective = new ts.Map();
85551
- resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
85677
+ resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key, mode) {
85552
85678
  if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
85553
85679
  return;
85554
85680
  }
@@ -85556,7 +85682,7 @@ var ts;
85556
85682
  if (file) {
85557
85683
  // Add the transitive closure of path references loaded by this file (as long as they are not)
85558
85684
  // part of an existing type reference.
85559
- addReferencedFilesToTypeDirective(file, key);
85685
+ addReferencedFilesToTypeDirective(file, key, mode);
85560
85686
  }
85561
85687
  });
85562
85688
  }
@@ -85750,16 +85876,16 @@ var ts;
85750
85876
  }
85751
85877
  return false;
85752
85878
  }
85753
- function addReferencedFilesToTypeDirective(file, key) {
85879
+ function addReferencedFilesToTypeDirective(file, key, mode) {
85754
85880
  if (fileToDirective.has(file.path))
85755
85881
  return;
85756
- fileToDirective.set(file.path, key);
85882
+ fileToDirective.set(file.path, [key, mode]);
85757
85883
  for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
85758
- var fileName = _a[_i].fileName;
85884
+ var _b = _a[_i], fileName = _b.fileName, resolutionMode = _b.resolutionMode;
85759
85885
  var resolvedFile = ts.resolveTripleslashReference(fileName, file.fileName);
85760
85886
  var referencedFile = host.getSourceFile(resolvedFile);
85761
85887
  if (referencedFile) {
85762
- addReferencedFilesToTypeDirective(referencedFile, key);
85888
+ addReferencedFilesToTypeDirective(referencedFile, key, resolutionMode || file.impliedNodeFormat);
85763
85889
  }
85764
85890
  }
85765
85891
  }
@@ -87464,28 +87590,27 @@ var ts;
87464
87590
  }
87465
87591
  function findMostOverlappyType(source, unionTarget) {
87466
87592
  var bestMatch;
87467
- var matchingCount = 0;
87468
- for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
87469
- var target = _a[_i];
87470
- var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
87471
- if (overlap.flags & 4194304 /* Index */) {
87472
- // perfect overlap of keys
87473
- bestMatch = target;
87474
- matchingCount = Infinity;
87475
- }
87476
- else if (overlap.flags & 1048576 /* Union */) {
87477
- // We only want to account for literal types otherwise.
87478
- // If we have a union of index types, it seems likely that we
87479
- // needed to elaborate between two generic mapped types anyway.
87480
- var len = ts.length(ts.filter(overlap.types, isUnitType));
87481
- if (len >= matchingCount) {
87482
- bestMatch = target;
87483
- matchingCount = len;
87484
- }
87485
- }
87486
- else if (isUnitType(overlap) && 1 >= matchingCount) {
87487
- bestMatch = target;
87488
- matchingCount = 1;
87593
+ if (!(source.flags & (131068 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) {
87594
+ var matchingCount = 0;
87595
+ for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
87596
+ var target = _a[_i];
87597
+ if (!(target.flags & (131068 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) {
87598
+ var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
87599
+ if (overlap.flags & 4194304 /* Index */) {
87600
+ // perfect overlap of keys
87601
+ return target;
87602
+ }
87603
+ else if (isUnitType(overlap) || overlap.flags & 1048576 /* Union */) {
87604
+ // We only want to account for literal types otherwise.
87605
+ // If we have a union of index types, it seems likely that we
87606
+ // needed to elaborate between two generic mapped types anyway.
87607
+ var len = overlap.flags & 1048576 /* Union */ ? ts.countWhere(overlap.types, isUnitType) : 1;
87608
+ if (len >= matchingCount) {
87609
+ bestMatch = target;
87610
+ matchingCount = len;
87611
+ }
87612
+ }
87613
+ }
87489
87614
  }
87490
87615
  }
87491
87616
  return bestMatch;
@@ -106528,7 +106653,7 @@ var ts;
106528
106653
  var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
106529
106654
  hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
106530
106655
  collectReferences(sourceFile, refs);
106531
- recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
106656
+ recordTypeReferenceDirectivesIfNecessary(ts.map(sourceFile.typeReferenceDirectives, function (ref) { return [ref.fileName, ref.resolutionMode]; }));
106532
106657
  collectLibs(sourceFile, libs);
106533
106658
  return sourceFile;
106534
106659
  }
@@ -106583,9 +106708,10 @@ var ts;
106583
106708
  return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
106584
106709
  }
106585
106710
  function getFileReferencesForUsedTypeReferences() {
106586
- return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
106711
+ return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForSpecifierModeTuple) : [];
106587
106712
  }
106588
- function getFileReferenceForTypeName(typeName) {
106713
+ function getFileReferenceForSpecifierModeTuple(_a) {
106714
+ var typeName = _a[0], mode = _a[1];
106589
106715
  // Elide type references for which we have imports
106590
106716
  if (emittedImports) {
106591
106717
  for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
@@ -106601,7 +106727,7 @@ var ts;
106601
106727
  }
106602
106728
  }
106603
106729
  }
106604
- return { fileName: typeName, pos: -1, end: -1 };
106730
+ return __assign({ fileName: typeName, pos: -1, end: -1 }, (mode ? { resolutionMode: mode } : undefined));
106605
106731
  }
106606
106732
  function mapReferencesIntoArray(references, outputFilePath) {
106607
106733
  return function (file) {
@@ -106621,7 +106747,7 @@ var ts;
106621
106747
  // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
106622
106748
  // via a non-relative name, emit a type reference directive to that non-relative name, rather than
106623
106749
  // a relative path to the declaration file
106624
- recordTypeReferenceDirectivesIfNecessary([specifier]);
106750
+ recordTypeReferenceDirectivesIfNecessary([[specifier, /*mode*/ undefined]]);
106625
106751
  return;
106626
106752
  }
106627
106753
  var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
@@ -111733,9 +111859,12 @@ var ts;
111733
111859
  for (var _d = 0, types_24 = types; _d < types_24.length; _d++) {
111734
111860
  var directive = types_24[_d];
111735
111861
  var pos = writer.getTextPos();
111736
- writeComment("/// <reference types=\"" + directive.fileName + "\" />");
111862
+ var resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.impliedNodeFormat)
111863
+ ? "resolution-mode=\"" + (directive.resolutionMode === ts.ModuleKind.ESNext ? "import" : "require") + "\""
111864
+ : "";
111865
+ writeComment("/// <reference types=\"" + directive.fileName + "\" " + resolutionMode + "/>");
111737
111866
  if (bundleFileInfo)
111738
- bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
111867
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: !directive.resolutionMode ? "type" /* Type */ : directive.resolutionMode === ts.ModuleKind.ESNext ? "type-import" /* TypeResolutionModeImport */ : "type-require" /* TypeResolutionModeRequire */, data: directive.fileName });
111739
111868
  writeLine();
111740
111869
  }
111741
111870
  for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
@@ -114342,7 +114471,7 @@ var ts;
114342
114471
  }
114343
114472
  ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
114344
114473
  /* @internal */
114345
- function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
114474
+ function loadWithTypeDirectiveCache(names, containingFile, redirectedReference, containingFileMode, loader) {
114346
114475
  if (names.length === 0) {
114347
114476
  return [];
114348
114477
  }
@@ -114351,19 +114480,28 @@ var ts;
114351
114480
  for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
114352
114481
  var name = names_2[_i];
114353
114482
  var result = void 0;
114354
- if (cache.has(name)) {
114355
- result = cache.get(name);
114483
+ var mode = getModeForFileReference(name, containingFileMode);
114484
+ // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
114485
+ var strName = ts.isString(name) ? name : name.fileName.toLowerCase();
114486
+ var cacheKey = mode !== undefined ? mode + "|" + strName : strName;
114487
+ if (cache.has(cacheKey)) {
114488
+ result = cache.get(cacheKey);
114356
114489
  }
114357
114490
  else {
114358
- cache.set(name, result = loader(name, containingFile, redirectedReference));
114491
+ cache.set(cacheKey, result = loader(strName, containingFile, redirectedReference, mode));
114359
114492
  }
114360
114493
  resolutions.push(result);
114361
114494
  }
114362
114495
  return resolutions;
114363
114496
  }
114364
- ts.loadWithLocalCache = loadWithLocalCache;
114497
+ ts.loadWithTypeDirectiveCache = loadWithTypeDirectiveCache;
114365
114498
  ;
114366
114499
  /* @internal */
114500
+ function getModeForFileReference(ref, containingFileMode) {
114501
+ return (ts.isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode;
114502
+ }
114503
+ ts.getModeForFileReference = getModeForFileReference;
114504
+ /* @internal */
114367
114505
  function getModeForResolutionAtIndex(file, index) {
114368
114506
  if (file.impliedNodeFormat === undefined)
114369
114507
  return undefined;
@@ -114466,7 +114604,7 @@ var ts;
114466
114604
  var _d, _e, _f, _g;
114467
114605
  var file = ts.Debug.checkDefined(getSourceFileByPath(ref.file));
114468
114606
  var kind = ref.kind, index = ref.index;
114469
- var pos, end, packageId;
114607
+ var pos, end, packageId, resolutionMode;
114470
114608
  switch (kind) {
114471
114609
  case ts.FileIncludeKind.Import:
114472
114610
  var importLiteral = getModuleNameStringLiteralAt(file, index);
@@ -114480,8 +114618,8 @@ var ts;
114480
114618
  (_a = file.referencedFiles[index], pos = _a.pos, end = _a.end);
114481
114619
  break;
114482
114620
  case ts.FileIncludeKind.TypeReferenceDirective:
114483
- (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
114484
- packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId;
114621
+ (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end, resolutionMode = _b.resolutionMode);
114622
+ packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId;
114485
114623
  break;
114486
114624
  case ts.FileIncludeKind.LibReferenceDirective:
114487
114625
  (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end);
@@ -114725,7 +114863,7 @@ var ts;
114725
114863
  var fileReasons = ts.createMultiMap();
114726
114864
  var cachedBindAndCheckDiagnosticsForFile = {};
114727
114865
  var cachedDeclarationDiagnosticsForFile = {};
114728
- var resolvedTypeReferenceDirectives = new ts.Map();
114866
+ var resolvedTypeReferenceDirectives = ts.createModeAwareCache();
114729
114867
  var fileProcessingDiagnostics;
114730
114868
  // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
114731
114869
  // This works as imported modules are discovered recursively in a depth first manner, specifically:
@@ -114778,12 +114916,12 @@ var ts;
114778
114916
  }
114779
114917
  var actualResolveTypeReferenceDirectiveNamesWorker;
114780
114918
  if (host.resolveTypeReferenceDirectives) {
114781
- actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
114919
+ actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference, containingFileMode) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options, containingFileMode); };
114782
114920
  }
114783
114921
  else {
114784
114922
  typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache());
114785
- var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217
114786
- actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
114923
+ var loader_2 = function (typesRef, containingFile, redirectedReference, resolutionMode) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache, resolutionMode).resolvedTypeReferenceDirective; }; // TODO: GH#18217
114924
+ actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference, containingFileMode) { return loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_2); };
114787
114925
  }
114788
114926
  // Map from a stringified PackageId to the source file with that id.
114789
114927
  // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
@@ -114880,7 +115018,8 @@ var ts;
114880
115018
  var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
114881
115019
  var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
114882
115020
  for (var i = 0; i < typeReferences.length; i++) {
114883
- processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_c = resolutions[i]) === null || _c === void 0 ? void 0 : _c.packageId });
115021
+ // under node12/nodenext module resolution, load `types`/ata include names as cjs resolution results by passing an `undefined` mode
115022
+ processTypeReferenceDirective(typeReferences[i], /*mode*/ undefined, resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_c = resolutions[i]) === null || _c === void 0 ? void 0 : _c.packageId });
114884
115023
  }
114885
115024
  ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
114886
115025
  }
@@ -115040,9 +115179,10 @@ var ts;
115040
115179
  return [];
115041
115180
  var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
115042
115181
  var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
115182
+ var containingFileMode = !ts.isString(containingFile) ? containingFile.impliedNodeFormat : undefined;
115043
115183
  ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
115044
115184
  ts.performance.mark("beforeResolveTypeReference");
115045
- var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
115185
+ var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference, containingFileMode);
115046
115186
  ts.performance.mark("afterResolveTypeReference");
115047
115187
  ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
115048
115188
  ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
@@ -115434,8 +115574,7 @@ var ts;
115434
115574
  else {
115435
115575
  newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
115436
115576
  }
115437
- // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
115438
- var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
115577
+ var typesReferenceDirectives = newSourceFile.typeReferenceDirectives;
115439
115578
  var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
115440
115579
  // ensure that types resolutions are still correct
115441
115580
  var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo);
@@ -116514,8 +116653,7 @@ var ts;
116514
116653
  });
116515
116654
  }
116516
116655
  function processTypeReferenceDirectives(file) {
116517
- // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
116518
- var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
116656
+ var typeDirectives = file.typeReferenceDirectives;
116519
116657
  if (!typeDirectives) {
116520
116658
  return;
116521
116659
  }
@@ -116526,17 +116664,21 @@ var ts;
116526
116664
  // store resolved type directive on the file
116527
116665
  var fileName = ts.toFileNameLowerCase(ref.fileName);
116528
116666
  ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
116529
- processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, });
116667
+ var mode = ref.resolutionMode || file.impliedNodeFormat;
116668
+ if (mode && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) {
116669
+ programDiagnostics.add(ts.createDiagnosticForRange(file, ref, ts.Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node12_or_nodenext));
116670
+ }
116671
+ processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, });
116530
116672
  }
116531
116673
  }
116532
- function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
116674
+ function processTypeReferenceDirective(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) {
116533
116675
  ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined });
116534
- processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason);
116676
+ processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason);
116535
116677
  ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
116536
116678
  }
116537
- function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
116679
+ function processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason) {
116538
116680
  // If we already found this library as a primary reference - nothing to do
116539
- var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
116681
+ var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode);
116540
116682
  if (previousResolution && previousResolution.primary) {
116541
116683
  return;
116542
116684
  }
@@ -116575,7 +116717,7 @@ var ts;
116575
116717
  addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_find_type_definition_file_for_0, [typeReferenceDirective]);
116576
116718
  }
116577
116719
  if (saveResolution) {
116578
- resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
116720
+ resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolvedTypeReferenceDirective);
116579
116721
  }
116580
116722
  }
116581
116723
  function pathForLibFile(libFileName) {
@@ -119393,9 +119535,9 @@ var ts;
119393
119535
  });
119394
119536
  hasChangedAutomaticTypeDirectiveNames = false;
119395
119537
  }
119396
- function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
119538
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference, _containingSourceFile, mode) {
119397
119539
  var _a;
119398
- var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
119540
+ var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
119399
119541
  // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
119400
119542
  if (!resolutionHost.getGlobalCache) {
119401
119543
  return primaryResult;
@@ -119416,12 +119558,12 @@ var ts;
119416
119558
  // Default return the result from the first pass
119417
119559
  return primaryResult;
119418
119560
  }
119419
- function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
119420
- return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache);
119561
+ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, _containingSourceFile, resolutionMode) {
119562
+ return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache, resolutionMode);
119421
119563
  }
119422
119564
  function resolveNamesWithLocalCache(_a) {
119423
119565
  var _b, _c, _d;
119424
- var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges, containingSourceFile = _a.containingSourceFile;
119566
+ var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges, containingSourceFile = _a.containingSourceFile, containingSourceFileMode = _a.containingSourceFileMode;
119425
119567
  var path = resolutionHost.toPath(containingFile);
119426
119568
  var resolutionsInFile = cache.get(path) || cache.set(path, ts.createModeAwareCache()).get(path);
119427
119569
  var dirPath = ts.getDirectoryPath(path);
@@ -119443,8 +119585,15 @@ var ts;
119443
119585
  var seenNamesInFile = ts.createModeAwareCache();
119444
119586
  var i = 0;
119445
119587
  for (var _i = 0, names_4 = names; _i < names_4.length; _i++) {
119446
- var name = names_4[_i];
119447
- var mode = containingSourceFile ? ts.getModeForResolutionAtIndex(containingSourceFile, i) : undefined;
119588
+ var entry = names_4[_i];
119589
+ var name = ts.isString(entry) ? entry : entry.fileName.toLowerCase();
119590
+ // Imports supply a `containingSourceFile` but no `containingSourceFileMode` - it would be redundant
119591
+ // they require calculating the mode for a given import from it's position in the resolution table, since a given
119592
+ // import's syntax may override the file's default mode.
119593
+ // Type references instead supply a `containingSourceFileMode` and a non-string entry which contains
119594
+ // a default file mode override if applicable.
119595
+ var mode = !ts.isString(entry) ? ts.getModeForFileReference(entry, containingSourceFileMode) :
119596
+ containingSourceFile ? ts.getModeForResolutionAtIndex(containingSourceFile, i) : undefined;
119448
119597
  i++;
119449
119598
  var resolution = resolutionsInFile.get(name, mode);
119450
119599
  // Resolution is valid if it is present and not invalidated
@@ -119473,7 +119622,7 @@ var ts;
119473
119622
  }
119474
119623
  }
119475
119624
  else {
119476
- resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile);
119625
+ resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile, mode);
119477
119626
  perDirectoryResolution.set(name, mode, resolution);
119478
119627
  if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) {
119479
119628
  resolutionHost.onDiscoveredSymlink();
@@ -119537,7 +119686,7 @@ var ts;
119537
119686
  return oldResult.resolvedFileName === newResult.resolvedFileName;
119538
119687
  }
119539
119688
  }
119540
- function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
119689
+ function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode) {
119541
119690
  return resolveNamesWithLocalCache({
119542
119691
  names: typeDirectiveNames,
119543
119692
  containingFile: containingFile,
@@ -119547,6 +119696,7 @@ var ts;
119547
119696
  loader: resolveTypeReferenceDirective,
119548
119697
  getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
119549
119698
  shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
119699
+ containingSourceFileMode: containingFileMode
119550
119700
  });
119551
119701
  }
119552
119702
  function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference, containingSourceFile) {
@@ -121455,7 +121605,7 @@ var ts;
121455
121605
  }
121456
121606
  return host.resolveTypeReferenceDirectives.apply(host, args);
121457
121607
  }) :
121458
- (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
121608
+ (function (typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode); });
121459
121609
  var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
121460
121610
  builderProgram = readBuilderProgram(compilerOptions, compilerHost);
121461
121611
  synchronizeProgram();
@@ -122191,9 +122341,9 @@ var ts;
122191
122341
  compilerHost.getModuleResolutionCache = function () { return moduleResolutionCache; };
122192
122342
  }
122193
122343
  if (!compilerHost.resolveTypeReferenceDirectives) {
122194
- var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; };
122195
- compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) {
122196
- return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4);
122344
+ var loader_4 = function (moduleName, containingFile, redirectedReference, containingFileMode) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache, containingFileMode).resolvedTypeReferenceDirective; };
122345
+ compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) {
122346
+ return ts.loadWithTypeDirectiveCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader_4);
122197
122347
  };
122198
122348
  }
122199
122349
  var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
@@ -127519,6 +127669,10 @@ var ts;
127519
127669
  return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore });
127520
127670
  }
127521
127671
  ts.getFormatCodeSettingsForWriting = getFormatCodeSettingsForWriting;
127672
+ function jsxModeNeedsExplicitImport(jsx) {
127673
+ return jsx === 2 /* React */ || jsx === 3 /* ReactNative */;
127674
+ }
127675
+ ts.jsxModeNeedsExplicitImport = jsxModeNeedsExplicitImport;
127522
127676
  // #endregion
127523
127677
  })(ts || (ts = {}));
127524
127678
  /*@internal*/
@@ -129463,9 +129617,18 @@ var ts;
129463
129617
  return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath);
129464
129618
  }
129465
129619
  }
129620
+ function isEmitResolutionKindUsingNodeModules(compilerOptions) {
129621
+ return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ||
129622
+ ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Node12 ||
129623
+ ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeNext;
129624
+ }
129625
+ function isEmitModuleResolutionRespectingExportMaps(compilerOptions) {
129626
+ return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Node12 ||
129627
+ ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeNext;
129628
+ }
129466
129629
  function getSupportedExtensionsForModuleResolution(compilerOptions) {
129467
129630
  var extensions = ts.getSupportedExtensions(compilerOptions);
129468
- return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
129631
+ return isEmitResolutionKindUsingNodeModules(compilerOptions) ?
129469
129632
  ts.getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) :
129470
129633
  extensions;
129471
129634
  }
@@ -129628,7 +129791,7 @@ var ts;
129628
129791
  result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined));
129629
129792
  }
129630
129793
  getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result);
129631
- if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) {
129794
+ if (isEmitResolutionKindUsingNodeModules(compilerOptions)) {
129632
129795
  // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies.
129633
129796
  // (But do if we didn't find anything, e.g. 'package.json' missing.)
129634
129797
  var foundGlobal = false;
@@ -129645,12 +129808,68 @@ var ts;
129645
129808
  }
129646
129809
  }
129647
129810
  if (!foundGlobal) {
129648
- ts.forEachAncestorDirectory(scriptPath, function (ancestor) {
129811
+ var ancestorLookup = function (ancestor) {
129649
129812
  var nodeModules = ts.combinePaths(ancestor, "node_modules");
129650
129813
  if (ts.tryDirectoryExists(host, nodeModules)) {
129651
129814
  getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result);
129652
129815
  }
129653
- });
129816
+ };
129817
+ if (fragmentDirectory && isEmitModuleResolutionRespectingExportMaps(compilerOptions)) {
129818
+ var nodeModulesDirectoryLookup_1 = ancestorLookup;
129819
+ ancestorLookup = function (ancestor) {
129820
+ var components = ts.getPathComponents(fragment);
129821
+ components.shift(); // shift off empty root
129822
+ var packagePath = components.shift();
129823
+ if (!packagePath) {
129824
+ return nodeModulesDirectoryLookup_1(ancestor);
129825
+ }
129826
+ if (ts.startsWith(packagePath, "@")) {
129827
+ var subName = components.shift();
129828
+ if (!subName) {
129829
+ return nodeModulesDirectoryLookup_1(ancestor);
129830
+ }
129831
+ packagePath = ts.combinePaths(packagePath, subName);
129832
+ }
129833
+ var packageFile = ts.combinePaths(ancestor, "node_modules", packagePath, "package.json");
129834
+ if (ts.tryFileExists(host, packageFile)) {
129835
+ var packageJson = ts.readJson(packageFile, host);
129836
+ var exports = packageJson.exports;
129837
+ if (exports) {
129838
+ if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null
129839
+ return; // null exports or entrypoint only, no sub-modules available
129840
+ }
129841
+ var keys = ts.getOwnKeys(exports);
129842
+ var fragmentSubpath_1 = components.join("/");
129843
+ var processedKeys = ts.mapDefined(keys, function (k) {
129844
+ if (k === ".")
129845
+ return undefined;
129846
+ if (!ts.startsWith(k, "./"))
129847
+ return undefined;
129848
+ var subpath = k.substring(2);
129849
+ if (!ts.startsWith(subpath, fragmentSubpath_1))
129850
+ return undefined;
129851
+ // subpath is a valid export (barring conditions, which we don't currently check here)
129852
+ if (!ts.stringContains(subpath, "*")) {
129853
+ return subpath;
129854
+ }
129855
+ // pattern export - only return everything up to the `*`, so the user can autocomplete, then
129856
+ // keep filling in the pattern (we could speculatively return a list of options by hitting disk,
129857
+ // but conditions will make that somewhat awkward, as each condition may have a different set of possible
129858
+ // options for the `*`.
129859
+ return subpath.slice(0, subpath.indexOf("*"));
129860
+ });
129861
+ ts.forEach(processedKeys, function (k) {
129862
+ if (k) {
129863
+ result.push(nameAndKind(k, "external module name" /* externalModuleName */, /*extension*/ undefined));
129864
+ }
129865
+ });
129866
+ return;
129867
+ }
129868
+ }
129869
+ return nodeModulesDirectoryLookup_1(ancestor);
129870
+ };
129871
+ }
129872
+ ts.forEachAncestorDirectory(scriptPath, ancestorLookup);
129654
129873
  }
129655
129874
  }
129656
129875
  return result;
@@ -131092,14 +131311,15 @@ var ts;
131092
131311
  if (tag.tagName.pos <= position && position <= tag.tagName.end) {
131093
131312
  return { kind: 1 /* JsDocTagName */ };
131094
131313
  }
131095
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 307 /* JSDocTypeExpression */) {
131314
+ var typeExpression = tryGetTypeExpressionFromTag(tag);
131315
+ if (typeExpression) {
131096
131316
  currentToken = ts.getTokenAtPosition(sourceFile, position);
131097
131317
  if (!currentToken ||
131098
131318
  (!ts.isDeclarationName(currentToken) &&
131099
131319
  (currentToken.parent.kind !== 345 /* JSDocPropertyTag */ ||
131100
131320
  currentToken.parent.name !== currentToken))) {
131101
131321
  // Use as type location if inside tag's type expression
131102
- insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
131322
+ insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression);
131103
131323
  }
131104
131324
  }
131105
131325
  if (!insideJsDocTagTypeExpression && ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
@@ -131356,10 +131576,19 @@ var ts;
131356
131576
  case 341 /* JSDocTypeTag */:
131357
131577
  case 343 /* JSDocTypedefTag */:
131358
131578
  return true;
131579
+ case 342 /* JSDocTemplateTag */:
131580
+ return !!tag.constraint;
131359
131581
  default:
131360
131582
  return false;
131361
131583
  }
131362
131584
  }
131585
+ function tryGetTypeExpressionFromTag(tag) {
131586
+ if (isTagWithTypeExpression(tag)) {
131587
+ var typeExpression = ts.isJSDocTemplateTag(tag) ? tag.constraint : tag.typeExpression;
131588
+ return typeExpression && typeExpression.kind === 307 /* JSDocTypeExpression */ ? typeExpression : undefined;
131589
+ }
131590
+ return undefined;
131591
+ }
131363
131592
  function getTypeScriptMemberSymbols() {
131364
131593
  // Right of dot member completion list
131365
131594
  completionKind = 2 /* PropertyAccess */;
@@ -134115,7 +134344,7 @@ var ts;
134115
134344
  }
134116
134345
  for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) {
134117
134346
  var ref = _d[_c];
134118
- var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName);
134347
+ var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName, ref.resolutionMode || referencingFile.impliedNodeFormat);
134119
134348
  if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) {
134120
134349
  refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
134121
134350
  }
@@ -137337,7 +137566,7 @@ var ts;
137337
137566
  }
137338
137567
  var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
137339
137568
  if (typeReferenceDirective) {
137340
- var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
137569
+ var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName, typeReferenceDirective.resolutionMode || sourceFile.impliedNodeFormat);
137341
137570
  var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217
137342
137571
  return file && { reference: typeReferenceDirective, fileName: file.fileName, file: file, unverified: false };
137343
137572
  }
@@ -139143,6 +139372,7 @@ var ts;
139143
139372
  return oldImports;
139144
139373
  }
139145
139374
  var typeChecker = program.getTypeChecker();
139375
+ var compilerOptions = program.getCompilerOptions();
139146
139376
  var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
139147
139377
  var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile);
139148
139378
  var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
@@ -139199,7 +139429,7 @@ var ts;
139199
139429
  return usedImports;
139200
139430
  function isDeclarationUsed(identifier) {
139201
139431
  // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
139202
- return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) ||
139432
+ return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) && ts.jsxModeNeedsExplicitImport(compilerOptions.jsx) ||
139203
139433
  ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
139204
139434
  }
139205
139435
  }
@@ -146439,8 +146669,18 @@ var ts;
146439
146669
  var indent = sourceFile.text.slice(startPosition, fnStart);
146440
146670
  this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent });
146441
146671
  };
146672
+ ChangeTracker.prototype.createJSDocText = function (sourceFile, node) {
146673
+ var comments = ts.flatMap(node.jsDoc, function (jsDoc) {
146674
+ return ts.isString(jsDoc.comment) ? ts.factory.createJSDocText(jsDoc.comment) : jsDoc.comment;
146675
+ });
146676
+ var jsDoc = ts.singleOrUndefined(node.jsDoc);
146677
+ return jsDoc && ts.positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && ts.length(comments) === 0 ? undefined :
146678
+ ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n")));
146679
+ };
146680
+ ChangeTracker.prototype.replaceJSDocComment = function (sourceFile, node, tags) {
146681
+ this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), ts.factory.createJSDocComment(this.createJSDocText(sourceFile, node), ts.factory.createNodeArray(tags)));
146682
+ };
146442
146683
  ChangeTracker.prototype.addJSDocTags = function (sourceFile, parent, newTags) {
146443
- var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; });
146444
146684
  var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; });
146445
146685
  var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags.some(function (tag, i) {
146446
146686
  var merged = tryMergeJsdocTags(tag, newTag);
@@ -146448,20 +146688,10 @@ var ts;
146448
146688
  oldTags[i] = merged;
146449
146689
  return !!merged;
146450
146690
  }); });
146451
- var tags = __spreadArray(__spreadArray([], oldTags, true), unmergedNewTags, true);
146452
- var jsDoc = ts.singleOrUndefined(parent.jsDoc);
146453
- var comment = jsDoc && ts.positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && !ts.length(comments) ? undefined :
146454
- ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n")));
146455
- var tag = ts.factory.createJSDocComment(comment, ts.factory.createNodeArray(tags));
146456
- var host = updateJSDocHost(parent);
146457
- this.insertJsdocCommentBefore(sourceFile, host, tag);
146691
+ this.replaceJSDocComment(sourceFile, parent, __spreadArray(__spreadArray([], oldTags, true), unmergedNewTags, true));
146458
146692
  };
146459
146693
  ChangeTracker.prototype.filterJSDocTags = function (sourceFile, parent, predicate) {
146460
- var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; });
146461
- var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; });
146462
- var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray([], (ts.filter(oldTags, predicate) || ts.emptyArray), true)));
146463
- var host = updateJSDocHost(parent);
146464
- this.insertJsdocCommentBefore(sourceFile, host, tag);
146694
+ this.replaceJSDocComment(sourceFile, parent, ts.filter(ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }), predicate));
146465
146695
  };
146466
146696
  ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
146467
146697
  this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text });
@@ -150256,9 +150486,9 @@ var ts;
150256
150486
  var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions));
150257
150487
  var checker = program.getTypeChecker();
150258
150488
  var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker));
150259
- var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, /*isJsxTagName*/ false, host, program, preferences, useAutoImportProvider);
150489
+ var exportInfo = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, /*isJsxTagName*/ false, host, program, preferences, useAutoImportProvider);
150260
150490
  var useRequire = shouldUseRequire(sourceFile, program);
150261
- var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences);
150491
+ var fix = getImportFixForSymbol(sourceFile, exportInfo, moduleSymbol, symbolName, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences);
150262
150492
  if (fix) {
150263
150493
  addImport({ fixes: [fix], symbolName: symbolName, errorIdentifierText: undefined });
150264
150494
  }
@@ -150447,7 +150677,7 @@ var ts;
150447
150677
  function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) {
150448
150678
  ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol || info.symbol.parent === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol");
150449
150679
  var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host);
150450
- return getBestFix(getImportFixes(exportInfos, symbolName, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences), sourceFile, program, packageJsonImportFilter);
150680
+ return getBestFix(getImportFixes(exportInfos, symbolName, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences), sourceFile, program, packageJsonImportFilter, host);
150451
150681
  }
150452
150682
  function codeFixActionToCodeAction(_a) {
150453
150683
  var description = _a.description, changes = _a.changes, commands = _a.commands;
@@ -150507,7 +150737,7 @@ var ts;
150507
150737
  /*position*/ undefined,
150508
150738
  /*isValidTypeOnlyUseSite*/ false,
150509
150739
  /*useRequire*/ false, exportInfo, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount;
150510
- var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host));
150740
+ var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host);
150511
150741
  return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount });
150512
150742
  }
150513
150743
  codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo;
@@ -150677,7 +150907,7 @@ var ts;
150677
150907
  // 5. Literally nothing to go on
150678
150908
  return true;
150679
150909
  }
150680
- function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, moduleSymbols, host, preferences, fromCacheOnly) {
150910
+ function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) {
150681
150911
  var isJs = ts.isSourceFileJS(sourceFile);
150682
150912
  var compilerOptions = program.getCompilerOptions();
150683
150913
  var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host);
@@ -150686,7 +150916,7 @@ var ts;
150686
150916
  ? function (moduleSymbol) { return ({ moduleSpecifiers: ts.moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }); }
150687
150917
  : function (moduleSymbol, checker) { return ts.moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences); };
150688
150918
  var computedWithoutCacheCount = 0;
150689
- var fixes = ts.flatMap(moduleSymbols, function (exportInfo) {
150919
+ var fixes = ts.flatMap(exportInfo, function (exportInfo, i) {
150690
150920
  var checker = getChecker(exportInfo.isFromPackageJson);
150691
150921
  var _a = getModuleSpecifiers(exportInfo.moduleSymbol, checker), computedWithoutCache = _a.computedWithoutCache, moduleSpecifiers = _a.moduleSpecifiers;
150692
150922
  var importedSymbolHasValueMeaning = !!(exportInfo.targetFlags & 111551 /* Value */);
@@ -150695,7 +150925,7 @@ var ts;
150695
150925
  return moduleSpecifiers === null || moduleSpecifiers === void 0 ? void 0 : moduleSpecifiers.map(function (moduleSpecifier) {
150696
150926
  // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
150697
150927
  return !importedSymbolHasValueMeaning && isJs && position !== undefined
150698
- ? { kind: 1 /* JsdocTypeImport */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo }
150928
+ ? { kind: 1 /* JsdocTypeImport */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo, isReExport: i > 0 }
150699
150929
  : {
150700
150930
  kind: 3 /* AddNew */,
150701
150931
  moduleSpecifier: moduleSpecifier,
@@ -150703,6 +150933,7 @@ var ts;
150703
150933
  useRequire: useRequire,
150704
150934
  addAsTypeOnly: addAsTypeOnly,
150705
150935
  exportInfo: exportInfo,
150936
+ isReExport: i > 0,
150706
150937
  };
150707
150938
  });
150708
150939
  });
@@ -150740,12 +150971,13 @@ var ts;
150740
150971
  info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider);
150741
150972
  }
150742
150973
  var packageJsonImportFilter = ts.createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host);
150743
- return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, packageJsonImportFilter) });
150974
+ return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, packageJsonImportFilter, context.host) });
150744
150975
  }
150745
- function sortFixes(fixes, sourceFile, program, packageJsonImportFilter) {
150746
- return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier); });
150976
+ function sortFixes(fixes, sourceFile, program, packageJsonImportFilter, host) {
150977
+ var _toPath = function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); };
150978
+ return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath); });
150747
150979
  }
150748
- function getBestFix(fixes, sourceFile, program, packageJsonImportFilter) {
150980
+ function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) {
150749
150981
  if (!ts.some(fixes))
150750
150982
  return;
150751
150983
  // These will always be placed first if available, and are better than other kinds
@@ -150754,22 +150986,37 @@ var ts;
150754
150986
  }
150755
150987
  return fixes.reduce(function (best, fix) {
150756
150988
  // Takes true branch of conditional if `fix` is better than `best`
150757
- return compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best;
150989
+ return compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }) === -1 /* LessThan */ ? fix : best;
150758
150990
  });
150759
150991
  }
150760
150992
  /** @returns `Comparison.LessThan` if `a` is better than `b`. */
150761
- function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) {
150993
+ function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath) {
150762
150994
  if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) {
150763
150995
  return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier))
150764
150996
  || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program)
150765
- || ts.compareBooleans(isOnlyDotsAndSlashes(a.moduleSpecifier), isOnlyDotsAndSlashes(b.moduleSpecifier))
150997
+ || ts.compareBooleans(isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath), isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath))
150766
150998
  || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier);
150767
150999
  }
150768
151000
  return 0 /* EqualTo */;
150769
151001
  }
150770
- var notDotOrSlashPattern = /[^.\/]/;
150771
- function isOnlyDotsAndSlashes(path) {
150772
- return !notDotOrSlashPattern.test(path);
151002
+ // This is a simple heuristic to try to avoid creating an import cycle with a barrel re-export.
151003
+ // E.g., do not `import { Foo } from ".."` when you could `import { Foo } from "../Foo"`.
151004
+ // This can produce false positives or negatives if re-exports cross into sibling directories
151005
+ // (e.g. `export * from "../whatever"`) or are not named "index" (we don't even try to consider
151006
+ // this if we're in a resolution mode where you can't drop trailing "/index" from paths).
151007
+ function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath) {
151008
+ var _a;
151009
+ if (fix.isReExport &&
151010
+ ((_a = fix.exportInfo) === null || _a === void 0 ? void 0 : _a.moduleFileName) &&
151011
+ ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
151012
+ isIndexFileName(fix.exportInfo.moduleFileName)) {
151013
+ var reExportDir = toPath(ts.getDirectoryPath(fix.exportInfo.moduleFileName));
151014
+ return ts.startsWith((importingFile.path), reExportDir);
151015
+ }
151016
+ return false;
151017
+ }
151018
+ function isIndexFileName(fileName) {
151019
+ return ts.getBaseFileName(fileName, [".js", ".jsx", ".d.ts", ".ts", ".tsx"], /*ignoreCase*/ true) === "index";
150773
151020
  }
150774
151021
  function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) {
150775
151022
  if (ts.startsWith(a, "node:") && !ts.startsWith(b, "node:"))
@@ -150787,9 +151034,9 @@ var ts;
150787
151034
  return undefined;
150788
151035
  var symbol = checker.getAliasedSymbol(umdSymbol);
150789
151036
  var symbolName = umdSymbol.name;
150790
- var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }];
151037
+ var exportInfo = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }];
150791
151038
  var useRequire = shouldUseRequire(sourceFile, program);
150792
- var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences);
151039
+ var fixes = getImportFixes(exportInfo, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences);
150793
151040
  return { fixes: fixes, symbolName: symbolName, errorIdentifierText: (_b = ts.tryCast(token, ts.isIdentifier)) === null || _b === void 0 ? void 0 : _b.text };
150794
151041
  }
150795
151042
  function getUmdSymbol(token, checker) {
@@ -150856,8 +151103,8 @@ var ts;
150856
151103
  ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here");
150857
151104
  var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(symbolToken);
150858
151105
  var useRequire = shouldUseRequire(sourceFile, program);
150859
- var exportInfos = getExportInfos(symbolName, ts.isJSXTagName(symbolToken), ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences);
150860
- var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) {
151106
+ var exportInfo = getExportInfos(symbolName, ts.isJSXTagName(symbolToken), ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences);
151107
+ var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfo.entries(), function (_a) {
150861
151108
  var _ = _a[0], exportInfos = _a[1];
150862
151109
  return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences);
150863
151110
  }));
@@ -150873,12 +151120,9 @@ var ts;
150873
151120
  return undefined;
150874
151121
  return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration: typeOnlyAliasDeclaration };
150875
151122
  }
150876
- function jsxModeNeedsExplicitImport(jsx) {
150877
- return jsx === 2 /* React */ || jsx === 3 /* ReactNative */;
150878
- }
150879
151123
  function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) {
150880
151124
  var parent = symbolToken.parent;
150881
- if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) {
151125
+ if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && ts.jsxModeNeedsExplicitImport(compilerOptions.jsx)) {
150882
151126
  var jsxNamespace = checker.getJsxNamespace(sourceFile);
150883
151127
  if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) {
150884
151128
  return jsxNamespace;
@@ -152958,6 +153202,95 @@ var ts;
152958
153202
  })(ts || (ts = {}));
152959
153203
  /* @internal */
152960
153204
  var ts;
153205
+ (function (ts) {
153206
+ var codefix;
153207
+ (function (codefix) {
153208
+ var deleteUnmatchedParameter = "deleteUnmatchedParameter";
153209
+ var renameUnmatchedParameter = "renameUnmatchedParameter";
153210
+ var errorCodes = [
153211
+ ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code,
153212
+ ];
153213
+ codefix.registerCodeFix({
153214
+ fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter],
153215
+ errorCodes: errorCodes,
153216
+ getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) {
153217
+ var sourceFile = context.sourceFile, span = context.span;
153218
+ var actions = [];
153219
+ var info = getInfo(sourceFile, span.start);
153220
+ if (info) {
153221
+ ts.append(actions, getDeleteAction(context, info));
153222
+ ts.append(actions, getRenameAction(context, info));
153223
+ return actions;
153224
+ }
153225
+ return undefined;
153226
+ },
153227
+ getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) {
153228
+ var tagsToSignature = new ts.Map();
153229
+ return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
153230
+ codefix.eachDiagnostic(context, errorCodes, function (_a) {
153231
+ var file = _a.file, start = _a.start;
153232
+ var info = getInfo(file, start);
153233
+ if (info) {
153234
+ tagsToSignature.set(info.signature, ts.append(tagsToSignature.get(info.signature), info.jsDocParameterTag));
153235
+ }
153236
+ });
153237
+ tagsToSignature.forEach(function (tags, signature) {
153238
+ if (context.fixId === deleteUnmatchedParameter) {
153239
+ var tagsSet_1 = new ts.Set(tags);
153240
+ changes.filterJSDocTags(signature.getSourceFile(), signature, function (t) { return !tagsSet_1.has(t); });
153241
+ }
153242
+ });
153243
+ }));
153244
+ }
153245
+ });
153246
+ function getDeleteAction(context, _a) {
153247
+ var name = _a.name, signature = _a.signature, jsDocParameterTag = _a.jsDocParameterTag;
153248
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) {
153249
+ return changeTracker.filterJSDocTags(context.sourceFile, signature, function (t) { return t !== jsDocParameterTag; });
153250
+ });
153251
+ return codefix.createCodeFixAction(deleteUnmatchedParameter, changes, [ts.Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)], deleteUnmatchedParameter, ts.Diagnostics.Delete_all_unused_param_tags);
153252
+ }
153253
+ function getRenameAction(context, _a) {
153254
+ var name = _a.name, signature = _a.signature, jsDocParameterTag = _a.jsDocParameterTag;
153255
+ if (!ts.length(signature.parameters))
153256
+ return undefined;
153257
+ var sourceFile = context.sourceFile;
153258
+ var tags = ts.getJSDocTags(signature);
153259
+ var names = new ts.Set();
153260
+ for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
153261
+ var tag = tags_2[_i];
153262
+ if (ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name)) {
153263
+ names.add(tag.name.escapedText);
153264
+ }
153265
+ }
153266
+ // @todo - match to all available names instead to the first parameter name
153267
+ // @see /codeFixRenameUnmatchedParameter3.ts
153268
+ var parameterName = ts.firstDefined(signature.parameters, function (p) {
153269
+ return ts.isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : undefined;
153270
+ });
153271
+ if (parameterName === undefined)
153272
+ return undefined;
153273
+ var newJSDocParameterTag = ts.factory.updateJSDocParameterTag(jsDocParameterTag, jsDocParameterTag.tagName, ts.factory.createIdentifier(parameterName), jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, jsDocParameterTag.comment);
153274
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) {
153275
+ return changeTracker.replaceJSDocComment(sourceFile, signature, ts.map(tags, function (t) { return t === jsDocParameterTag ? newJSDocParameterTag : t; }));
153276
+ });
153277
+ return codefix.createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [ts.Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]);
153278
+ }
153279
+ function getInfo(sourceFile, pos) {
153280
+ var token = ts.getTokenAtPosition(sourceFile, pos);
153281
+ if (token.parent && ts.isJSDocParameterTag(token.parent) && ts.isIdentifier(token.parent.name)) {
153282
+ var jsDocParameterTag = token.parent;
153283
+ var signature = ts.getHostSignatureFromJSDoc(jsDocParameterTag);
153284
+ if (signature) {
153285
+ return { signature: signature, name: token.parent.name, jsDocParameterTag: jsDocParameterTag };
153286
+ }
153287
+ }
153288
+ return undefined;
153289
+ }
153290
+ })(codefix = ts.codefix || (ts.codefix = {}));
153291
+ })(ts || (ts = {}));
153292
+ /* @internal */
153293
+ var ts;
152961
153294
  (function (ts) {
152962
153295
  var codefix;
152963
153296
  (function (codefix) {
@@ -164055,7 +164388,7 @@ var ts;
164055
164388
  if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
164056
164389
  this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
164057
164390
  var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217
164058
- return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); });
164391
+ return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, ts.isString(name) ? name : name.fileName.toLowerCase()); });
164059
164392
  };
164060
164393
  }
164061
164394
  }