_lookup_locations,
    transpileOptionValue: void 0
  },
  {
    // this option can only be specified in tsconfig.json
    // use type = object to copy the value as-is
    name: "rootDirs",
    type: "list",
    isTSConfigOnly: true,
    element: {
      name: "rootDirs",
      type: "string",
      isFilePath: true
    },
    affectsModuleResolution: true,
    allowConfigDirTemplateSubstitution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules,
    transpileOptionValue: void 0,
    defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files
  },
  {
    name: "typeRoots",
    type: "list",
    element: {
      name: "typeRoots",
      type: "string",
      isFilePath: true
    },
    affectsModuleResolution: true,
    allowConfigDirTemplateSubstitution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types
  },
  {
    name: "types",
    type: "list",
    element: {
      name: "types",
      type: "string"
    },
    affectsProgramStructure: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file,
    transpileOptionValue: void 0
  },
  {
    name: "allowSyntheticDefaultImports",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export,
    defaultValueDescription: Diagnostics.module_system_or_esModuleInterop
  },
  {
    name: "esModuleInterop",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    showInSimplifiedHelpView: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility,
    defaultValueDescription: false
  },
  {
    name: "preserveSymlinks",
    type: "boolean",
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node,
    defaultValueDescription: false
  },
  {
    name: "allowUmdGlobalAccess",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Allow_accessing_UMD_globals_from_modules,
    defaultValueDescription: false
  },
  {
    name: "moduleSuffixes",
    type: "list",
    element: {
      name: "suffix",
      type: "string"
    },
    listPreserveFalsyValues: true,
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module
  },
  {
    name: "allowImportingTsExtensions",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set,
    defaultValueDescription: false,
    transpileOptionValue: void 0
  },
  {
    name: "rewriteRelativeImportExtensions",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files,
    defaultValueDescription: false
  },
  {
    name: "resolvePackageJsonExports",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports,
    defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false
  },
  {
    name: "resolvePackageJsonImports",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports,
    defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false
  },
  {
    name: "customConditions",
    type: "list",
    element: {
      name: "condition",
      type: "string"
    },
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports
  },
  {
    name: "noUncheckedSideEffectImports",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Check_side_effect_imports,
    defaultValueDescription: false
  },
  // Source Maps
  {
    name: "sourceRoot",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    paramType: Diagnostics.LOCATION,
    category: Diagnostics.Emit,
    description: Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code
  },
  {
    name: "mapRoot",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    paramType: Diagnostics.LOCATION,
    category: Diagnostics.Emit,
    description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations
  },
  {
    name: "inlineSources",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript,
    defaultValueDescription: false
  },
  // Experimental
  {
    name: "experimentalDecorators",
    type: "boolean",
    affectsEmit: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Enable_experimental_support_for_legacy_experimental_decorators,
    defaultValueDescription: false
  },
  {
    name: "emitDecoratorMetadata",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files,
    defaultValueDescription: false
  },
  // Advanced
  {
    name: "jsxFactory",
    type: "string",
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h,
    defaultValueDescription: "`React.createElement`"
  },
  {
    name: "jsxFragmentFactory",
    type: "string",
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment,
    defaultValueDescription: "React.Fragment"
  },
  {
    name: "jsxImportSource",
    type: "string",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsModuleResolution: true,
    affectsSourceFile: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk,
    defaultValueDescription: "react"
  },
  {
    name: "resolveJsonModule",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Enable_importing_json_files,
    defaultValueDescription: false
  },
  {
    name: "allowArbitraryExtensions",
    type: "boolean",
    affectsProgramStructure: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present,
    defaultValueDescription: false
  },
  {
    name: "out",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: false,
    // This is intentionally broken to support compatibility with existing tsconfig files
    // for correct behaviour, please use outFile
    category: Diagnostics.Backwards_Compatibility,
    paramType: Diagnostics.FILE,
    transpileOptionValue: void 0,
    description: Diagnostics.Deprecated_setting_Use_outFile_instead
  },
  {
    name: "reactNamespace",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit,
    defaultValueDescription: "`React`"
  },
  {
    name: "skipDefaultLibCheck",
    type: "boolean",
    // We need to store these to determine whether `lib` files need to be rechecked
    affectsBuildInfo: true,
    category: Diagnostics.Completeness,
    description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript,
    defaultValueDescription: false
  },
  {
    name: "charset",
    type: "string",
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files,
    defaultValueDescription: "utf8"
  },
  {
    name: "emitBOM",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files,
    defaultValueDescription: false
  },
  {
    name: "newLine",
    type: new Map(Object.entries({
      crlf: 0 /* CarriageReturnLineFeed */,
      lf: 1 /* LineFeed */
    })),
    affectsEmit: true,
    affectsBuildInfo: true,
    paramType: Diagnostics.NEWLINE,
    category: Diagnostics.Emit,
    description: Diagnostics.Set_the_newline_character_for_emitting_files,
    defaultValueDescription: "lf"
  },
  {
    name: "noErrorTruncation",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Output_Formatting,
    description: Diagnostics.Disable_truncating_types_in_error_messages,
    defaultValueDescription: false
  },
  {
    name: "noLib",
    type: "boolean",
    category: Diagnostics.Language_and_Environment,
    affectsProgramStructure: true,
    description: Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts,
    // We are not returning a sourceFile for lib file when asked by the program,
    // so pass --noLib to avoid reporting a file not found error.
    transpileOptionValue: true,
    defaultValueDescription: false
  },
  {
    name: "noResolve",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Modules,
    description: Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project,
    // We are not doing a full typecheck, we are not resolving the whole context,
    // so pass --noResolve to avoid reporting missing file errors.
    transpileOptionValue: true,
    defaultValueDescription: false
  },
  {
    name: "stripInternal",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments,
    defaultValueDescription: false
  },
  {
    name: "disableSizeLimit",
    type: "boolean",
    affectsProgramStructure: true,
    category: Diagnostics.Editor_Support,
    description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server,
    defaultValueDescription: false
  },
  {
    name: "disableSourceOfProjectReferenceRedirect",
    type: "boolean",
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects,
    defaultValueDescription: false
  },
  {
    name: "disableSolutionSearching",
    type: "boolean",
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing,
    defaultValueDescription: false
  },
  {
    name: "disableReferencedProjectLoad",
    type: "boolean",
    isTSConfigOnly: true,
    category: Diagnostics.Projects,
    description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript,
    defaultValueDescription: false
  },
  {
    name: "noImplicitUseStrict",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files,
    defaultValueDescription: false
  },
  {
    name: "noEmitHelpers",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output,
    defaultValueDescription: false
  },
  {
    name: "noEmitOnError",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    transpileOptionValue: void 0,
    description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported,
    defaultValueDescription: false
  },
  {
    name: "preserveConstEnums",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Emit,
    description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code,
    defaultValueDescription: false
  },
  {
    name: "declarationDir",
    type: "string",
    affectsEmit: true,
    affectsBuildInfo: true,
    affectsDeclarationPath: true,
    isFilePath: true,
    paramType: Diagnostics.DIRECTORY,
    category: Diagnostics.Emit,
    transpileOptionValue: void 0,
    description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files
  },
  {
    name: "skipLibCheck",
    type: "boolean",
    // We need to store these to determine whether `lib` files need to be rechecked
    affectsBuildInfo: true,
    category: Diagnostics.Completeness,
    description: Diagnostics.Skip_type_checking_all_d_ts_files,
    defaultValueDescription: false
  },
  {
    name: "allowUnusedLabels",
    type: "boolean",
    affectsBindDiagnostics: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Disable_error_reporting_for_unused_labels,
    defaultValueDescription: void 0
  },
  {
    name: "allowUnreachableCode",
    type: "boolean",
    affectsBindDiagnostics: true,
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Type_Checking,
    description: Diagnostics.Disable_error_reporting_for_unreachable_code,
    defaultValueDescription: void 0
  },
  {
    name: "suppressExcessPropertyErrors",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals,
    defaultValueDescription: false
  },
  {
    name: "suppressImplicitAnyIndexErrors",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures,
    defaultValueDescription: false
  },
  {
    name: "forceConsistentCasingInFileNames",
    type: "boolean",
    affectsModuleResolution: true,
    category: Diagnostics.Interop_Constraints,
    description: Diagnostics.Ensure_that_casing_is_correct_in_imports,
    defaultValueDescription: true
  },
  {
    name: "maxNodeModuleJsDepth",
    type: "number",
    affectsModuleResolution: true,
    category: Diagnostics.JavaScript_Support,
    description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs,
    defaultValueDescription: 0
  },
  {
    name: "noStrictGenericChecks",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
    defaultValueDescription: false
  },
  {
    name: "useDefineForClassFields",
    type: "boolean",
    affectsSemanticDiagnostics: true,
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Language_and_Environment,
    description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields,
    defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext
  },
  {
    name: "preserveValueImports",
    type: "boolean",
    affectsEmit: true,
    affectsBuildInfo: true,
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed,
    defaultValueDescription: false
  },
  {
    name: "keyofStringsOnly",
    type: "boolean",
    category: Diagnostics.Backwards_Compatibility,
    description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option,
    defaultValueDescription: false
  },
  {
    // A list of plugins to load in the language service
    name: "plugins",
    type: "list",
    isTSConfigOnly: true,
    element: {
      name: "plugin",
      type: "object"
    },
    description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include,
    category: Diagnostics.Editor_Support
  },
  {
    name: "moduleDetection",
    type: new Map(Object.entries({
      auto: 2 /* Auto */,
      legacy: 1 /* Legacy */,
      force: 3 /* Force */
    })),
    affectsSourceFile: true,
    affectsModuleResolution: true,
    description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files,
    category: Diagnostics.Language_and_Environment,
    defaultValueDescription: Diagnostics.auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules
  },
  {
    name: "ignoreDeprecations",
    type: "string",
    defaultValueDescription: void 0
  }
];
var optionDeclarations = [
  ...commonOptionsWithBuild,
  ...commandOptionsWithoutBuild
];
var semanticDiagnosticsOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsSemanticDiagnostics);
var affectsEmitOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsEmit);
var affectsDeclarationPathOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsDeclarationPath);
var moduleResolutionOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsModuleResolution);
var sourceFileAffectingCompilerOptions = optionDeclarations.filter((option) => !!option.affectsSourceFile || !!option.affectsBindDiagnostics);
var optionsAffectingProgramStructure = optionDeclarations.filter((option) => !!option.affectsProgramStructure);
var transpileOptionValueCompilerOptions = optionDeclarations.filter((option) => hasProperty(option, "transpileOptionValue"));
var configDirTemplateSubstitutionOptions = optionDeclarations.filter(
  (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath
);
var configDirTemplateSubstitutionWatchOptions = optionsForWatch.filter(
  (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath
);
var commandLineOptionOfCustomType = optionDeclarations.filter(isCommandLineOptionOfCustomType);
function isCommandLineOptionOfCustomType(option) {
  return !isString(option.type);
}
var tscBuildOption = {
  name: "build",
  type: "boolean",
  shortName: "b",
  showInSimplifiedHelpView: true,
  category: Diagnostics.Command_line_Options,
  description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date,
  defaultValueDescription: false
};
var optionsForBuild = [
  tscBuildOption,
  {
    name: "verbose",
    shortName: "v",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Enable_verbose_logging,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "dry",
    shortName: "d",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "force",
    shortName: "f",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "clean",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Delete_the_outputs_of_all_projects,
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "stopBuildOnErrors",
    category: Diagnostics.Command_line_Options,
    description: Diagnostics.Skip_building_downstream_projects_on_error_in_upstream_project,
    type: "boolean",
    defaultValueDescription: false
  }
];
var buildOpts = [
  ...commonOptionsWithBuild,
  ...optionsForBuild
];
var typeAcquisitionDeclarations = [
  {
    name: "enable",
    type: "boolean",
    defaultValueDescription: false
  },
  {
    name: "include",
    type: "list",
    element: {
      name: "include",
      type: "string"
    }
  },
  {
    name: "exclude",
    type: "list",
    element: {
      name: "exclude",
      type: "string"
    }
  },
  {
    name: "disableFilenameBasedTypeAcquisition",
    type: "boolean",
    defaultValueDescription: false
  }
];
function createOptionNameMap(optionDeclarations2) {
  const optionsNameMap = /* @__PURE__ */ new Map();
  const shortOptionNames = /* @__PURE__ */ new Map();
  forEach(optionDeclarations2, (option) => {
    optionsNameMap.set(option.name.toLowerCase(), option);
    if (option.shortName) {
      shortOptionNames.set(option.shortName, option.name);
    }
  });
  return { optionsNameMap, shortOptionNames };
}
var optionsNameMapCache;
function getOptionsNameMap() {
  return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(optionDeclarations));
}
var compilerOptionsAlternateMode = {
  diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build,
  getOptionsNameMap: getBuildOptionsNameMap
};
var defaultInitCompilerOptions = {
  module: 1 /* CommonJS */,
  target: 3 /* ES2016 */,
  strict: true,
  esModuleInterop: true,
  forceConsistentCasingInFileNames: true,
  skipLibCheck: true
};
function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
  const namesOfType = arrayFrom(opt.type.keys());
  const stringNames = (opt.deprecatedKeys ? namesOfType.filter((k) => !opt.deprecatedKeys.has(k)) : namesOfType).map((key) => `'${key}'`).join(", ");
  return createDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, stringNames);
}
function parseCustomTypeOption(opt, value, errors) {
  return convertJsonOptionOfCustomType(opt, (value ?? "").trim(), errors);
}
function parseListTypeOption(opt, value = "", errors) {
  value = value.trim();
  if (startsWith(value, "-")) {
    return void 0;
  }
  if (opt.type === "listOrElement" && !value.includes(",")) {
    return validateJsonOptionValue(opt, value, errors);
  }
  if (value === "") {
    return [];
  }
  const values = value.split(",");
  switch (opt.element.type) {
    case "number":
      return mapDefined(values, (v) => validateJsonOptionValue(opt.element, parseInt(v), errors));
    case "string":
      return mapDefined(values, (v) => validateJsonOptionValue(opt.element, v || "", errors));
    case "boolean":
    case "object":
      return Debug.fail(`List of ${opt.element.type} is not yet supported.`);
    default:
      return mapDefined(values, (v) => parseCustomTypeOption(opt.element, v, errors));
  }
}
function getOptionName(option) {
  return option.name;
}
function createUnknownOptionError(unknownOption, diagnostics, unknownOptionErrorText, node, sourceFile) {
  var _a;
  const otherOption = (_a = diagnostics.alternateMode) == null ? void 0 : _a.getOptionsNameMap().optionsNameMap.get(unknownOption.toLowerCase());
  if (otherOption) {
    return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(
      sourceFile,
      node,
      otherOption !== tscBuildOption ? diagnostics.alternateMode.diagnostic : Diagnostics.Option_build_must_be_the_first_command_line_argument,
      unknownOption
    );
  }
  const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
  return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
}
function parseCommandLineWorker(diagnostics, commandLine, readFile) {
  const options = {};
  let watchOptions;
  const fileNames = [];
  const errors = [];
  parseStrings(commandLine);
  return {
    options,
    watchOptions,
    fileNames,
    errors
  };
  function parseStrings(args) {
    let i = 0;
    while (i < args.length) {
      const s = args[i];
      i++;
      if (s.charCodeAt(0) === 64 /* at */) {
        parseResponseFile(s.slice(1));
      } else if (s.charCodeAt(0) === 45 /* minus */) {
        const inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
        const opt = getOptionDeclarationFromName(
          diagnostics.getOptionsNameMap,
          inputOptionName,
          /*allowShort*/
          true
        );
        if (opt) {
          i = parseOptionValue(args, i, diagnostics, opt, options, errors);
        } else {
          const watchOpt = getOptionDeclarationFromName(
            watchOptionsDidYouMeanDiagnostics.getOptionsNameMap,
            inputOptionName,
            /*allowShort*/
            true
          );
          if (watchOpt) {
            i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
          } else {
            errors.push(createUnknownOptionError(inputOptionName, diagnostics, s));
          }
        }
      } else {
        fileNames.push(s);
      }
    }
  }
  function parseResponseFile(fileName) {
    const text = tryReadFile(fileName, readFile || ((fileName2) => sys.readFile(fileName2)));
    if (!isString(text)) {
      errors.push(text);
      return;
    }
    const args = [];
    let pos = 0;
    while (true) {
      while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) pos++;
      if (pos >= text.length) break;
      const start = pos;
      if (text.charCodeAt(start) === 34 /* doubleQuote */) {
        pos++;
        while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) pos++;
        if (pos < text.length) {
          args.push(text.substring(start + 1, pos));
          pos++;
        } else {
          errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
        }
      } else {
        while (text.charCodeAt(pos) > 32 /* space */) pos++;
        args.push(text.substring(start, pos));
      }
    }
    parseStrings(args);
  }
}
function parseOptionValue(args, i, diagnostics, opt, options, errors) {
  if (opt.isTSConfigOnly) {
    const optValue = args[i];
    if (optValue === "null") {
      options[opt.name] = void 0;
      i++;
    } else if (opt.type === "boolean") {
      if (optValue === "false") {
        options[opt.name] = validateJsonOptionValue(
          opt,
          /*value*/
          false,
          errors
        );
        i++;
      } else {
        if (optValue === "true") i++;
        errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name));
      }
    } else {
      errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name));
      if (optValue && !startsWith(optValue, "-")) i++;
    }
  } else {
    if (!args[i] && opt.type !== "boolean") {
      errors.push(createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
    }
    if (args[i] !== "null") {
      switch (opt.type) {
        case "number":
          options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors);
          i++;
          break;
        case "boolean":
          const optValue = args[i];
          options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors);
          if (optValue === "false" || optValue === "true") {
            i++;
          }
          break;
        case "string":
          options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors);
          i++;
          break;
        case "list":
          const result = parseListTypeOption(opt, args[i], errors);
          options[opt.name] = result || [];
          if (result) {
            i++;
          }
          break;
        case "listOrElement":
          Debug.fail("listOrElement not supported here");
          break;
        // If not a primitive, the possible types are specified in what is effectively a map of options.
        default:
          options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
          i++;
          break;
      }
    } else {
      options[opt.name] = void 0;
      i++;
    }
  }
  return i;
}
var compilerOptionsDidYouMeanDiagnostics = {
  alternateMode: compilerOptionsAlternateMode,
  getOptionsNameMap,
  optionDeclarations,
  unknownOptionDiagnostic: Diagnostics.Unknown_compiler_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
  optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument
};
function parseCommandLine(commandLine, readFile) {
  return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
}
function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort = false) {
  optionName = optionName.toLowerCase();
  const { optionsNameMap, shortOptionNames } = getOptionNameMap();
  if (allowShort) {
    const short = shortOptionNames.get(optionName);
    if (short !== void 0) {
      optionName = short;
    }
  }
  return optionsNameMap.get(optionName);
}
var buildOptionsNameMapCache;
function getBuildOptionsNameMap() {
  return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts));
}
var buildOptionsAlternateMode = {
  diagnostic: Diagnostics.Compiler_option_0_may_not_be_used_with_build,
  getOptionsNameMap
};
var buildOptionsDidYouMeanDiagnostics = {
  alternateMode: buildOptionsAlternateMode,
  getOptionsNameMap: getBuildOptionsNameMap,
  optionDeclarations: buildOpts,
  unknownOptionDiagnostic: Diagnostics.Unknown_build_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_build_option_0_Did_you_mean_1,
  optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1
};
function parseBuildCommand(commandLine) {
  const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker(
    buildOptionsDidYouMeanDiagnostics,
    commandLine
  );
  const buildOptions = options;
  if (projects.length === 0) {
    projects.push(".");
  }
  if (buildOptions.clean && buildOptions.force) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
  }
  if (buildOptions.clean && buildOptions.verbose) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
  }
  if (buildOptions.clean && buildOptions.watch) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
  }
  if (buildOptions.watch && buildOptions.dry) {
    errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
  }
  return { buildOptions, watchOptions, projects, errors };
}
function getDiagnosticText(message, ...args) {
  return cast(createCompilerDiagnostic(message, ...args).messageText, isString);
}
function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
  const configFileText = tryReadFile(configFileName, (fileName) => host.readFile(fileName));
  if (!isString(configFileText)) {
    host.onUnRecoverableConfigFileDiagnostic(configFileText);
    return void 0;
  }
  const result = parseJsonText(configFileName, configFileText);
  const cwd = host.getCurrentDirectory();
  result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames));
  result.resolvedPath = result.path;
  result.originalFileName = result.fileName;
  return parseJsonSourceFileConfigFileContent(
    result,
    host,
    getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd),
    optionsToExtend,
    getNormalizedAbsolutePath(configFileName, cwd),
    /*resolutionStack*/
    void 0,
    extraFileExtensions,
    extendedConfigCache,
    watchOptionsToExtend
  );
}
function parseConfigFileTextToJson(fileName, jsonText) {
  const jsonSourceFile = parseJsonText(fileName, jsonText);
  return {
    config: convertConfigFileToObject(
      jsonSourceFile,
      jsonSourceFile.parseDiagnostics,
      /*jsonConversionNotifier*/
      void 0
    ),
    error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : void 0
  };
}
function readJsonConfigFile(fileName, readFile) {
  const textOrDiagnostic = tryReadFile(fileName, readFile);
  return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] };
}
function tryReadFile(fileName, readFile) {
  let text;
  try {
    text = readFile(fileName);
  } catch (e) {
    return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
  }
  return text === void 0 ? createCompilerDiagnostic(Diagnostics.Cannot_read_file_0, fileName) : text;
}
function commandLineOptionsToMap(options) {
  return arrayToMap(options, getOptionName);
}
var typeAcquisitionDidYouMeanDiagnostics = {
  optionDeclarations: typeAcquisitionDeclarations,
  unknownOptionDiagnostic: Diagnostics.Unknown_type_acquisition_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1
};
var watchOptionsNameMapCache;
function getWatchOptionsNameMap() {
  return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(optionsForWatch));
}
var watchOptionsDidYouMeanDiagnostics = {
  getOptionsNameMap: getWatchOptionsNameMap,
  optionDeclarations: optionsForWatch,
  unknownOptionDiagnostic: Diagnostics.Unknown_watch_option_0,
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
  optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1
};
var commandLineCompilerOptionsMapCache;
function getCommandLineCompilerOptionsMap() {
  return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(optionDeclarations));
}
var commandLineWatchOptionsMapCache;
function getCommandLineWatchOptionsMap() {
  return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(optionsForWatch));
}
var commandLineTypeAcquisitionMapCache;
function getCommandLineTypeAcquisitionMap() {
  return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(typeAcquisitionDeclarations));
}
var extendsOptionDeclaration = {
  name: "extends",
  type: "listOrElement",
  element: {
    name: "extends",
    type: "string"
  },
  category: Diagnostics.File_Management,
  disallowNullOrUndefined: true
};
var compilerOptionsDeclaration = {
  name: "compilerOptions",
  type: "object",
  elementOptions: getCommandLineCompilerOptionsMap(),
  extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics
};
var watchOptionsDeclaration = {
  name: "watchOptions",
  type: "object",
  elementOptions: getCommandLineWatchOptionsMap(),
  extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics
};
var typeAcquisitionDeclaration = {
  name: "typeAcquisition",
  type: "object",
  elementOptions: getCommandLineTypeAcquisitionMap(),
  extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
};
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
  if (_tsconfigRootOptions === void 0) {
    _tsconfigRootOptions = {
      name: void 0,
      // should never be needed since this is root
      type: "object",
      elementOptions: commandLineOptionsToMap([
        compilerOptionsDeclaration,
        watchOptionsDeclaration,
        typeAcquisitionDeclaration,
        extendsOptionDeclaration,
        {
          name: "references",
          type: "list",
          element: {
            name: "references",
            type: "object"
          },
          category: Diagnostics.Projects
        },
        {
          name: "files",
          type: "list",
          element: {
            name: "files",
            type: "string"
          },
          category: Diagnostics.File_Management
        },
        {
          name: "include",
          type: "list",
          element: {
            name: "include",
            type: "string"
          },
          category: Diagnostics.File_Management,
          defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk
        },
        {
          name: "exclude",
          type: "list",
          element: {
            name: "exclude",
            type: "string"
          },
          category: Diagnostics.File_Management,
          defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified
        },
        compileOnSaveCommandLineOption
      ])
    };
  }
  return _tsconfigRootOptions;
}
function convertConfigFileToObject(sourceFile, errors, jsonConversionNotifier) {
  var _a;
  const rootExpression = (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression;
  if (rootExpression && rootExpression.kind !== 210 /* ObjectLiteralExpression */) {
    errors.push(createDiagnosticForNodeInSourceFile(
      sourceFile,
      rootExpression,
      Diagnostics.The_root_value_of_a_0_file_must_be_an_object,
      getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json"
    ));
    if (isArrayLiteralExpression(rootExpression)) {
      const firstObject = find(rootExpression.elements, isObjectLiteralExpression);
      if (firstObject) {
        return convertToJson(
          sourceFile,
          firstObject,
          errors,
          /*returnValue*/
          true,
          jsonConversionNotifier
        );
      }
    }
    return {};
  }
  return convertToJson(
    sourceFile,
    rootExpression,
    errors,
    /*returnValue*/
    true,
    jsonConversionNotifier
  );
}
function convertToObject(sourceFile, errors) {
  var _a;
  return convertToJson(
    sourceFile,
    (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression,
    errors,
    /*returnValue*/
    true,
    /*jsonConversionNotifier*/
    void 0
  );
}
function convertToJson(sourceFile, rootExpression, errors, returnValue, jsonConversionNotifier) {
  if (!rootExpression) {
    return returnValue ? {} : void 0;
  }
  return convertPropertyValueToJson(rootExpression, jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.rootOptions);
  function convertObjectLiteralExpressionToJson(node, objectOption) {
    var _a;
    const result = returnValue ? {} : void 0;
    for (const element of node.properties) {
      if (element.kind !== 303 /* PropertyAssignment */) {
        errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element, Diagnostics.Property_assignment_expected));
        continue;
      }
      if (element.questionToken) {
        errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
      }
      if (!isDoubleQuotedString(element.name)) {
        errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, Diagnostics.String_literal_with_double_quotes_expected));
      }
      const textOfKey = isComputedNonLiteralName(element.name) ? void 0 : getTextOfPropertyName(element.name);
      const keyText = textOfKey && unescapeLeadingUnderscores(textOfKey);
      const option = keyText ? (_a = objectOption == null ? void 0 : objectOption.elementOptions) == null ? void 0 : _a.get(keyText) : void 0;
      const value = convertPropertyValueToJson(element.initializer, option);
      if (typeof keyText !== "undefined") {
        if (returnValue) {
          result[keyText] = value;
        }
        jsonConversionNotifier == null ? void 0 : jsonConversionNotifier.onPropertySet(keyText, value, element, objectOption, option);
      }
    }
    return result;
  }
  function convertArrayLiteralExpressionToJson(elements, elementOption) {
    if (!returnValue) {
      elements.forEach((element) => convertPropertyValueToJson(element, elementOption));
      return void 0;
    }
    return filter(elements.map((element) => convertPropertyValueToJson(element, elementOption)), (v) => v !== void 0);
  }
  function convertPropertyValueToJson(valueExpression, option) {
    switch (valueExpression.kind) {
      case 112 /* TrueKeyword */:
        return true;
      case 97 /* FalseKeyword */:
        return false;
      case 106 /* NullKeyword */:
        return null;
      // eslint-disable-line no-restricted-syntax
      case 11 /* StringLiteral */:
        if (!isDoubleQuotedString(valueExpression)) {
          errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected));
        }
        return valueExpression.text;
      case 9 /* NumericLiteral */:
        return Number(valueExpression.text);
      case 224 /* PrefixUnaryExpression */:
        if (valueExpression.operator !== 41 /* MinusToken */ || valueExpression.operand.kind !== 9 /* NumericLiteral */) {
          break;
        }
        return -Number(valueExpression.operand.text);
      case 210 /* ObjectLiteralExpression */:
        const objectLiteralExpression = valueExpression;
        return convertObjectLiteralExpressionToJson(objectLiteralExpression, option);
      case 209 /* ArrayLiteralExpression */:
        return convertArrayLiteralExpressionToJson(
          valueExpression.elements,
          option && option.element
        );
    }
    if (option) {
      errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
    } else {
      errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal));
    }
    return void 0;
  }
  function isDoubleQuotedString(node) {
    return isStringLiteral(node) && isStringDoubleQuoted(node, sourceFile);
  }
}
function getCompilerOptionValueTypeString(option) {
  return option.type === "listOrElement" ? `${getCompilerOptionValueTypeString(option.element)} or Array` : option.type === "list" ? "Array" : isString(option.type) ? option.type : "string";
}
function isCompilerOptionsValue(option, value) {
  if (option) {
    if (isNullOrUndefined(value)) return !option.disallowNullOrUndefined;
    if (option.type === "list") {
      return isArray(value);
    }
    if (option.type === "listOrElement") {
      return isArray(value) || isCompilerOptionsValue(option.element, value);
    }
    const expectedType = isString(option.type) ? option.type : "string";
    return typeof value === expectedType;
  }
  return false;
}
function convertToTSConfig(configParseResult, configFileName, host) {
  var _a, _b, _c;
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  const files = map(
    filter(
      configParseResult.fileNames,
      !((_b = (_a = configParseResult.options.configFile) == null ? void 0 : _a.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs(
        configFileName,
        configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs,
        configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs,
        host
      )
    ),
    (f) => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName)
  );
  const pathOptions = { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames };
  const optionMap = serializeCompilerOptions(configParseResult.options, pathOptions);
  const watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
  const config = {
    compilerOptions: {
      ...optionMapToObject(optionMap),
      showConfig: void 0,
      configFile: void 0,
      configFilePath: void 0,
      help: void 0,
      init: void 0,
      listFiles: void 0,
      listEmittedFiles: void 0,
      project: void 0,
      build: void 0,
      version: void 0
    },
    watchOptions: watchOptionMap && optionMapToObject(watchOptionMap),
    references: map(configParseResult.projectReferences, (r) => ({ ...r, path: r.originalPath ? r.originalPath : "", originalPath: void 0 })),
    files: length(files) ? files : void 0,
    ...((_c = configParseResult.options.configFile) == null ? void 0 : _c.configFileSpecs) ? {
      include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs),
      exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs
    } : {},
    compileOnSave: !!configParseResult.compileOnSave ? true : void 0
  };
  const providedKeys = new Set(optionMap.keys());
  const impliedCompilerOptions = {};
  for (const option in computedOptions) {
    if (!providedKeys.has(option) && optionDependsOn(option, providedKeys)) {
      const implied = computedOptions[option].computeValue(configParseResult.options);
      const defaultValue = computedOptions[option].computeValue({});
      if (implied !== defaultValue) {
        impliedCompilerOptions[option] = computedOptions[option].computeValue(configParseResult.options);
      }
    }
  }
  assign(config.compilerOptions, optionMapToObject(serializeCompilerOptions(impliedCompilerOptions, pathOptions)));
  return config;
}
function optionDependsOn(option, dependsOn) {
  const seen = /* @__PURE__ */ new Set();
  return optionDependsOnRecursive(option);
  function optionDependsOnRecursive(option2) {
    var _a;
    if (addToSeen(seen, option2)) {
      return some((_a = computedOptions[option2]) == null ? void 0 : _a.dependencies, (dep) => dependsOn.has(dep) || optionDependsOnRecursive(dep));
    }
    return false;
  }
}
function optionMapToObject(optionMap) {
  return Object.fromEntries(optionMap);
}
function filterSameAsDefaultInclude(specs) {
  if (!length(specs)) return void 0;
  if (length(specs) !== 1) return specs;
  if (specs[0] === defaultIncludeSpec) return void 0;
  return specs;
}
function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
  if (!includeSpecs) return returnTrue;
  const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
  const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
  const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
  if (includeRe) {
    if (excludeRe) {
      return (path2) => !(includeRe.test(path2) && !excludeRe.test(path2));
    }
    return (path2) => !includeRe.test(path2);
  }
  if (excludeRe) {
    return (path2) => excludeRe.test(path2);
  }
  return returnTrue;
}
function getCustomTypeMapOfCommandLineOption(optionDefinition) {
  switch (optionDefinition.type) {
    case "string":
    case "number":
    case "boolean":
    case "object":
      return void 0;
    case "list":
    case "listOrElement":
      return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
    default:
      return optionDefinition.type;
  }
}
function getNameOfCompilerOptionValue(value, customTypeMap) {
  return forEachEntry(customTypeMap, (mapValue, key) => {
    if (mapValue === value) {
      return key;
    }
  });
}
function serializeCompilerOptions(options, pathOptions) {
  return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
}
function serializeWatchOptions(options) {
  return serializeOptionBaseObject(options, getWatchOptionsNameMap());
}
function serializeOptionBaseObject(options, { optionsNameMap }, pathOptions) {
  const result = /* @__PURE__ */ new Map();
  const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
  for (const name in options) {
    if (hasProperty(options, name)) {
      if (optionsNameMap.has(name) && (optionsNameMap.get(name).category === Diagnostics.Command_line_Options || optionsNameMap.get(name).category === Diagnostics.Output_Formatting)) {
        continue;
      }
      const value = options[name];
      const optionDefinition = optionsNameMap.get(name.toLowerCase());
      if (optionDefinition) {
        Debug.assert(optionDefinition.type !== "listOrElement");
        const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
        if (!customTypeMap) {
          if (pathOptions && optionDefinition.isFilePath) {
            result.set(name, getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(value, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
          } else if (pathOptions && optionDefinition.type === "list" && optionDefinition.element.isFilePath) {
            result.set(name, value.map((v) => getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(v, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName)));
          } else {
            result.set(name, value);
          }
        } else {
          if (optionDefinition.type === "list") {
            result.set(name, value.map((element) => getNameOfCompilerOptionValue(element, customTypeMap)));
          } else {
            result.set(name, getNameOfCompilerOptionValue(value, customTypeMap));
          }
        }
      }
    }
  }
  return result;
}
function getCompilerOptionsDiffValue(options, newLine) {
  const compilerOptionsMap = getSerializedCompilerOption(options);
  return getOverwrittenDefaultOptions();
  function makePadding(paddingLength) {
    return Array(paddingLength + 1).join(" ");
  }
  function getOverwrittenDefaultOptions() {
    const result = [];
    const tab = makePadding(2);
    commandOptionsWithoutBuild.forEach((cmd) => {
      if (!compilerOptionsMap.has(cmd.name)) {
        return;
      }
      const newValue = compilerOptionsMap.get(cmd.name);
      const defaultValue = getDefaultValueForOption(cmd);
      if (newValue !== defaultValue) {
        result.push(`${tab}${cmd.name}: ${newValue}`);
      } else if (hasProperty(defaultInitCompilerOptions, cmd.name)) {
        result.push(`${tab}${cmd.name}: ${defaultValue}`);
      }
    });
    return result.join(newLine) + newLine;
  }
}
function getSerializedCompilerOption(options) {
  const compilerOptions = extend(options, defaultInitCompilerOptions);
  return serializeCompilerOptions(compilerOptions);
}
function generateTSConfig(options, fileNames, newLine) {
  const compilerOptionsMap = getSerializedCompilerOption(options);
  return writeConfigurations();
  function makePadding(paddingLength) {
    return Array(paddingLength + 1).join(" ");
  }
  function isAllowedOptionForOutput({ category, name, isCommandLineOnly }) {
    const categoriesToSkip = [Diagnostics.Command_line_Options, Diagnostics.Editor_Support, Diagnostics.Compiler_Diagnostics, Diagnostics.Backwards_Compatibility, Diagnostics.Watch_and_Build_Modes, Diagnostics.Output_Formatting];
    return !isCommandLineOnly && category !== void 0 && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name));
  }
  function writeConfigurations() {
    const categorizedOptions = /* @__PURE__ */ new Map();
    categorizedOptions.set(Diagnostics.Projects, []);
    categorizedOptions.set(Diagnostics.Language_and_Environment, []);
    categorizedOptions.set(Diagnostics.Modules, []);
    categorizedOptions.set(Diagnostics.JavaScript_Support, []);
    categorizedOptions.set(Diagnostics.Emit, []);
    categorizedOptions.set(Diagnostics.Interop_Constraints, []);
    categorizedOptions.set(Diagnostics.Type_Checking, []);
    categorizedOptions.set(Diagnostics.Completeness, []);
    for (const option of optionDeclarations) {
      if (isAllowedOptionForOutput(option)) {
        let listForCategory = categorizedOptions.get(option.category);
        if (!listForCategory) categorizedOptions.set(option.category, listForCategory = []);
        listForCategory.push(option);
      }
    }
    let marginLength = 0;
    let seenKnownKeys = 0;
    const entries = [];
    categorizedOptions.forEach((options2, category) => {
      if (entries.length !== 0) {
        entries.push({ value: "" });
      }
      entries.push({ value: `/* ${getLocaleSpecificMessage(category)} */` });
      for (const option of options2) {
        let optionName;
        if (compilerOptionsMap.has(option.name)) {
          optionName = `"${option.name}": ${JSON.stringify(compilerOptionsMap.get(option.name))}${(seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","}`;
        } else {
          optionName = `// "${option.name}": ${JSON.stringify(getDefaultValueForOption(option))},`;
        }
        entries.push({
          value: optionName,
          description: `/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */`
        });
        marginLength = Math.max(optionName.length, marginLength);
      }
    });
    const tab = makePadding(2);
    const result = [];
    result.push(`{`);
    result.push(`${tab}"compilerOptions": {`);
    result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`);
    result.push("");
    for (const entry of entries) {
      const { value, description = "" } = entry;
      result.push(value && `${tab}${tab}${value}${description && makePadding(marginLength - value.length + 2) + description}`);
    }
    if (fileNames.length) {
      result.push(`${tab}},`);
      result.push(`${tab}"files": [`);
      for (let i = 0; i < fileNames.length; i++) {
        result.push(`${tab}${tab}${JSON.stringify(fileNames[i])}${i === fileNames.length - 1 ? "" : ","}`);
      }
      result.push(`${tab}]`);
    } else {
      result.push(`${tab}}`);
    }
    result.push(`}`);
    return result.join(newLine) + newLine;
  }
}
function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
  const result = {};
  const optionsNameMap = getOptionsNameMap().optionsNameMap;
  for (const name in options) {
    if (hasProperty(options, name)) {
      result[name] = convertToOptionValueWithAbsolutePaths(
        optionsNameMap.get(name.toLowerCase()),
        options[name],
        toAbsolutePath
      );
    }
  }
  if (result.configFilePath) {
    result.configFilePath = toAbsolutePath(result.configFilePath);
  }
  return result;
}
function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
  if (option && !isNullOrUndefined(value)) {
    if (option.type === "list") {
      const values = value;
      if (option.element.isFilePath && values.length) {
        return values.map(toAbsolutePath);
      }
    } else if (option.isFilePath) {
      return toAbsolutePath(value);
    }
    Debug.assert(option.type !== "listOrElement");
  }
  return value;
}
function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
  var _a, _b;
  (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName });
  const result = parseJsonConfigFileContentWorker(
    /*json*/
    void 0,
    sourceFile,
    host,
    basePath,
    existingOptions,
    existingWatchOptions,
    configFileName,
    resolutionStack,
    extraFileExtensions,
    extendedConfigCache
  );
  (_b = tracing) == null ? void 0 : _b.pop();
  return result;
}
function setConfigFileInOptions(options, configFile) {
  if (configFile) {
    Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
  }
}
function isNullOrUndefined(x) {
  return x === void 0 || x === null;
}
function directoryOfCombinedPath(fileName, basePath) {
  return getDirectoryPath(getNormalizedAbsolutePath(fileName, basePath));
}
var defaultIncludeSpec = "**/*";
function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions = {}, existingWatchOptions, configFileName, resolutionStack = [], extraFileExtensions = [], extendedConfigCache) {
  Debug.assert(json === void 0 && sourceFile !== void 0 || json !== void 0 && sourceFile === void 0);
  const errors = [];
  const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
  const { raw } = parsedConfig;
  const options = handleOptionConfigDirTemplateSubstitution(
    extend(existingOptions, parsedConfig.options || {}),
    configDirTemplateSubstitutionOptions,
    basePath
  );
  const watchOptions = handleWatchOptionsConfigDirTemplateSubstitution(
    existingWatchOptions && parsedConfig.watchOptions ? extend(existingWatchOptions, parsedConfig.watchOptions) : parsedConfig.watchOptions || existingWatchOptions,
    basePath
  );
  options.configFilePath = configFileName && normalizeSlashes(configFileName);
  const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath);
  const configFileSpecs = getConfigFileSpecs();
  if (sourceFile) sourceFile.configFileSpecs = configFileSpecs;
  setConfigFileInOptions(options, sourceFile);
  return {
    options,
    watchOptions,
    fileNames: getFileNames(basePathForFileNames),
    projectReferences: getProjectReferences(basePathForFileNames),
    typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
    raw,
    errors,
    // Wildcard directories (provided as part of a wildcard path) are stored in a
    // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
    // or a recursive directory. This information is used by filesystem watchers to monitor for
    // new entries in these paths.
    wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames),
    compileOnSave: !!raw.compileOnSave
  };
  function getConfigFileSpecs() {
    const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object");
    const filesSpecs = toPropValue(getSpecsFromRaw("files"));
    if (filesSpecs) {
      const hasZeroOrNoReferences = referencesOfRaw === "no-prop" || isArray(referencesOfRaw) && referencesOfRaw.length === 0;
      const hasExtends = hasProperty(raw, "extends");
      if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
        if (sourceFile) {
          const fileName = configFileName || "tsconfig.json";
          const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty;
          const nodeValue = forEachTsConfigPropArray(sourceFile, "files", (property) => property.initializer);
          const error = createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnosticMessage, fileName);
          errors.push(error);
        } else {
          createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
        }
      }
    }
    let includeSpecs = toPropValue(getSpecsFromRaw("include"));
    const excludeOfRaw = getSpecsFromRaw("exclude");
    let isDefaultIncludeSpec = false;
    let excludeSpecs = toPropValue(excludeOfRaw);
    if (excludeOfRaw === "no-prop") {
      const outDir = options.outDir;
      const declarationDir = options.declarationDir;
      if (outDir || declarationDir) {
        excludeSpecs = filter([outDir, declarationDir], (d) => !!d);
      }
    }
    if (filesSpecs === void 0 && includeSpecs === void 0) {
      includeSpecs = [defaultIncludeSpec];
      isDefaultIncludeSpec = true;
    }
    let validatedIncludeSpecsBeforeSubstitution, validatedExcludeSpecsBeforeSubstitution;
    let validatedIncludeSpecs, validatedExcludeSpecs;
    if (includeSpecs) {
      validatedIncludeSpecsBeforeSubstitution = validateSpecs(
        includeSpecs,
        errors,
        /*disallowTrailingRecursion*/
        true,
        sourceFile,
        "include"
      );
      validatedIncludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate(
        validatedIncludeSpecsBeforeSubstitution,
        basePathForFileNames
      ) || validatedIncludeSpecsBeforeSubstitution;
    }
    if (excludeSpecs) {
      validatedExcludeSpecsBeforeSubstitution = validateSpecs(
        excludeSpecs,
        errors,
        /*disallowTrailingRecursion*/
        false,
        sourceFile,
        "exclude"
      );
      validatedExcludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate(
        validatedExcludeSpecsBeforeSubstitution,
        basePathForFileNames
      ) || validatedExcludeSpecsBeforeSubstitution;
    }
    const validatedFilesSpecBeforeSubstitution = filter(filesSpecs, isString);
    const validatedFilesSpec = getSubstitutedStringArrayWithConfigDirTemplate(
      validatedFilesSpecBeforeSubstitution,
      basePathForFileNames
    ) || validatedFilesSpecBeforeSubstitution;
    return {
      filesSpecs,
      includeSpecs,
      excludeSpecs,
      validatedFilesSpec,
      validatedIncludeSpecs,
      validatedExcludeSpecs,
      validatedFilesSpecBeforeSubstitution,
      validatedIncludeSpecsBeforeSubstitution,
      validatedExcludeSpecsBeforeSubstitution,
      isDefaultIncludeSpec
    };
  }
  function getFileNames(basePath2) {
    const fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath2, options, host, extraFileExtensions);
    if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) {
      errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
    }
    return fileNames;
  }
  function getProjectReferences(basePath2) {
    let projectReferences;
    const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object");
    if (isArray(referencesOfRaw)) {
      for (const ref of referencesOfRaw) {
        if (typeof ref.path !== "string") {
          createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
        } else {
          (projectReferences || (projectReferences = [])).push({
            path: getNormalizedAbsolutePath(ref.path, basePath2),
            originalPath: ref.path,
            prepend: ref.prepend,
            circular: ref.circular
          });
        }
      }
    }
    return projectReferences;
  }
  function toPropValue(specResult) {
    return isArray(specResult) ? specResult : void 0;
  }
  function getSpecsFromRaw(prop) {
    return getPropFromRaw(prop, isString, "string");
  }
  function getPropFromRaw(prop, validateElement, elementTypeName) {
    if (hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
      if (isArray(raw[prop])) {
        const result = raw[prop];
        if (!sourceFile && !every(result, validateElement)) {
          errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
        }
        return result;
      } else {
        createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
        return "not-array";
      }
    }
    return "no-prop";
  }
  function createCompilerDiagnosticOnlyIfJson(message, ...args) {
    if (!sourceFile) {
      errors.push(createCompilerDiagnostic(message, ...args));
    }
  }
}
function handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, basePath) {
  return handleOptionConfigDirTemplateSubstitution(watchOptions, configDirTemplateSubstitutionWatchOptions, basePath);
}
function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, basePath) {
  if (!options) return options;
  let result;
  for (const option of optionDeclarations2) {
    if (options[option.name] !== void 0) {
      const value = options[option.name];
      switch (option.type) {
        case "string":
          Debug.assert(option.isFilePath);
          if (startsWithConfigDirTemplate(value)) {
            setOptionValue(option, getSubstitutedPathWithConfigDirTemplate(value, basePath));
          }
          break;
        case "list":
          Debug.assert(option.element.isFilePath);
          const listResult = getSubstitutedStringArrayWithConfigDirTemplate(value, basePath);
          if (listResult) setOptionValue(option, listResult);
          break;
        case "object":
          Debug.assert(option.name === "paths");
          const objectResult = getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(value, basePath);
          if (objectResult) setOptionValue(option, objectResult);
          break;
        default:
          Debug.fail("option type not supported");
      }
    }
  }
  return result || options;
  function setOptionValue(option, value) {
    (result ?? (result = assign({}, options)))[option.name] = value;
  }
}
var configDirTemplate = `\${configDir}`;
function startsWithConfigDirTemplate(value) {
  return isString(value) && startsWith(
    value,
    configDirTemplate,
    /*ignoreCase*/
    true
  );
}
function getSubstitutedPathWithConfigDirTemplate(value, basePath) {
  return getNormalizedAbsolutePath(value.replace(configDirTemplate, "./"), basePath);
}
function getSubstitutedStringArrayWithConfigDirTemplate(list, basePath) {
  if (!list) return list;
  let result;
  list.forEach((element, index) => {
    if (!startsWithConfigDirTemplate(element)) return;
    (result ?? (result = list.slice()))[index] = getSubstitutedPathWithConfigDirTemplate(element, basePath);
  });
  return result;
}
function getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(mapLike, basePath) {
  let result;
  const ownKeys = getOwnKeys(mapLike);
  ownKeys.forEach((key) => {
    if (!isArray(mapLike[key])) return;
    const subStitution = getSubstitutedStringArrayWithConfigDirTemplate(mapLike[key], basePath);
    if (!subStitution) return;
    (result ?? (result = assign({}, mapLike)))[key] = subStitution;
  });
  return result;
}
function isErrorNoInputFiles(error) {
  return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
}
function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }, configFileName) {
  return createCompilerDiagnostic(
    Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
    configFileName || "tsconfig.json",
    JSON.stringify(includeSpecs || []),
    JSON.stringify(excludeSpecs || [])
  );
}
function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) {
  return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
}
function isSolutionConfig(config) {
  return !config.fileNames.length && hasProperty(config.raw, "references");
}
function canJsonReportNoInputFiles(raw) {
  return !hasProperty(raw, "files") && !hasProperty(raw, "references");
}
function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
  const existingErrors = configParseDiagnostics.length;
  if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) {
    configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
  } else {
    filterMutate(configParseDiagnostics, (error) => !isErrorNoInputFiles(error));
  }
  return existingErrors !== configParseDiagnostics.length;
}
function isSuccessfulParsedTsconfig(value) {
  return !!value.options;
}
function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
  var _a;
  basePath = normalizeSlashes(basePath);
  const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath);
  if (resolutionStack.includes(resolvedPath)) {
    errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
    return { raw: json || convertToObject(sourceFile, errors) };
  }
  const ownConfig = json ? parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
  if ((_a = ownConfig.options) == null ? void 0 : _a.paths) {
    ownConfig.options.pathsBasePath = basePath;
  }
  if (ownConfig.extendedConfigPath) {
    resolutionStack = resolutionStack.concat([resolvedPath]);
    const result = { options: {} };
    if (isString(ownConfig.extendedConfigPath)) {
      applyExtendedConfig(result, ownConfig.extendedConfigPath);
    } else {
      ownConfig.extendedConfigPath.forEach((extendedConfigPath) => applyExtendedConfig(result, extendedConfigPath));
    }
    if (result.include) ownConfig.raw.include = result.include;
    if (result.exclude) ownConfig.raw.exclude = result.exclude;
    if (result.files) ownConfig.raw.files = result.files;
    if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave;
    if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys());
    ownConfig.options = assign(result.options, ownConfig.options);
    ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assignWatchOptions(result, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions;
  }
  return ownConfig;
  function applyExtendedConfig(result, extendedConfigPath) {
    const extendedConfig = getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result);
    if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
      const extendsRaw = extendedConfig.raw;
      let relativeDifference;
      const setPropertyInResultIfNotUndefined = (propertyName) => {
        if (ownConfig.raw[propertyName]) return;
        if (extendsRaw[propertyName]) {
          result[propertyName] = map(extendsRaw[propertyName], (path) => startsWithConfigDirTemplate(path) || isRootedDiskPath(path) ? path : combinePaths(
            relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))),
            path
          ));
        }
      };
      setPropertyInResultIfNotUndefined("include");
      setPropertyInResultIfNotUndefined("exclude");
      setPropertyInResultIfNotUndefined("files");
      if (extendsRaw.compileOnSave !== void 0) {
        result.compileOnSave = extendsRaw.compileOnSave;
      }
      assign(result.options, extendedConfig.options);
      result.watchOptions = result.watchOptions && extendedConfig.watchOptions ? assignWatchOptions(result, extendedConfig.watchOptions) : result.watchOptions || extendedConfig.watchOptions;
    }
  }
  function assignWatchOptions(result, watchOptions) {
    if (result.watchOptionsCopied) return assign(result.watchOptions, watchOptions);
    result.watchOptionsCopied = true;
    return assign({}, result.watchOptions, watchOptions);
  }
}
function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
  if (hasProperty(json, "excludes")) {
    errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
  }
  const options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
  const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition, basePath, errors, configFileName);
  const watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
  json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
  const extendedConfigPath = json.extends || json.extends === "" ? getExtendsConfigPathOrArray(json.extends, host, basePath, configFileName, errors) : void 0;
  return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath };
}
function getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, valueExpression, sourceFile) {
  let extendedConfigPath;
  const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
  if (isString(value)) {
    extendedConfigPath = getExtendsConfigPath(
      value,
      host,
      newBase,
      errors,
      valueExpression,
      sourceFile
    );
  } else if (isArray(value)) {
    extendedConfigPath = [];
    for (let index = 0; index < value.length; index++) {
      const fileName = value[index];
      if (isString(fileName)) {
        extendedConfigPath = append(
          extendedConfigPath,
          getExtendsConfigPath(
            fileName,
            host,
            newBase,
            errors,
            valueExpression == null ? void 0 : valueExpression.elements[index],
            sourceFile
          )
        );
      } else {
        convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile);
      }
    }
  } else {
    convertJsonOption(extendsOptionDeclaration, value, basePath, errors, propertyAssignment, valueExpression, sourceFile);
  }
  return extendedConfigPath;
}
function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
  const options = getDefaultCompilerOptions(configFileName);
  let typeAcquisition;
  let watchOptions;
  let extendedConfigPath;
  let rootCompilerOptions;
  const rootOptions = getTsconfigRootOptionsMap();
  const json = convertConfigFileToObject(
    sourceFile,
    errors,
    { rootOptions, onPropertySet }
  );
  if (!typeAcquisition) {
    typeAcquisition = getDefaultTypeAcquisition(configFileName);
  }
  if (rootCompilerOptions && json && json.compilerOptions === void 0) {
    errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, getTextOfPropertyName(rootCompilerOptions[0])));
  }
  return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath };
  function onPropertySet(keyText, value, propertyAssignment, parentOption, option) {
    if (option && option !== extendsOptionDeclaration) value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile);
    if (parentOption == null ? void 0 : parentOption.name) {
      if (option) {
        let currentOption;
        if (parentOption === compilerOptionsDeclaration) currentOption = options;
        else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ?? (watchOptions = {});
        else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName));
        else Debug.fail("Unknown option");
        currentOption[option.name] = value;
      } else if (keyText && (parentOption == null ? void 0 : parentOption.extraKeyDiagnostics)) {
        if (parentOption.elementOptions) {
          errors.push(createUnknownOptionError(
            keyText,
            parentOption.extraKeyDiagnostics,
            /*unknownOptionErrorText*/
            void 0,
            propertyAssignment.name,
            sourceFile
          ));
        } else {
          errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, parentOption.extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
        }
      }
    } else if (parentOption === rootOptions) {
      if (option === extendsOptionDeclaration) {
        extendedConfigPath = getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, propertyAssignment.initializer, sourceFile);
      } else if (!option) {
        if (keyText === "excludes") {
          errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
        }
        if (find(commandOptionsWithoutBuild, (opt) => opt.name === keyText)) {
          rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name);
        }
      }
    }
  }
}
function getExtendsConfigPath(extendedConfig, host, basePath, errors, valueExpression, sourceFile) {
  extendedConfig = normalizeSlashes(extendedConfig);
  if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../")) {
    let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath);
    if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json" /* Json */)) {
      extendedConfigPath = `${extendedConfigPath}.json`;
      if (!host.fileExists(extendedConfigPath)) {
        errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig));
        return void 0;
      }
    }
    return extendedConfigPath;
  }
  const resolved = nodeNextJsonConfigResolver(extendedConfig, combinePaths(basePath, "tsconfig.json"), host);
  if (resolved.resolvedModule) {
    return resolved.resolvedModule.resolvedFileName;
  }
  if (extendedConfig === "") {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, "extends"));
  } else {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig));
  }
  return void 0;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result) {
  const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath);
  let value;
  let extendedResult;
  let extendedConfig;
  if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
    ({ extendedResult, extendedConfig } = value);
  } else {
    extendedResult = readJsonConfigFile(extendedConfigPath, (path2) => host.readFile(path2));
    if (!extendedResult.parseDiagnostics.length) {
      extendedConfig = parseConfig(
        /*json*/
        void 0,
        extendedResult,
        host,
        getDirectoryPath(extendedConfigPath),
        getBaseFileName(extendedConfigPath),
        resolutionStack,
        errors,
        extendedConfigCache
      );
    }
    if (extendedConfigCache) {
      extendedConfigCache.set(path, { extendedResult, extendedConfig });
    }
  }
  if (sourceFile) {
    (result.extendedSourceFiles ?? (result.extendedSourceFiles = /* @__PURE__ */ new Set())).add(extendedResult.fileName);
    if (extendedResult.extendedSourceFiles) {
      for (const extenedSourceFile of extendedResult.extendedSourceFiles) {
        result.extendedSourceFiles.add(extenedSourceFile);
      }
    }
  }
  if (extendedResult.parseDiagnostics.length) {
    errors.push(...extendedResult.parseDiagnostics);
    return void 0;
  }
  return extendedConfig;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
  if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) {
    return false;
  }
  const result = convertJsonOption(compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
  return typeof result === "boolean" && result;
}
function getDefaultCompilerOptions(configFileName) {
  const options = configFileName && getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {};
  return options;
}
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
  const options = getDefaultCompilerOptions(configFileName);
  convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, compilerOptionsDidYouMeanDiagnostics, errors);
  if (configFileName) {
    options.configFilePath = normalizeSlashes(configFileName);
  }
  return options;
}
function getDefaultTypeAcquisition(configFileName) {
  return { enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
  const options = getDefaultTypeAcquisition(configFileName);
  convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), jsonOptions, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
  return options;
}
function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
  return convertOptionsFromJson(
    getCommandLineWatchOptionsMap(),
    jsonOptions,
    basePath,
    /*defaultOptions*/
    void 0,
    watchOptionsDidYouMeanDiagnostics,
    errors
  );
}
function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
  if (!jsonOptions) {
    return;
  }
  for (const id in jsonOptions) {
    const opt = optionsNameMap.get(id);
    if (opt) {
      (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
    } else {
      errors.push(createUnknownOptionError(id, diagnostics));
    }
  }
  return defaultOptions;
}
function createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, message, ...args) {
  return sourceFile && node ? createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) : createCompilerDiagnostic(message, ...args);
}
function convertJsonOption(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile) {
  if (opt.isCommandLineOnly) {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment == null ? void 0 : propertyAssignment.name, Diagnostics.Option_0_can_only_be_specified_on_command_line, opt.name));
    return void 0;
  }
  if (isCompilerOptionsValue(opt, value)) {
    const optType = opt.type;
    if (optType === "list" && isArray(value)) {
      return convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile);
    } else if (optType === "listOrElement") {
      return isArray(value) ? convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression, sourceFile) : convertJsonOption(opt.element, value, basePath, errors, propertyAssignment, valueExpression, sourceFile);
    } else if (!isString(opt.type)) {
      return convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile);
    }
    const validatedValue = validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile);
    return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
  } else {
    errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
  }
}
function normalizeNonListOptionValue(option, basePath, value) {
  if (option.isFilePath) {
    value = normalizeSlashes(value);
    value = !startsWithConfigDirTemplate(value) ? getNormalizedAbsolutePath(value, basePath) : value;
    if (value === "") {
      value = ".";
    }
  }
  return value;
}
function validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile) {
  var _a;
  if (isNullOrUndefined(value)) return void 0;
  const d = (_a = opt.extraValidation) == null ? void 0 : _a.call(opt, value);
  if (!d) return value;
  errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d));
  return void 0;
}
function convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile) {
  if (isNullOrUndefined(value)) return void 0;
  const key = value.toLowerCase();
  const val = opt.type.get(key);
  if (val !== void 0) {
    return validateJsonOptionValue(opt, val, errors, valueExpression, sourceFile);
  } else {
    errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args) => createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args)));
  }
}
function convertJsonOptionOfListType(option, values, basePath, errors, propertyAssignment, valueExpression, sourceFile) {
  return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), (v) => option.listPreserveFalsyValues ? true : !!v);
}
var invalidTrailingRecursionPattern = /(?:^|\/)\*\*\/?$/;
var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions = emptyArray) {
  basePath = normalizePath(basePath);
  const keyMapper = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
  const literalFileMap = /* @__PURE__ */ new Map();
  const wildcardFileMap = /* @__PURE__ */ new Map();
  const wildCardJsonFileMap = /* @__PURE__ */ new Map();
  const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = configFileSpecs;
  const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);
  const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
  if (validatedFilesSpec) {
    for (const fileName of validatedFilesSpec) {
      const file = getNormalizedAbsolutePath(fileName, basePath);
      literalFileMap.set(keyMapper(file), file);
    }
  }
  let jsonOnlyIncludeRegexes;
  if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
    for (const file of host.readDirectory(
      basePath,
      flatten(supportedExtensionsWithJsonIfResolveJsonModule),
      validatedExcludeSpecs,
      validatedIncludeSpecs,
      /*depth*/
      void 0
    )) {
      if (fileExtensionIs(file, ".json" /* Json */)) {
        if (!jsonOnlyIncludeRegexes) {
          const includes = validatedIncludeSpecs.filter((s) => endsWith(s, ".json" /* Json */));
          const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), (pattern) => `^${pattern}$`);
          jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray;
        }
        const includeIndex = findIndex(jsonOnlyIncludeRegexes, (re) => re.test(file));
        if (includeIndex !== -1) {
          const key2 = keyMapper(file);
          if (!literalFileMap.has(key2) && !wildCardJsonFileMap.has(key2)) {
            wildCardJsonFileMap.set(key2, file);
          }
        }
        continue;
      }
      if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
        continue;
      }
      removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
      const key = keyMapper(file);
      if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
        wildcardFileMap.set(key, file);
      }
    }
  }
  const literalFiles = arrayFrom(literalFileMap.values());
  const wildcardFiles = arrayFrom(wildcardFileMap.values());
  return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values()));
}
function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) {
  const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec;
  if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false;
  basePath = normalizePath(basePath);
  const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2);
  if (validatedFilesSpec) {
    for (const fileName of validatedFilesSpec) {
      if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false;
    }
  }
  return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath);
}
function invalidDotDotAfterRecursiveWildcard(s) {
  const wildcardIndex = startsWith(s, "**/") ? 0 : s.indexOf("/**/");
  if (wildcardIndex === -1) {
    return false;
  }
  const lastDotIndex = endsWith(s, "/..") ? s.length : s.lastIndexOf("/../");
  return lastDotIndex > wildcardIndex;
}
function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) {
  return matchesExcludeWorker(
    pathToCheck,
    filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)),
    useCaseSensitiveFileNames2,
    currentDirectory
  );
}
function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) {
  const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude");
  const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2);
  if (!excludeRegex) return false;
  if (excludeRegex.test(pathToCheck)) return true;
  return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck));
}
function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) {
  return specs.filter((spec) => {
    if (!isString(spec)) return false;
    const diag2 = specToDiagnostic(spec, disallowTrailingRecursion);
    if (diag2 !== void 0) {
      errors.push(createDiagnostic(...diag2));
    }
    return diag2 === void 0;
  });
  function createDiagnostic(message, spec) {
    const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
    return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile, element, message, spec);
  }
}
function specToDiagnostic(spec, disallowTrailingRecursion) {
  Debug.assert(typeof spec === "string");
  if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
    return [Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
  } else if (invalidDotDotAfterRecursiveWildcard(spec)) {
    return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
  }
}
function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, basePath, useCaseSensitiveFileNames2) {
  const rawExcludeRegex = getRegularExpressionForWildcard(exclude, basePath, "exclude");
  const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i");
  const wildcardDirectories = {};
  const wildCardKeyToPath = /* @__PURE__ */ new Map();
  if (include !== void 0) {
    const recursiveKeys = [];
    for (const file of include) {
      const spec = normalizePath(combinePaths(basePath, file));
      if (excludeRegex && excludeRegex.test(spec)) {
        continue;
      }
      const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2);
      if (match) {
        const { key, path, flags } = match;
        const existingPath = wildCardKeyToPath.get(key);
        const existingFlags = existingPath !== void 0 ? wildcardDirectories[existingPath] : void 0;
        if (existingFlags === void 0 || existingFlags < flags) {
          wildcardDirectories[existingPath !== void 0 ? existingPath : path] = flags;
          if (existingPath === void 0) wildCardKeyToPath.set(key, path);
          if (flags === 1 /* Recursive */) {
            recursiveKeys.push(key);
          }
        }
      }
    }
    for (const path in wildcardDirectories) {
      if (hasProperty(wildcardDirectories, path)) {
        for (const recursiveKey of recursiveKeys) {
          const key = toCanonicalKey(path, useCaseSensitiveFileNames2);
          if (key !== recursiveKey && containsPath(recursiveKey, key, basePath, !useCaseSensitiveFileNames2)) {
            delete wildcardDirectories[path];
          }
        }
      }
    }
  }
  return wildcardDirectories;
}
function toCanonicalKey(path, useCaseSensitiveFileNames2) {
  return useCaseSensitiveFileNames2 ? path : toFileNameLowerCase(path);
}
function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2) {
  const match = wildcardDirectoryPattern.exec(spec);
  if (match) {
    const questionWildcardIndex = spec.indexOf("?");
    const starWildcardIndex = spec.indexOf("*");
    const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator);
    return {
      key: toCanonicalKey(match[0], useCaseSensitiveFileNames2),
      path: match[0],
      flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */
    };
  }
  if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) {
    const path = removeTrailingDirectorySeparator(spec);
    return {
      key: toCanonicalKey(path, useCaseSensitiveFileNames2),
      path,
      flags: 1 /* Recursive */
    };
  }
  return void 0;
}
function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
  const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0);
  if (!extensionGroup) {
    return false;
  }
  for (const ext of extensionGroup) {
    if (fileExtensionIs(file, ext) && (ext !== ".ts" /* Ts */ || !fileExtensionIs(file, ".d.ts" /* Dts */))) {
      return false;
    }
    const higherPriorityPath = keyMapper(changeExtension(file, ext));
    if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
      if (ext === ".d.ts" /* Dts */ && (fileExtensionIs(file, ".js" /* Js */) || fileExtensionIs(file, ".jsx" /* Jsx */))) {
        continue;
      }
      return true;
    }
  }
  return false;
}
function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
  const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0);
  if (!extensionGroup) {
    return;
  }
  for (let i = extensionGroup.length - 1; i >= 0; i--) {
    const ext = extensionGroup[i];
    if (fileExtensionIs(file, ext)) {
      return;
    }
    const lowerPriorityPath = keyMapper(changeExtension(file, ext));
    wildcardFiles.delete(lowerPriorityPath);
  }
}
function getDefaultValueForOption(option) {
  switch (option.type) {
    case "number":
      return 1;
    case "boolean":
      return true;
    case "string":
      const defaultValue = option.defaultValueDescription;
      return option.isFilePath ? `./${defaultValue && typeof defaultValue === "string" ? defaultValue : ""}` : "";
    case "list":
      return [];
    case "listOrElement":
      return getDefaultValueForOption(option.element);
    case "object":
      return {};
    default:
      const value = firstOrUndefinedIterator(option.type.keys());
      if (value !== void 0) return value;
      return Debug.fail("Expected 'option.type' to have entries.");
  }
}

// src/compiler/moduleNameResolver.ts
function trace(host, message, ...args) {
  host.trace(formatMessage(message, ...args));
}
function isTraceEnabled(compilerOptions, host) {
  return !!compilerOptions.traceResolution && host.trace !== void 0;
}
function withPackageId(packageInfo, r, state) {
  let packageId;
  if (r && packageInfo) {
    const packageJsonContent = packageInfo.contents.packageJsonContent;
    if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
      packageId = {
        name: packageJsonContent.name,
        subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length),
        version: packageJsonContent.version,
        peerDependencies: getPeerDependenciesOfPackageJsonInfo(packageInfo, state)
      };
    }
  }
  return r && { path: r.path, extension: r.ext, packageId, resolvedUsingTsExtension: r.resolvedUsingTsExtension };
}
function noPackageId(r) {
  return withPackageId(
    /*packageInfo*/
    void 0,
    r,
    /*state*/
    void 0
  );
}
function removeIgnoredPackageId(r) {
  if (r) {
    Debug.assert(r.packageId === void 0);
    return { path: r.path, ext: r.extension, resolvedUsingTsExtension: r.resolvedUsingTsExtension };
  }
}
function formatExtensions(extensions) {
  const result = [];
  if (extensions & 1 /* TypeScript */) result.push("TypeScript");
  if (extensions & 2 /* JavaScript */) result.push("JavaScript");
  if (extensions & 4 /* Declaration */) result.push("Declaration");
  if (extensions & 8 /* Json */) result.push("JSON");
  return result.join(", ");
}
function resolvedTypeScriptOnly(resolved) {
  if (!resolved) {
    return void 0;
  }
  Debug.assert(extensionIsTS(resolved.extension));
  return { fileName: resolved.path, packageId: resolved.packageId };
}
function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, alternateResult) {
  if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) {
    const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled);
    if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath };
  }
  return createResolvedModuleWithFailedLookupLocations(
    resolved,
    isExternalLibraryImport,
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state.resultFromCache,
    cache,
    alternateResult
  );
}
function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache, cache, alternateResult) {
  if (resultFromCache) {
    if (!(cache == null ? void 0 : cache.isReadonly)) {
      resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations);
      resultFromCache.affectingLocations = updateResolutionField(resultFromCache.affectingLocations, affectingLocations);
      resultFromCache.resolutionDiagnostics = updateResolutionField(resultFromCache.resolutionDiagnostics, diagnostics);
      return resultFromCache;
    } else {
      return {
        ...resultFromCache,
        failedLookupLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.failedLookupLocations, failedLookupLocations),
        affectingLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.affectingLocations, affectingLocations),
        resolutionDiagnostics: initializeResolutionFieldForReadonlyCache(resultFromCache.resolutionDiagnostics, diagnostics)
      };
    }
  }
  return {
    resolvedModule: resolved && {
      resolvedFileName: resolved.path,
      originalPath: resolved.originalPath === true ? void 0 : resolved.originalPath,
      extension: resolved.extension,
      isExternalLibraryImport,
      packageId: resolved.packageId,
      resolvedUsingTsExtension: !!resolved.resolvedUsingTsExtension
    },
    failedLookupLocations: initializeResolutionField(failedLookupLocations),
    affectingLocations: initializeResolutionField(affectingLocations),
    resolutionDiagnostics: initializeResolutionField(diagnostics),
    alternateResult
  };
}
function initializeResolutionField(value) {
  return value.length ? value : void 0;
}
function updateResolutionField(to, value) {
  if (!(value == null ? void 0 : value.length)) return to;
  if (!(to == null ? void 0 : to.length)) return value;
  to.push(...value);
  return to;
}
function initializeResolutionFieldForReadonlyCache(fromCache, value) {
  if (!(fromCache == null ? void 0 : fromCache.length)) return initializeResolutionField(value);
  if (!value.length) return fromCache.slice();
  return [...fromCache, ...value];
}
function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
  if (!hasProperty(jsonContent, fieldName)) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName);
    }
    return;
  }
  const value = jsonContent[fieldName];
  if (typeof value !== typeOfTag || value === null) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
    }
    return;
  }
  return value;
}
function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
  const fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
  if (fileName === void 0) {
    return;
  }
  if (!fileName) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_had_a_falsy_0_field, fieldName);
    }
    return;
  }
  const path = normalizePath(combinePaths(baseDirectory, fileName));
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
  }
  return path;
}
function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
  return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
}
function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
  return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
}
function readPackageJsonMainField(jsonContent, baseDirectory, state) {
  return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
}
function readPackageJsonTypesVersionsField(jsonContent, state) {
  const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
  if (typesVersions === void 0) return;
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
  }
  return typesVersions;
}
function readPackageJsonTypesVersionPaths(jsonContent, state) {
  const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
  if (typesVersions === void 0) return;
  if (state.traceEnabled) {
    for (const key in typesVersions) {
      if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) {
        trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
      }
    }
  }
  const result = getPackageJsonTypesVersionsPaths(typesVersions);
  if (!result) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor);
    }
    return;
  }
  const { version: bestVersionKey, paths: bestVersionPaths } = result;
  if (typeof bestVersionPaths !== "object") {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths);
    }
    return;
  }
  return result;
}
var typeScriptVersion;
function getPackageJsonTypesVersionsPaths(typesVersions) {
  if (!typeScriptVersion) typeScriptVersion = new Version(version);
  for (const key in typesVersions) {
    if (!hasProperty(typesVersions, key)) continue;
    const keyRange = VersionRange.tryParse(key);
    if (keyRange === void 0) {
      continue;
    }
    if (keyRange.test(typeScriptVersion)) {
      return { version: key, paths: typesVersions[key] };
    }
  }
}
function getEffectiveTypeRoots(options, host) {
  if (options.typeRoots) {
    return options.typeRoots;
  }
  let currentDirectory;
  if (options.configFilePath) {
    currentDirectory = getDirectoryPath(options.configFilePath);
  } else if (host.getCurrentDirectory) {
    currentDirectory = host.getCurrentDirectory();
  }
  if (currentDirectory !== void 0) {
    return getDefaultTypeRoots(currentDirectory);
  }
}
function getDefaultTypeRoots(currentDirectory) {
  let typeRoots;
  forEachAncestorDirectory(normalizePath(currentDirectory), (directory) => {
    const atTypes = combinePaths(directory, nodeModulesAtTypes);
    (typeRoots ?? (typeRoots = [])).push(atTypes);
  });
  return typeRoots;
}
var nodeModulesAtTypes = combinePaths("node_modules", "@types");
function arePathsEqual(path1, path2, host) {
  const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
  return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */;
}
function getOriginalAndResolvedFileName(fileName, host, traceEnabled) {
  const resolvedFileName = realPath(fileName, host, traceEnabled);
  const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host);
  return {
    // If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames
    resolvedFileName: pathsAreEqual ? fileName : resolvedFileName,
    originalPath: pathsAreEqual ? void 0 : fileName
  };
}
function getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState) {
  const nameForLookup = endsWith(typeRoot, "/node_modules/@types") || endsWith(typeRoot, "/node_modules/@types/") ? mangleScopedPackageNameWithTrace(typeReferenceDirectiveName, moduleResolutionState) : typeReferenceDirectiveName;
  return combinePaths(typeRoot, nameForLookup);
}
function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache, resolutionMode) {
  Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.");
  const traceEnabled = isTraceEnabled(options, host);
  if (redirectedReference) {
    options = redirectedReference.commandLine.options;
  }
  const containingDirectory = containingFile ? getDirectoryPath(containingFile) : void 0;
  let result = containingDirectory ? cache == null ? void 0 : cache.getFromDirectoryCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference) : void 0;
  if (!result && containingDirectory && !isExternalModuleNameRelative(typeReferenceDirectiveName)) {
    result = cache == null ? void 0 : cache.getFromNonRelativeNameCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference);
  }
  if (result) {
    if (traceEnabled) {
      trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile);
      if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
      trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory);
      traceResult(result);
    }
    return result;
  }
  const typeRoots = getEffectiveTypeRoots(options, host);
  if (traceEnabled) {
    if (containingFile === void 0) {
      if (typeRoots === void 0) {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
      } else {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
      }
    } else {
      if (typeRoots === void 0) {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
      } else {
        trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
      }
    }
    if (redirectedReference) {
      trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
    }
  }
  const failedLookupLocations = [];
  const affectingLocations = [];
  let features = getNodeResolutionFeatures(options);
  if (resolutionMode !== void 0) {
    features |= 30 /* AllFeatures */;
  }
  const moduleResolution = getEmitModuleResolutionKind(options);
  if (resolutionMode === 99 /* ESNext */ && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) {
    features |= 32 /* EsmMode */;
  }
  const conditions = features & 8 /* Exports */ ? getConditions(options, resolutionMode) : [];
  const diagnostics = [];
  const moduleResolutionState = {
    compilerOptions: options,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache: cache,
    features,
    conditions,
    requestContainingDirectory: containingDirectory,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  let resolved = primaryLookup();
  let primary = true;
  if (!resolved) {
    resolved = secondaryLookup();
    primary = false;
  }
  let resolvedTypeReferenceDirective;
  if (resolved) {
    const { fileName, packageId } = resolved;
    let resolvedFileName = fileName, originalPath;
    if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled));
    resolvedTypeReferenceDirective = {
      primary,
      resolvedFileName,
      originalPath,
      packageId,
      isExternalLibraryImport: pathContainsNodeModules(fileName)
    };
  }
  result = {
    resolvedTypeReferenceDirective,
    failedLookupLocations: initializeResolutionField(failedLookupLocations),
    affectingLocations: initializeResolutionField(affectingLocations),
    resolutionDiagnostics: initializeResolutionField(diagnostics)
  };
  if (containingDirectory && cache && !cache.isReadonly) {
    cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(
      typeReferenceDirectiveName,
      /*mode*/
      resolutionMode,
      result
    );
    if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
      cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result);
    }
  }
  if (traceEnabled) traceResult(result);
  return result;
  function traceResult(result2) {
    var _a;
    if (!((_a = result2.resolvedTypeReferenceDirective) == null ? void 0 : _a.resolvedFileName)) {
      trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
    } else if (result2.resolvedTypeReferenceDirective.packageId) {
      trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, packageIdToString(result2.resolvedTypeReferenceDirective.packageId), result2.resolvedTypeReferenceDirective.primary);
    } else {
      trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result2.resolvedTypeReferenceDirective.resolvedFileName, result2.resolvedTypeReferenceDirective.primary);
    }
  }
  function primaryLookup() {
    if (typeRoots && typeRoots.length) {
      if (traceEnabled) {
        trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
      }
      return firstDefined(typeRoots, (typeRoot) => {
        const candidate = getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState);
        const directoryExists = directoryProbablyExists(typeRoot, host);
        if (!directoryExists && traceEnabled) {
          trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot);
        }
        if (options.typeRoots) {
          const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState);
          if (resolvedFromFile) {
            const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path);
            const packageInfo = packageDirectory ? getPackageJsonInfo(
              packageDirectory,
              /*onlyRecordFailures*/
              false,
              moduleResolutionState
            ) : void 0;
            return resolvedTypeScriptOnly(withPackageId(packageInfo, resolvedFromFile, moduleResolutionState));
          }
        }
        return resolvedTypeScriptOnly(
          loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState)
        );
      });
    } else {
      if (traceEnabled) {
        trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
      }
    }
  }
  function secondaryLookup() {
    const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
    if (initialLocationForSecondaryLookup !== void 0) {
      let result2;
      if (!options.typeRoots || !endsWith(containingFile, inferredTypesContainingFile)) {
        if (traceEnabled) {
          trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
        }
        if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
          const searchResult = loadModuleFromNearestNodeModulesDirectory(
            4 /* Declaration */,
            typeReferenceDirectiveName,
            initialLocationForSecondaryLookup,
            moduleResolutionState,
            /*cache*/
            void 0,
            /*redirectedReference*/
            void 0
          );
          result2 = searchResult && searchResult.value;
        } else {
          const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName);
          result2 = nodeLoadModuleByRelativeName(
            4 /* Declaration */,
            candidate,
            /*onlyRecordFailures*/
            false,
            moduleResolutionState,
            /*considerPackageJson*/
            true
          );
        }
      } else if (traceEnabled) {
        trace(host, Diagnostics.Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder);
      }
      return resolvedTypeScriptOnly(result2);
    } else {
      if (traceEnabled) {
        trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
      }
    }
  }
}
function getNodeResolutionFeatures(options) {
  let features = 0 /* None */;
  switch (getEmitModuleResolutionKind(options)) {
    case 3 /* Node16 */:
      features = 30 /* Node16Default */;
      break;
    case 99 /* NodeNext */:
      features = 30 /* NodeNextDefault */;
      break;
    case 100 /* Bundler */:
      features = 30 /* BundlerDefault */;
      break;
  }
  if (options.resolvePackageJsonExports) {
    features |= 8 /* Exports */;
  } else if (options.resolvePackageJsonExports === false) {
    features &= ~8 /* Exports */;
  }
  if (options.resolvePackageJsonImports) {
    features |= 2 /* Imports */;
  } else if (options.resolvePackageJsonImports === false) {
    features &= ~2 /* Imports */;
  }
  return features;
}
function getConditions(options, resolutionMode) {
  const moduleResolution = getEmitModuleResolutionKind(options);
  if (resolutionMode === void 0) {
    if (moduleResolution === 100 /* Bundler */) {
      resolutionMode = 99 /* ESNext */;
    } else if (moduleResolution === 2 /* Node10 */) {
      return [];
    }
  }
  const conditions = resolutionMode === 99 /* ESNext */ ? ["import"] : ["require"];
  if (!options.noDtsResolution) {
    conditions.push("types");
  }
  if (moduleResolution !== 100 /* Bundler */) {
    conditions.push("node");
  }
  return concatenate(conditions, options.customConditions);
}
function getAutomaticTypeDirectiveNames(options, host) {
  if (options.types) {
    return options.types;
  }
  const result = [];
  if (host.directoryExists && host.getDirectories) {
    const typeRoots = getEffectiveTypeRoots(options, host);
    if (typeRoots) {
      for (const root of typeRoots) {
        if (host.directoryExists(root)) {
          for (const typeDirectivePath of host.getDirectories(root)) {
            const normalized = normalizePath(typeDirectivePath);
            const packageJsonPath = combinePaths(root, normalized, "package.json");
            const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
            if (!isNotNeededPackage) {
              const baseFileName = getBaseFileName(normalized);
              if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
                result.push(baseFileName);
              }
            }
          }
        }
      }
    }
  }
  return result;
}
function isPackageJsonInfo(entry) {
  return !!(entry == null ? void 0 : entry.contents);
}
function isMissingPackageJsonInfo(entry) {
  return !!entry && !entry.contents;
}
function compilerOptionValueToString(value) {
  var _a;
  if (value === null || typeof value !== "object") {
    return "" + value;
  }
  if (isArray(value)) {
    return `[${(_a = value.map((e) => compilerOptionValueToString(e))) == null ? void 0 : _a.join(",")}]`;
  }
  let str = "{";
  for (const key in value) {
    if (hasProperty(value, key)) {
      str += `${key}: ${compilerOptionValueToString(value[key])}`;
    }
  }
  return str + "}";
}
function getKeyForCompilerOptions(options, affectingOptionDeclarations) {
  return affectingOptionDeclarations.map((option) => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`;
}
function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) {
  const redirectsMap = /* @__PURE__ */ new Map();
  const redirectsKeyToMap = /* @__PURE__ */ new Map();
  let ownMap = /* @__PURE__ */ new Map();
  if (ownOptions) redirectsMap.set(ownOptions, ownMap);
  return {
    getMapOfCacheRedirects,
    getOrCreateMapOfCacheRedirects,
    update,
    clear: clear2,
    getOwnMap: () => ownMap
  };
  function getMapOfCacheRedirects(redirectedReference) {
    return redirectedReference ? getOrCreateMap(
      redirectedReference.commandLine.options,
      /*create*/
      false
    ) : ownMap;
  }
  function getOrCreateMapOfCacheRedirects(redirectedReference) {
    return redirectedReference ? getOrCreateMap(
      redirectedReference.commandLine.options,
      /*create*/
      true
    ) : ownMap;
  }
  function update(newOptions) {
    if (ownOptions !== newOptions) {
      if (ownOptions) ownMap = getOrCreateMap(
        newOptions,
        /*create*/
        true
      );
      else redirectsMap.set(newOptions, ownMap);
      ownOptions = newOptions;
    }
  }
  function getOrCreateMap(redirectOptions, create) {
    let result = redirectsMap.get(redirectOptions);
    if (result) return result;
    const key = getRedirectsCacheKey(redirectOptions);
    result = redirectsKeyToMap.get(key);
    if (!result) {
      if (ownOptions) {
        const ownKey = getRedirectsCacheKey(ownOptions);
        if (ownKey === key) result = ownMap;
        else if (!redirectsKeyToMap.has(ownKey)) redirectsKeyToMap.set(ownKey, ownMap);
      }
      if (create) result ?? (result = /* @__PURE__ */ new Map());
      if (result) redirectsKeyToMap.set(key, result);
    }
    if (result) redirectsMap.set(redirectOptions, result);
    return result;
  }
  function clear2() {
    const ownKey = ownOptions && optionsToRedirectsKey.get(ownOptions);
    ownMap.clear();
    redirectsMap.clear();
    optionsToRedirectsKey.clear();
    redirectsKeyToMap.clear();
    if (ownOptions) {
      if (ownKey) optionsToRedirectsKey.set(ownOptions, ownKey);
      redirectsMap.set(ownOptions, ownMap);
    }
  }
  function getRedirectsCacheKey(options) {
    let result = optionsToRedirectsKey.get(options);
    if (!result) {
      optionsToRedirectsKey.set(options, result = getKeyForCompilerOptions(options, moduleResolutionOptionDeclarations));
    }
    return result;
  }
}
function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) {
  let cache;
  return { getPackageJsonInfo: getPackageJsonInfo2, setPackageJsonInfo, clear: clear2, getInternalMap };
  function getPackageJsonInfo2(packageJsonPath) {
    return cache == null ? void 0 : cache.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName));
  }
  function setPackageJsonInfo(packageJsonPath, info) {
    (cache || (cache = /* @__PURE__ */ new Map())).set(toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info);
  }
  function clear2() {
    cache = void 0;
  }
  function getInternalMap() {
    return cache;
  }
}
function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
  const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
  let result = cache.get(key);
  if (!result) {
    result = create();
    cache.set(key, result);
  }
  return result;
}
function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options, optionsToRedirectsKey) {
  const directoryToModuleNameMap = createCacheWithRedirects(options, optionsToRedirectsKey);
  return {
    getFromDirectoryCache,
    getOrCreateCacheForDirectory,
    clear: clear2,
    update,
    directoryToModuleNameMap
  };
  function clear2() {
    directoryToModuleNameMap.clear();
  }
  function update(options2) {
    directoryToModuleNameMap.update(options2);
  }
  function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
    const path = toPath(directoryName, currentDirectory, getCanonicalFileName);
    return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, () => createModeAwareCache());
  }
  function getFromDirectoryCache(name, mode, directoryName, redirectedReference) {
    var _a, _b;
    const path = toPath(directoryName, currentDirectory, getCanonicalFileName);
    return (_b = (_a = directoryToModuleNameMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(path)) == null ? void 0 : _b.get(name, mode);
  }
}
function createModeAwareCacheKey(specifier, mode) {
  return mode === void 0 ? specifier : `${mode}|${specifier}`;
}
function createModeAwareCache() {
  const underlying = /* @__PURE__ */ new Map();
  const memoizedReverseKeys = /* @__PURE__ */ new Map();
  const cache = {
    get(specifier, mode) {
      return underlying.get(getUnderlyingCacheKey(specifier, mode));
    },
    set(specifier, mode, value) {
      underlying.set(getUnderlyingCacheKey(specifier, mode), value);
      return cache;
    },
    delete(specifier, mode) {
      underlying.delete(getUnderlyingCacheKey(specifier, mode));
      return cache;
    },
    has(specifier, mode) {
      return underlying.has(getUnderlyingCacheKey(specifier, mode));
    },
    forEach(cb) {
      return underlying.forEach((elem, key) => {
        const [specifier, mode] = memoizedReverseKeys.get(key);
        return cb(elem, specifier, mode);
      });
    },
    size() {
      return underlying.size;
    }
  };
  return cache;
  function getUnderlyingCacheKey(specifier, mode) {
    const result = createModeAwareCacheKey(specifier, mode);
    memoizedReverseKeys.set(result, [specifier, mode]);
    return result;
  }
}
function getOriginalOrResolvedModuleFileName(result) {
  return result.resolvedModule && (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
}
function getOriginalOrResolvedTypeReferenceFileName(result) {
  return result.resolvedTypeReferenceDirective && (result.resolvedTypeReferenceDirective.originalPath || result.resolvedTypeReferenceDirective.resolvedFileName);
}
function createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName, optionsToRedirectsKey) {
  const moduleNameToDirectoryMap = createCacheWithRedirects(options, optionsToRedirectsKey);
  return {
    getFromNonRelativeNameCache,
    getOrCreateCacheForNonRelativeName,
    clear: clear2,
    update
  };
  function clear2() {
    moduleNameToDirectoryMap.clear();
  }
  function update(options2) {
    moduleNameToDirectoryMap.update(options2);
  }
  function getFromNonRelativeNameCache(nonRelativeModuleName, mode, directoryName, redirectedReference) {
    var _a, _b;
    Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
    return (_b = (_a = moduleNameToDirectoryMap.getMapOfCacheRedirects(redirectedReference)) == null ? void 0 : _a.get(createModeAwareCacheKey(nonRelativeModuleName, mode))) == null ? void 0 : _b.get(directoryName);
  }
  function getOrCreateCacheForNonRelativeName(nonRelativeModuleName, mode, redirectedReference) {
    Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
    return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, createModeAwareCacheKey(nonRelativeModuleName, mode), createPerModuleNameCache);
  }
  function createPerModuleNameCache() {
    const directoryPathMap = /* @__PURE__ */ new Map();
    return { get, set };
    function get(directory) {
      return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName));
    }
    function set(directory, result) {
      const path = toPath(directory, currentDirectory, getCanonicalFileName);
      if (directoryPathMap.has(path)) {
        return;
      }
      directoryPathMap.set(path, result);
      const resolvedFileName = getResolvedFileName(result);
      const commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
      let current = path;
      while (current !== commonPrefix) {
        const parent = getDirectoryPath(current);
        if (parent === current || directoryPathMap.has(parent)) {
          break;
        }
        directoryPathMap.set(parent, result);
        current = parent;
      }
    }
    function getCommonPrefix(directory, resolution) {
      const resolutionDirectory = toPath(getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
      let i = 0;
      const limit = Math.min(directory.length, resolutionDirectory.length);
      while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
        i++;
      }
      if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === directorySeparator)) {
        return directory;
      }
      const rootLength = getRootLength(directory);
      if (i < rootLength) {
        return void 0;
      }
      const sep = directory.lastIndexOf(directorySeparator, i - 1);
      if (sep === -1) {
        return void 0;
      }
      return directory.substr(0, Math.max(sep, rootLength));
    }
  }
}
function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName, optionsToRedirectsKey) {
  optionsToRedirectsKey ?? (optionsToRedirectsKey = /* @__PURE__ */ new Map());
  const perDirectoryResolutionCache = createPerDirectoryResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    optionsToRedirectsKey
  );
  const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    getResolvedFileName,
    optionsToRedirectsKey
  );
  packageJsonInfoCache ?? (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName));
  return {
    ...packageJsonInfoCache,
    ...perDirectoryResolutionCache,
    ...nonRelativeNameResolutionCache,
    clear: clear2,
    update,
    getPackageJsonInfoCache: () => packageJsonInfoCache,
    clearAllExceptPackageJsonInfoCache,
    optionsToRedirectsKey
  };
  function clear2() {
    clearAllExceptPackageJsonInfoCache();
    packageJsonInfoCache.clear();
  }
  function clearAllExceptPackageJsonInfoCache() {
    perDirectoryResolutionCache.clear();
    nonRelativeNameResolutionCache.clear();
  }
  function update(options2) {
    perDirectoryResolutionCache.update(options2);
    nonRelativeNameResolutionCache.update(options2);
  }
}
function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) {
  const result = createModuleOrTypeReferenceResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    packageJsonInfoCache,
    getOriginalOrResolvedModuleFileName,
    optionsToRedirectsKey
  );
  result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference);
  return result;
}
function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) {
  return createModuleOrTypeReferenceResolutionCache(
    currentDirectory,
    getCanonicalFileName,
    options,
    packageJsonInfoCache,
    getOriginalOrResolvedTypeReferenceFileName,
    optionsToRedirectsKey
  );
}
function getOptionsForLibraryResolution(options) {
  return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution };
}
function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) {
  return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache);
}
function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  if (redirectedReference) {
    compilerOptions = redirectedReference.commandLine.options;
  }
  if (traceEnabled) {
    trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
    if (redirectedReference) {
      trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
    }
  }
  const containingDirectory = getDirectoryPath(containingFile);
  let result = cache == null ? void 0 : cache.getFromDirectoryCache(moduleName, resolutionMode, containingDirectory, redirectedReference);
  if (result) {
    if (traceEnabled) {
      trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
    }
  } else {
    let moduleResolution = compilerOptions.moduleResolution;
    if (moduleResolution === void 0) {
      moduleResolution = getEmitModuleResolutionKind(compilerOptions);
      if (traceEnabled) {
        trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
      }
    } else {
      if (traceEnabled) {
        trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]);
      }
    }
    switch (moduleResolution) {
      case 3 /* Node16 */:
        result = node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
        break;
      case 99 /* NodeNext */:
        result = nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode);
        break;
      case 2 /* Node10 */:
        result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0);
        break;
      case 1 /* Classic */:
        result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
        break;
      case 100 /* Bundler */:
        result = bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode ? getConditions(compilerOptions, resolutionMode) : void 0);
        break;
      default:
        return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`);
    }
    if (cache && !cache.isReadonly) {
      cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result);
      if (!isExternalModuleNameRelative(moduleName)) {
        cache.getOrCreateCacheForNonRelativeName(moduleName, resolutionMode, redirectedReference).set(containingDirectory, result);
      }
    }
  }
  if (traceEnabled) {
    if (result.resolvedModule) {
      if (result.resolvedModule.packageId) {
        trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, packageIdToString(result.resolvedModule.packageId));
      } else {
        trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
      }
    } else {
      trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
    }
  }
  return result;
}
function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
  const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
  if (resolved) return resolved.value;
  if (!isExternalModuleNameRelative(moduleName)) {
    return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
  } else {
    return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
  }
}
function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
  const { baseUrl, paths } = state.compilerOptions;
  if (paths && !pathIsRelative(moduleName)) {
    if (state.traceEnabled) {
      if (baseUrl) {
        trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
      }
      trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
    }
    const baseDirectory = getPathsBasePath(state.compilerOptions, state.host);
    const pathPatterns = tryParsePatterns(paths);
    return tryLoadModuleUsingPaths(
      extensions,
      moduleName,
      baseDirectory,
      paths,
      pathPatterns,
      loader,
      /*onlyRecordFailures*/
      false,
      state
    );
  }
}
function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
  if (!state.compilerOptions.rootDirs) {
    return void 0;
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
  }
  const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
  let matchedRootDir;
  let matchedNormalizedPrefix;
  for (const rootDir of state.compilerOptions.rootDirs) {
    let normalizedRoot = normalizePath(rootDir);
    if (!endsWith(normalizedRoot, directorySeparator)) {
      normalizedRoot += directorySeparator;
    }
    const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === void 0 || matchedNormalizedPrefix.length < normalizedRoot.length);
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
    }
    if (isLongestMatchingPrefix) {
      matchedNormalizedPrefix = normalizedRoot;
      matchedRootDir = rootDir;
    }
  }
  if (matchedNormalizedPrefix) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
    }
    const suffix = candidate.substr(matchedNormalizedPrefix.length);
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
    }
    const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state);
    if (resolvedFileName) {
      return resolvedFileName;
    }
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs);
    }
    for (const rootDir of state.compilerOptions.rootDirs) {
      if (rootDir === matchedRootDir) {
        continue;
      }
      const candidate2 = combinePaths(normalizePath(rootDir), suffix);
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate2);
      }
      const baseDirectory = getDirectoryPath(candidate2);
      const resolvedFileName2 = loader(extensions, candidate2, !directoryProbablyExists(baseDirectory, state.host), state);
      if (resolvedFileName2) {
        return resolvedFileName2;
      }
    }
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed);
    }
  }
  return void 0;
}
function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
  const { baseUrl } = state.compilerOptions;
  if (!baseUrl) {
    return void 0;
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
  }
  const candidate = normalizePath(combinePaths(baseUrl, moduleName));
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
  }
  return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
}
function resolveJSModule(moduleName, initialDir, host) {
  const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host);
  if (!resolvedModule) {
    throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations == null ? void 0 : failedLookupLocations.join(", ")}`);
  }
  return resolvedModule.resolvedFileName;
}
function node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
  return nodeNextModuleNameResolverWorker(
    30 /* Node16Default */,
    moduleName,
    containingFile,
    compilerOptions,
    host,
    cache,
    redirectedReference,
    resolutionMode
  );
}
function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) {
  return nodeNextModuleNameResolverWorker(
    30 /* NodeNextDefault */,
    moduleName,
    containingFile,
    compilerOptions,
    host,
    cache,
    redirectedReference,
    resolutionMode
  );
}
function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode, conditions) {
  const containingDirectory = getDirectoryPath(containingFile);
  const esmMode = resolutionMode === 99 /* ESNext */ ? 32 /* EsmMode */ : 0;
  let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */;
  if (getResolveJsonModule(compilerOptions)) {
    extensions |= 8 /* Json */;
  }
  return nodeModuleNameResolverWorker(
    features | esmMode,
    moduleName,
    containingDirectory,
    compilerOptions,
    host,
    cache,
    extensions,
    /*isConfigLookup*/
    false,
    redirectedReference,
    conditions
  );
}
function tryResolveJSModuleWorker(moduleName, initialDir, host) {
  return nodeModuleNameResolverWorker(
    0 /* None */,
    moduleName,
    initialDir,
    { moduleResolution: 2 /* Node10 */, allowJs: true },
    host,
    /*cache*/
    void 0,
    2 /* JavaScript */,
    /*isConfigLookup*/
    false,
    /*redirectedReference*/
    void 0,
    /*conditions*/
    void 0
  );
}
function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions) {
  const containingDirectory = getDirectoryPath(containingFile);
  let extensions = compilerOptions.noDtsResolution ? 3 /* ImplementationFiles */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */;
  if (getResolveJsonModule(compilerOptions)) {
    extensions |= 8 /* Json */;
  }
  return nodeModuleNameResolverWorker(
    getNodeResolutionFeatures(compilerOptions),
    moduleName,
    containingDirectory,
    compilerOptions,
    host,
    cache,
    extensions,
    /*isConfigLookup*/
    false,
    redirectedReference,
    conditions
  );
}
function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions, isConfigLookup) {
  let extensions;
  if (isConfigLookup) {
    extensions = 8 /* Json */;
  } else if (compilerOptions.noDtsResolution) {
    extensions = 3 /* ImplementationFiles */;
    if (getResolveJsonModule(compilerOptions)) extensions |= 8 /* Json */;
  } else {
    extensions = getResolveJsonModule(compilerOptions) ? 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */ | 8 /* Json */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */;
  }
  return nodeModuleNameResolverWorker(conditions ? 30 /* AllFeatures */ : 0 /* None */, moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, extensions, !!isConfigLookup, redirectedReference, conditions);
}
function nodeNextJsonConfigResolver(moduleName, containingFile, host) {
  return nodeModuleNameResolverWorker(
    30 /* NodeNextDefault */,
    moduleName,
    getDirectoryPath(containingFile),
    { moduleResolution: 99 /* NodeNext */ },
    host,
    /*cache*/
    void 0,
    8 /* Json */,
    /*isConfigLookup*/
    true,
    /*redirectedReference*/
    void 0,
    /*conditions*/
    void 0
  );
}
function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference, conditions) {
  var _a, _b, _c, _d, _e;
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  const failedLookupLocations = [];
  const affectingLocations = [];
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  conditions ?? (conditions = getConditions(
    compilerOptions,
    moduleResolution === 100 /* Bundler */ || moduleResolution === 2 /* Node10 */ ? void 0 : features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */
  ));
  const diagnostics = [];
  const state = {
    compilerOptions,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache: cache,
    features,
    conditions: conditions ?? emptyArray,
    requestContainingDirectory: containingDirectory,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
    trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", state.conditions.map((c) => `'${c}'`).join(", "));
  }
  let result;
  if (moduleResolution === 2 /* Node10 */) {
    const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */);
    const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */);
    result = priorityExtensions && tryResolve(priorityExtensions, state) || secondaryExtensions && tryResolve(secondaryExtensions, state) || void 0;
  } else {
    result = tryResolve(extensions, state);
  }
  let alternateResult;
  if (state.resolvedPackageDirectory && !isConfigLookup && !isExternalModuleNameRelative(moduleName)) {
    const wantedTypesButGotJs = (result == null ? void 0 : result.value) && extensions & (1 /* TypeScript */ | 4 /* Declaration */) && !extensionIsOk(1 /* TypeScript */ | 4 /* Declaration */, result.value.resolved.extension);
    if (((_a = result == null ? void 0 : result.value) == null ? void 0 : _a.isExternalLibraryImport) && wantedTypesButGotJs && features & 8 /* Exports */ && (conditions == null ? void 0 : conditions.includes("import"))) {
      traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update);
      const diagnosticState = {
        ...state,
        features: state.features & ~8 /* Exports */,
        reportDiagnostic: noop
      };
      const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState);
      if ((_b = diagnosticResult == null ? void 0 : diagnosticResult.value) == null ? void 0 : _b.isExternalLibraryImport) {
        alternateResult = diagnosticResult.value.resolved.path;
      }
    } else if ((!(result == null ? void 0 : result.value) || wantedTypesButGotJs) && moduleResolution === 2 /* Node10 */) {
      traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_moduleResolution_bundler_to_see_if_project_may_need_configuration_update);
      const diagnosticsCompilerOptions = { ...state.compilerOptions, moduleResolution: 100 /* Bundler */ };
      const diagnosticState = {
        ...state,
        compilerOptions: diagnosticsCompilerOptions,
        features: 30 /* BundlerDefault */,
        conditions: getConditions(diagnosticsCompilerOptions),
        reportDiagnostic: noop
      };
      const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState);
      if ((_c = diagnosticResult == null ? void 0 : diagnosticResult.value) == null ? void 0 : _c.isExternalLibraryImport) {
        alternateResult = diagnosticResult.value.resolved.path;
      }
    }
  }
  return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
    moduleName,
    (_d = result == null ? void 0 : result.value) == null ? void 0 : _d.resolved,
    (_e = result == null ? void 0 : result.value) == null ? void 0 : _e.isExternalLibraryImport,
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state,
    cache,
    alternateResult
  );
  function tryResolve(extensions2, state2) {
    const loader = (extensions3, candidate, onlyRecordFailures, state3) => nodeLoadModuleByRelativeName(
      extensions3,
      candidate,
      onlyRecordFailures,
      state3,
      /*considerPackageJson*/
      true
    );
    const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions2, moduleName, containingDirectory, loader, state2);
    if (resolved) {
      return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
    }
    if (!isExternalModuleNameRelative(moduleName)) {
      if (features & 2 /* Imports */ && startsWith(moduleName, "#")) {
        const resolved3 = loadModuleFromImports(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference);
        if (resolved3) {
          return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } };
        }
      }
      if (features & 4 /* SelfName */) {
        const resolved3 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference);
        if (resolved3) {
          return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } };
        }
      }
      if (moduleName.includes(":")) {
        if (traceEnabled) {
          trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2));
        }
        return void 0;
      }
      if (traceEnabled) {
        trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2));
      }
      let resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference);
      if (extensions2 & 4 /* Declaration */) {
        resolved2 ?? (resolved2 = resolveFromTypeRoot(moduleName, state2));
      }
      return resolved2 && { value: resolved2.value && { resolved: resolved2.value, isExternalLibraryImport: true } };
    } else {
      const { path: candidate, parts } = normalizePathForCJSResolution(containingDirectory, moduleName);
      const resolved2 = nodeLoadModuleByRelativeName(
        extensions2,
        candidate,
        /*onlyRecordFailures*/
        false,
        state2,
        /*considerPackageJson*/
        true
      );
      return resolved2 && toSearchResult({ resolved: resolved2, isExternalLibraryImport: contains(parts, "node_modules") });
    }
  }
}
function normalizePathForCJSResolution(containingDirectory, moduleName) {
  const combined = combinePaths(containingDirectory, moduleName);
  const parts = getPathComponents(combined);
  const lastPart = lastOrUndefined(parts);
  const path = lastPart === "." || lastPart === ".." ? ensureTrailingDirectorySeparator(normalizePath(combined)) : normalizePath(combined);
  return { path, parts };
}
function realPath(path, host, traceEnabled) {
  if (!host.realpath) {
    return path;
  }
  const real = normalizePath(host.realpath(path));
  if (traceEnabled) {
    trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real);
  }
  return real;
}
function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_types_Colon_1, candidate, formatExtensions(extensions));
  }
  if (!hasTrailingDirectorySeparator(candidate)) {
    if (!onlyRecordFailures) {
      const parentOfCandidate = getDirectoryPath(candidate);
      if (!directoryProbablyExists(parentOfCandidate, state.host)) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
        }
        onlyRecordFailures = true;
      }
    }
    const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
    if (resolvedFromFile) {
      const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : void 0;
      const packageInfo = packageDirectory ? getPackageJsonInfo(
        packageDirectory,
        /*onlyRecordFailures*/
        false,
        state
      ) : void 0;
      return withPackageId(packageInfo, resolvedFromFile, state);
    }
  }
  if (!onlyRecordFailures) {
    const candidateExists = directoryProbablyExists(candidate, state.host);
    if (!candidateExists) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
      }
      onlyRecordFailures = true;
    }
  }
  if (!(state.features & 32 /* EsmMode */)) {
    return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
  }
  return void 0;
}
var nodeModulesPathPart = "/node_modules/";
function pathContainsNodeModules(path) {
  return path.includes(nodeModulesPathPart);
}
function parseNodeModuleFromPath(resolved, isFolder) {
  const path = normalizePath(resolved);
  const idx = path.lastIndexOf(nodeModulesPathPart);
  if (idx === -1) {
    return void 0;
  }
  const indexAfterNodeModules = idx + nodeModulesPathPart.length;
  let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder);
  if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
    indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder);
  }
  return path.slice(0, indexAfterPackageName);
}
function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) {
  const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1);
  return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex;
}
function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
  return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
}
function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
  const resolvedByReplacingExtension = loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
  if (resolvedByReplacingExtension) {
    return resolvedByReplacingExtension;
  }
  if (!(state.features & 32 /* EsmMode */)) {
    const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, "", onlyRecordFailures, state);
    if (resolvedByAddingExtension) {
      return resolvedByAddingExtension;
    }
  }
}
function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state) {
  const filename = getBaseFileName(candidate);
  if (!filename.includes(".")) {
    return void 0;
  }
  let extensionless = removeFileExtension(candidate);
  if (extensionless === candidate) {
    extensionless = candidate.substring(0, candidate.lastIndexOf("."));
  }
  const extension = candidate.substring(extensionless.length);
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
  }
  return tryAddingExtensions(extensionless, extensions, extension, onlyRecordFailures, state);
}
function loadFileNameFromPackageJsonField(extensions, candidate, packageJsonValue, onlyRecordFailures, state) {
  if (extensions & 1 /* TypeScript */ && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || extensions & 4 /* Declaration */ && fileExtensionIsOneOf(candidate, supportedDeclarationExtensions)) {
    const result = tryFile(candidate, onlyRecordFailures, state);
    const ext = tryExtractTSExtension(candidate);
    return result !== void 0 ? { path: candidate, ext, resolvedUsingTsExtension: packageJsonValue ? !endsWith(packageJsonValue, ext) : void 0 } : void 0;
  }
  if (state.isConfigLookup && extensions === 8 /* Json */ && fileExtensionIs(candidate, ".json" /* Json */)) {
    const result = tryFile(candidate, onlyRecordFailures, state);
    return result !== void 0 ? { path: candidate, ext: ".json" /* Json */, resolvedUsingTsExtension: void 0 } : void 0;
  }
  return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state);
}
function tryAddingExtensions(candidate, extensions, originalExtension, onlyRecordFailures, state) {
  if (!onlyRecordFailures) {
    const directory = getDirectoryPath(candidate);
    if (directory) {
      onlyRecordFailures = !directoryProbablyExists(directory, state.host);
    }
  }
  switch (originalExtension) {
    case ".mjs" /* Mjs */:
    case ".mts" /* Mts */:
    case ".d.mts" /* Dmts */:
      return extensions & 1 /* TypeScript */ && tryExtension(".mts" /* Mts */, originalExtension === ".mts" /* Mts */ || originalExtension === ".d.mts" /* Dmts */) || extensions & 4 /* Declaration */ && tryExtension(".d.mts" /* Dmts */, originalExtension === ".mts" /* Mts */ || originalExtension === ".d.mts" /* Dmts */) || extensions & 2 /* JavaScript */ && tryExtension(".mjs" /* Mjs */) || void 0;
    case ".cjs" /* Cjs */:
    case ".cts" /* Cts */:
    case ".d.cts" /* Dcts */:
      return extensions & 1 /* TypeScript */ && tryExtension(".cts" /* Cts */, originalExtension === ".cts" /* Cts */ || originalExtension === ".d.cts" /* Dcts */) || extensions & 4 /* Declaration */ && tryExtension(".d.cts" /* Dcts */, originalExtension === ".cts" /* Cts */ || originalExtension === ".d.cts" /* Dcts */) || extensions & 2 /* JavaScript */ && tryExtension(".cjs" /* Cjs */) || void 0;
    case ".json" /* Json */:
      return extensions & 4 /* Declaration */ && tryExtension(".d.json.ts") || extensions & 8 /* Json */ && tryExtension(".json" /* Json */) || void 0;
    case ".tsx" /* Tsx */:
    case ".jsx" /* Jsx */:
      return extensions & 1 /* TypeScript */ && (tryExtension(".tsx" /* Tsx */, originalExtension === ".tsx" /* Tsx */) || tryExtension(".ts" /* Ts */, originalExtension === ".tsx" /* Tsx */)) || extensions & 4 /* Declaration */ && tryExtension(".d.ts" /* Dts */, originalExtension === ".tsx" /* Tsx */) || extensions & 2 /* JavaScript */ && (tryExtension(".jsx" /* Jsx */) || tryExtension(".js" /* Js */)) || void 0;
    case ".ts" /* Ts */:
    case ".d.ts" /* Dts */:
    case ".js" /* Js */:
    case "":
      return extensions & 1 /* TypeScript */ && (tryExtension(".ts" /* Ts */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */) || tryExtension(".tsx" /* Tsx */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */)) || extensions & 4 /* Declaration */ && tryExtension(".d.ts" /* Dts */, originalExtension === ".ts" /* Ts */ || originalExtension === ".d.ts" /* Dts */) || extensions & 2 /* JavaScript */ && (tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */)) || state.isConfigLookup && tryExtension(".json" /* Json */) || void 0;
    default:
      return extensions & 4 /* Declaration */ && !isDeclarationFileName(candidate + originalExtension) && tryExtension(`.d${originalExtension}.ts`) || void 0;
  }
  function tryExtension(ext, resolvedUsingTsExtension) {
    const path = tryFile(candidate + ext, onlyRecordFailures, state);
    return path === void 0 ? void 0 : { path, ext, resolvedUsingTsExtension: !state.candidateIsFromPackageJsonField && resolvedUsingTsExtension };
  }
}
function tryFile(fileName, onlyRecordFailures, state) {
  var _a;
  if (!((_a = state.compilerOptions.moduleSuffixes) == null ? void 0 : _a.length)) {
    return tryFileLookup(fileName, onlyRecordFailures, state);
  }
  const ext = tryGetExtensionFromPath2(fileName) ?? "";
  const fileNameNoExtension = ext ? removeExtension(fileName, ext) : fileName;
  return forEach(state.compilerOptions.moduleSuffixes, (suffix) => tryFileLookup(fileNameNoExtension + suffix + ext, onlyRecordFailures, state));
}
function tryFileLookup(fileName, onlyRecordFailures, state) {
  var _a;
  if (!onlyRecordFailures) {
    if (state.host.fileExists(fileName)) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.File_0_exists_use_it_as_a_name_resolution_result, fileName);
      }
      return fileName;
    } else {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
      }
    }
  }
  (_a = state.failedLookupLocations) == null ? void 0 : _a.push(fileName);
  return void 0;
}
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson = true) {
  const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : void 0;
  const packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
  const versionPaths = packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state);
  return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths), state);
}
function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) {
  return {
    host,
    compilerOptions: options,
    traceEnabled: isTraceEnabled(options, host),
    failedLookupLocations: void 0,
    affectingLocations: void 0,
    packageJsonInfoCache,
    features: 0 /* None */,
    conditions: emptyArray,
    requestContainingDirectory: void 0,
    reportDiagnostic: noop,
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
}
function getPackageScopeForPath(directory, state) {
  return forEachAncestorDirectoryStoppingAtGlobalCache(
    state.host,
    directory,
    (dir) => getPackageJsonInfo(
      dir,
      /*onlyRecordFailures*/
      false,
      state
    )
  );
}
function getVersionPathsOfPackageJsonInfo(packageJsonInfo, state) {
  if (packageJsonInfo.contents.versionPaths === void 0) {
    packageJsonInfo.contents.versionPaths = readPackageJsonTypesVersionPaths(packageJsonInfo.contents.packageJsonContent, state) || false;
  }
  return packageJsonInfo.contents.versionPaths || void 0;
}
function getPeerDependenciesOfPackageJsonInfo(packageJsonInfo, state) {
  if (packageJsonInfo.contents.peerDependencies === void 0) {
    packageJsonInfo.contents.peerDependencies = readPackageJsonPeerDependencies(packageJsonInfo, state) || false;
  }
  return packageJsonInfo.contents.peerDependencies || void 0;
}
function readPackageJsonPeerDependencies(packageJsonInfo, state) {
  const peerDependencies = readPackageJsonField(packageJsonInfo.contents.packageJsonContent, "peerDependencies", "object", state);
  if (peerDependencies === void 0) return void 0;
  if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field);
  const packageDirectory = realPath(packageJsonInfo.packageDirectory, state.host, state.traceEnabled);
  const nodeModules = packageDirectory.substring(0, packageDirectory.lastIndexOf("node_modules") + "node_modules".length) + directorySeparator;
  let result = "";
  for (const key in peerDependencies) {
    if (hasProperty(peerDependencies, key)) {
      const peerPackageJson = getPackageJsonInfo(
        nodeModules + key,
        /*onlyRecordFailures*/
        false,
        state
      );
      if (peerPackageJson) {
        const version2 = peerPackageJson.contents.packageJsonContent.version;
        result += `+${key}@${version2}`;
        if (state.traceEnabled) trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2);
      } else {
        if (state.traceEnabled) trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key);
      }
    }
  }
  return result;
}
function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
  var _a, _b, _c, _d, _e, _f;
  const { host, traceEnabled } = state;
  const packageJsonPath = combinePaths(packageDirectory, "package.json");
  if (onlyRecordFailures) {
    (_a = state.failedLookupLocations) == null ? void 0 : _a.push(packageJsonPath);
    return void 0;
  }
  const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
  if (existing !== void 0) {
    if (isPackageJsonInfo(existing)) {
      if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
      (_c = state.affectingLocations) == null ? void 0 : _c.push(packageJsonPath);
      return existing.packageDirectory === packageDirectory ? existing : { packageDirectory, contents: existing.contents };
    } else {
      if (existing.directoryExists && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath);
      (_d = state.failedLookupLocations) == null ? void 0 : _d.push(packageJsonPath);
      return void 0;
    }
  }
  const directoryExists = directoryProbablyExists(packageDirectory, host);
  if (directoryExists && host.fileExists(packageJsonPath)) {
    const packageJsonContent = readJson(packageJsonPath, host);
    if (traceEnabled) {
      trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath);
    }
    const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0, peerDependencies: void 0 } };
    if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result);
    (_e = state.affectingLocations) == null ? void 0 : _e.push(packageJsonPath);
    return result;
  } else {
    if (directoryExists && traceEnabled) {
      trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath);
    }
    if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists });
    (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath);
  }
}
function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
  let packageFile;
  if (jsonContent) {
    if (state.isConfigLookup) {
      packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
    } else {
      packageFile = extensions & 4 /* Declaration */ && readPackageJsonTypesFields(jsonContent, candidate, state) || extensions & (3 /* ImplementationFiles */ | 4 /* Declaration */) && readPackageJsonMainField(jsonContent, candidate, state) || void 0;
    }
  }
  const loader = (extensions2, candidate2, onlyRecordFailures2, state2) => {
    const fromFile = loadFileNameFromPackageJsonField(
      extensions2,
      candidate2,
      /*packageJsonValue*/
      void 0,
      onlyRecordFailures2,
      state2
    );
    if (fromFile) {
      return noPackageId(fromFile);
    }
    const expandedExtensions = extensions2 === 4 /* Declaration */ ? 1 /* TypeScript */ | 4 /* Declaration */ : extensions2;
    const features = state2.features;
    const candidateIsFromPackageJsonField = state2.candidateIsFromPackageJsonField;
    state2.candidateIsFromPackageJsonField = true;
    if ((jsonContent == null ? void 0 : jsonContent.type) !== "module") {
      state2.features &= ~32 /* EsmMode */;
    }
    const result = nodeLoadModuleByRelativeName(
      expandedExtensions,
      candidate2,
      onlyRecordFailures2,
      state2,
      /*considerPackageJson*/
      false
    );
    state2.features = features;
    state2.candidateIsFromPackageJsonField = candidateIsFromPackageJsonField;
    return result;
  };
  const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : void 0;
  const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host);
  const indexPath = combinePaths(candidate, state.isConfigLookup ? "tsconfig" : "index");
  if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) {
    const moduleName = getRelativePathFromDirectory(
      candidate,
      packageFile || indexPath,
      /*ignoreCase*/
      false
    );
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName);
    }
    const pathPatterns = tryParsePatterns(versionPaths.paths);
    const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, pathPatterns, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
    if (result) {
      return removeIgnoredPackageId(result.value);
    }
  }
  const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
  if (packageFileResult) return packageFileResult;
  if (!(state.features & 32 /* EsmMode */)) {
    return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
  }
}
function extensionIsOk(extensions, extension) {
  return extensions & 2 /* JavaScript */ && (extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */ || extension === ".mjs" /* Mjs */ || extension === ".cjs" /* Cjs */) || extensions & 1 /* TypeScript */ && (extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".mts" /* Mts */ || extension === ".cts" /* Cts */) || extensions & 4 /* Declaration */ && (extension === ".d.ts" /* Dts */ || extension === ".d.mts" /* Dmts */ || extension === ".d.cts" /* Dcts */) || extensions & 8 /* Json */ && extension === ".json" /* Json */ || false;
}
function parsePackageName(moduleName) {
  let idx = moduleName.indexOf(directorySeparator);
  if (moduleName[0] === "@") {
    idx = moduleName.indexOf(directorySeparator, idx + 1);
  }
  return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
}
function allKeysStartWithDot(obj) {
  return every(getOwnKeys(obj), (k) => startsWith(k, "."));
}
function noKeyStartsWithDot(obj) {
  return !some(getOwnKeys(obj), (k) => startsWith(k, "."));
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
  var _a, _b;
  const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a));
  const scope = getPackageScopeForPath(directoryPath, state);
  if (!scope || !scope.contents.packageJsonContent.exports) {
    return void 0;
  }
  if (typeof scope.contents.packageJsonContent.name !== "string") {
    return void 0;
  }
  const parts = getPathComponents(moduleName);
  const nameParts = getPathComponents(scope.contents.packageJsonContent.name);
  if (!every(nameParts, (p, i) => parts[i] === p)) {
    return void 0;
  }
  const trailingParts = parts.slice(nameParts.length);
  const subpath = !length(trailingParts) ? "." : `.${directorySeparator}${trailingParts.join(directorySeparator)}`;
  if (getAllowJSCompilerOption(state.compilerOptions) && !pathContainsNodeModules(directory)) {
    return loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference);
  }
  const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */);
  const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */);
  return loadModuleFromExports(scope, priorityExtensions, subpath, state, cache, redirectedReference) || loadModuleFromExports(scope, secondaryExtensions, subpath, state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
  if (!scope.contents.packageJsonContent.exports) {
    return void 0;
  }
  if (subpath === ".") {
    let mainExport;
    if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports)) {
      mainExport = scope.contents.packageJsonContent.exports;
    } else if (hasProperty(scope.contents.packageJsonContent.exports, ".")) {
      mainExport = scope.contents.packageJsonContent.exports["."];
    }
    if (mainExport) {
      const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport(
        extensions,
        state,
        cache,
        redirectedReference,
        subpath,
        scope,
        /*isImports*/
        false
      );
      return loadModuleFromTargetExportOrImport(
        mainExport,
        "",
        /*pattern*/
        false,
        "."
      );
    }
  } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
    if (typeof scope.contents.packageJsonContent.exports !== "object") {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
      }
      return toSearchResult(
        /*value*/
        void 0
      );
    }
    const result = loadModuleFromExportsOrImports(
      extensions,
      state,
      cache,
      redirectedReference,
      subpath,
      scope.contents.packageJsonContent.exports,
      scope,
      /*isImports*/
      false
    );
    if (result) {
      return result;
    }
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
  }
  return toSearchResult(
    /*value*/
    void 0
  );
}
function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) {
  var _a, _b;
  if (moduleName === "#" || startsWith(moduleName, "#/")) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
  }
  const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a));
  const scope = getPackageScopeForPath(directoryPath, state);
  if (!scope) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
  }
  if (!scope.contents.packageJsonContent.imports) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
  }
  const result = loadModuleFromExportsOrImports(
    extensions,
    state,
    cache,
    redirectedReference,
    moduleName,
    scope.contents.packageJsonContent.imports,
    scope,
    /*isImports*/
    true
  );
  if (result) {
    return result;
  }
  if (state.traceEnabled) {
    trace(state.host, Diagnostics.Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1, moduleName, scope.packageDirectory);
  }
  return toSearchResult(
    /*value*/
    void 0
  );
}
function comparePatternKeys(a, b) {
  const aPatternIndex = a.indexOf("*");
  const bPatternIndex = b.indexOf("*");
  const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
  const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
  if (baseLenA > baseLenB) return -1 /* LessThan */;
  if (baseLenB > baseLenA) return 1 /* GreaterThan */;
  if (aPatternIndex === -1) return 1 /* GreaterThan */;
  if (bPatternIndex === -1) return -1 /* LessThan */;
  if (a.length > b.length) return -1 /* LessThan */;
  if (b.length > a.length) return 1 /* GreaterThan */;
  return 0 /* EqualTo */;
}
function loadModuleFromExportsOrImports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) {
  const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);
  if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) {
    const target = lookupTable[moduleName];
    return loadModuleFromTargetExportOrImport(
      target,
      /*subpath*/
      "",
      /*pattern*/
      false,
      moduleName
    );
  }
  const expandingKeys = toSorted(filter(getOwnKeys(lookupTable), (k) => hasOneAsterisk(k) || endsWith(k, "/")), comparePatternKeys);
  for (const potentialTarget of expandingKeys) {
    if (state.features & 16 /* ExportsPatternTrailers */ && matchesPatternWithTrailer(potentialTarget, moduleName)) {
      const target = lookupTable[potentialTarget];
      const starPos = potentialTarget.indexOf("*");
      const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos));
      return loadModuleFromTargetExportOrImport(
        target,
        subpath,
        /*pattern*/
        true,
        potentialTarget
      );
    } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) {
      const target = lookupTable[potentialTarget];
      const subpath = moduleName.substring(potentialTarget.length - 1);
      return loadModuleFromTargetExportOrImport(
        target,
        subpath,
        /*pattern*/
        true,
        potentialTarget
      );
    } else if (startsWith(moduleName, potentialTarget)) {
      const target = lookupTable[potentialTarget];
      const subpath = moduleName.substring(potentialTarget.length);
      return loadModuleFromTargetExportOrImport(
        target,
        subpath,
        /*pattern*/
        false,
        potentialTarget
      );
    }
  }
  function matchesPatternWithTrailer(target, name) {
    if (endsWith(target, "*")) return false;
    const starPos = target.indexOf("*");
    if (starPos === -1) return false;
    return startsWith(name, target.substring(0, starPos)) && endsWith(name, target.substring(starPos + 1));
  }
}
function hasOneAsterisk(patternKey) {
  const firstStar = patternKey.indexOf("*");
  return firstStar !== -1 && firstStar === patternKey.lastIndexOf("*");
}
function getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) {
  return loadModuleFromTargetExportOrImport;
  function loadModuleFromTargetExportOrImport(target, subpath, pattern, key) {
    if (typeof target === "string") {
      if (!pattern && subpath.length > 0 && !endsWith(target, "/")) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      if (!startsWith(target, "./")) {
        if (isImports && !startsWith(target, "../") && !startsWith(target, "/") && !isRootedDiskPath(target)) {
          const combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath;
          traceIfEnabled(state, Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup);
          traceIfEnabled(state, Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/");
          const result = nodeModuleNameResolverWorker(
            state.features,
            combinedLookup,
            scope.packageDirectory + "/",
            state.compilerOptions,
            state.host,
            cache,
            extensions,
            /*isConfigLookup*/
            false,
            redirectedReference,
            state.conditions
          );
          return toSearchResult(
            result.resolvedModule ? {
              path: result.resolvedModule.resolvedFileName,
              extension: result.resolvedModule.extension,
              packageId: result.resolvedModule.packageId,
              originalPath: result.resolvedModule.originalPath,
              resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension
            } : void 0
          );
        }
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target);
      const partsAfterFirst = parts.slice(1);
      if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      const resolvedTarget = combinePaths(scope.packageDirectory, target);
      const subpathParts = getPathComponents(subpath);
      if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) {
        if (state.traceEnabled) {
          trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
        }
        return toSearchResult(
          /*value*/
          void 0
        );
      }
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath);
      }
      const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath);
      const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports);
      if (inputLink) return inputLink;
      return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(
        extensions,
        finalPath,
        target,
        /*onlyRecordFailures*/
        false,
        state
      ), state));
    } else if (typeof target === "object" && target !== null) {
      if (!Array.isArray(target)) {
        traceIfEnabled(state, Diagnostics.Entering_conditional_exports);
        for (const condition of getOwnKeys(target)) {
          if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) {
            traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition);
            const subTarget = target[condition];
            const result = loadModuleFromTargetExportOrImport(subTarget, subpath, pattern, key);
            if (result) {
              traceIfEnabled(state, Diagnostics.Resolved_under_condition_0, condition);
              traceIfEnabled(state, Diagnostics.Exiting_conditional_exports);
              return result;
            } else {
              traceIfEnabled(state, Diagnostics.Failed_to_resolve_under_condition_0, condition);
            }
          } else {
            traceIfEnabled(state, Diagnostics.Saw_non_matching_condition_0, condition);
          }
        }
        traceIfEnabled(state, Diagnostics.Exiting_conditional_exports);
        return void 0;
      } else {
        if (!length(target)) {
          if (state.traceEnabled) {
            trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
          }
          return toSearchResult(
            /*value*/
            void 0
          );
        }
        for (const elem of target) {
          const result = loadModuleFromTargetExportOrImport(elem, subpath, pattern, key);
          if (result) {
            return result;
          }
        }
      }
    } else if (target === null) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.package_json_scope_0_explicitly_maps_specifier_1_to_null, scope.packageDirectory, moduleName);
      }
      return toSearchResult(
        /*value*/
        void 0
      );
    }
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
    }
    return toSearchResult(
      /*value*/
      void 0
    );
    function toAbsolutePath(path) {
      var _a, _b;
      if (path === void 0) return path;
      return getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a));
    }
    function combineDirectoryPath(root, dir) {
      return ensureTrailingDirectorySeparator(combinePaths(root, dir));
    }
    function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) {
      var _a, _b, _c, _d;
      if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && !finalPath.includes("/node_modules/") && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) {
        const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) });
        const commonSourceDirGuesses = [];
        if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) {
          const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName));
          commonSourceDirGuesses.push(commonDir);
        } else if (state.requestContainingDirectory) {
          const requestingFile = toAbsolutePath(combinePaths(state.requestContainingDirectory, "index.ts"));
          const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [requestingFile, toAbsolutePath(packagePath)], ((_d = (_c = state.host).getCurrentDirectory) == null ? void 0 : _d.call(_c)) || "", getCanonicalFileName));
          commonSourceDirGuesses.push(commonDir);
          let fragment = ensureTrailingDirectorySeparator(commonDir);
          while (fragment && fragment.length > 1) {
            const parts = getPathComponents(fragment);
            parts.pop();
            const commonDir2 = getPathFromPathComponents(parts);
            commonSourceDirGuesses.unshift(commonDir2);
            fragment = ensureTrailingDirectorySeparator(commonDir2);
          }
        }
        if (commonSourceDirGuesses.length > 1) {
          state.reportDiagnostic(createCompilerDiagnostic(
            isImports2 ? Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate : Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate,
            entry === "" ? "." : entry,
            // replace empty string with `.` - the reverse of the operation done when entries are built - so main entrypoint errors don't look weird
            packagePath
          ));
        }
        for (const commonSourceDirGuess of commonSourceDirGuesses) {
          const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess);
          for (const candidateDir of candidateDirectories) {
            if (containsPath(candidateDir, finalPath, !useCaseSensitiveFileNames(state))) {
              const pathFragment = finalPath.slice(candidateDir.length + 1);
              const possibleInputBase = combinePaths(commonSourceDirGuess, pathFragment);
              const jsAndDtsExtensions = [".mjs" /* Mjs */, ".cjs" /* Cjs */, ".js" /* Js */, ".json" /* Json */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */, ".d.ts" /* Dts */];
              for (const ext of jsAndDtsExtensions) {
                if (fileExtensionIs(possibleInputBase, ext)) {
                  const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase);
                  for (const possibleExt of inputExts) {
                    if (!extensionIsOk(extensions, possibleExt)) continue;
                    const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state));
                    if (state.host.fileExists(possibleInputWithInputExtension)) {
                      return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(
                        extensions,
                        possibleInputWithInputExtension,
                        /*packageJsonValue*/
                        void 0,
                        /*onlyRecordFailures*/
                        false,
                        state
                      ), state));
                    }
                  }
                }
              }
            }
          }
        }
      }
      return void 0;
      function getOutputDirectoriesForBaseDirectory(commonSourceDirGuess) {
        var _a2, _b2;
        const currentDir = state.compilerOptions.configFile ? ((_b2 = (_a2 = state.host).getCurrentDirectory) == null ? void 0 : _b2.call(_a2)) || "" : commonSourceDirGuess;
        const candidateDirectories = [];
        if (state.compilerOptions.declarationDir) {
          candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.declarationDir)));
        }
        if (state.compilerOptions.outDir && state.compilerOptions.outDir !== state.compilerOptions.declarationDir) {
          candidateDirectories.push(toAbsolutePath(combineDirectoryPath(currentDir, state.compilerOptions.outDir)));
        }
        return candidateDirectories;
      }
    }
  }
}
function isApplicableVersionedTypesKey(conditions, key) {
  if (!conditions.includes("types")) return false;
  if (!startsWith(key, "types@")) return false;
  const range = VersionRange.tryParse(key.substring("types@".length));
  if (!range) return false;
  return range.test(version);
}
function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
  return loadModuleFromNearestNodeModulesDirectoryWorker(
    extensions,
    moduleName,
    directory,
    state,
    /*typesScopeOnly*/
    false,
    cache,
    redirectedReference
  );
}
function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
  return loadModuleFromNearestNodeModulesDirectoryWorker(
    4 /* Declaration */,
    moduleName,
    directory,
    state,
    /*typesScopeOnly*/
    true,
    /*cache*/
    void 0,
    /*redirectedReference*/
    void 0
  );
}
function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
  const mode = state.features === 0 ? void 0 : state.features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */;
  const priorityExtensions = extensions & (1 /* TypeScript */ | 4 /* Declaration */);
  const secondaryExtensions = extensions & ~(1 /* TypeScript */ | 4 /* Declaration */);
  if (priorityExtensions) {
    traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0, formatExtensions(priorityExtensions));
    const result = lookup(priorityExtensions);
    if (result) return result;
  }
  if (secondaryExtensions && !typesScopeOnly) {
    traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0, formatExtensions(secondaryExtensions));
    return lookup(secondaryExtensions);
  }
  function lookup(extensions2) {
    return forEachAncestorDirectoryStoppingAtGlobalCache(
      state.host,
      normalizeSlashes(directory),
      (ancestorDirectory) => {
        if (getBaseFileName(ancestorDirectory) !== "node_modules") {
          const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state);
          if (resolutionFromCache) {
            return resolutionFromCache;
          }
          return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions2, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference));
        }
      }
    );
  }
}
function forEachAncestorDirectoryStoppingAtGlobalCache(host, directory, callback) {
  var _a;
  const globalCache = (_a = host == null ? void 0 : host.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(host);
  return forEachAncestorDirectory(directory, (ancestorDirectory) => {
    const result = callback(ancestorDirectory);
    if (result !== void 0) return result;
    if (ancestorDirectory === globalCache) return false;
  }) || void 0;
}
function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
  const nodeModulesFolder = combinePaths(directory, "node_modules");
  const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
  if (!nodeModulesFolderExists && state.traceEnabled) {
    trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
  }
  if (!typesScopeOnly) {
    const packageResult = loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state, cache, redirectedReference);
    if (packageResult) {
      return packageResult;
    }
  }
  if (extensions & 4 /* Declaration */) {
    const nodeModulesAtTypes2 = combinePaths(nodeModulesFolder, "@types");
    let nodeModulesAtTypesExists = nodeModulesFolderExists;
    if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes2, state.host)) {
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes2);
      }
      nodeModulesAtTypesExists = false;
    }
    return loadModuleFromSpecificNodeModulesDirectory(4 /* Declaration */, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes2, nodeModulesAtTypesExists, state, cache, redirectedReference);
  }
}
function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) {
  var _a, _b;
  const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName));
  const { packageName, rest } = parsePackageName(moduleName);
  const packageDirectory = combinePaths(nodeModulesDirectory, packageName);
  let rootPackageInfo;
  let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
  if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */) || !hasProperty(((_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) ?? emptyArray, "exports"))) {
    const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
    if (fromFile) {
      return noPackageId(fromFile);
    }
    const fromDirectory = loadNodeModuleFromDirectoryWorker(
      extensions,
      candidate,
      !nodeModulesDirectoryExists,
      state,
      packageInfo.contents.packageJsonContent,
      getVersionPathsOfPackageJsonInfo(packageInfo, state)
    );
    return withPackageId(packageInfo, fromDirectory, state);
  }
  const loader = (extensions2, candidate2, onlyRecordFailures, state2) => {
    let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker(
      extensions2,
      candidate2,
      onlyRecordFailures,
      state2,
      packageInfo && packageInfo.contents.packageJsonContent,
      packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state2)
    );
    if (!pathAndExtension && packageInfo && (packageInfo.contents.packageJsonContent.exports === void 0 || packageInfo.contents.packageJsonContent.exports === null) && state2.features & 32 /* EsmMode */) {
      pathAndExtension = loadModuleFromFile(extensions2, combinePaths(candidate2, "index.js"), onlyRecordFailures, state2);
    }
    return withPackageId(packageInfo, pathAndExtension, state2);
  };
  if (rest !== "") {
    packageInfo = rootPackageInfo ?? getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
  }
  if (packageInfo) {
    state.resolvedPackageDirectory = true;
  }
  if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & 8 /* Exports */) {
    return (_b = loadModuleFromExports(packageInfo, extensions, combinePaths(".", rest), state, cache, redirectedReference)) == null ? void 0 : _b.value;
  }
  const versionPaths = rest !== "" && packageInfo ? getVersionPathsOfPackageJsonInfo(packageInfo, state) : void 0;
  if (versionPaths) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest);
    }
    const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host);
    const pathPatterns = tryParsePatterns(versionPaths.paths);
    const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, pathPatterns, loader, !packageDirectoryExists, state);
    if (fromPaths) {
      return fromPaths.value;
    }
  }
  return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
}
function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, onlyRecordFailures, state) {
  const matchedPattern = matchPatternOrExact(pathPatterns, moduleName);
  if (matchedPattern) {
    const matchedStar = isString(matchedPattern) ? void 0 : matchedText(matchedPattern, moduleName);
    const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern);
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
    }
    const resolved = forEach(paths[matchedPatternText], (subst) => {
      const path = matchedStar ? replaceFirstStar(subst, matchedStar) : subst;
      const candidate = normalizePath(combinePaths(baseDirectory, path));
      if (state.traceEnabled) {
        trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
      }
      const extension = tryGetExtensionFromPath2(subst);
      if (extension !== void 0) {
        const path2 = tryFile(candidate, onlyRecordFailures, state);
        if (path2 !== void 0) {
          return noPackageId({ path: path2, ext: extension, resolvedUsingTsExtension: void 0 });
        }
      }
      return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
    });
    return { value: resolved };
  }
}
var mangledScopedPackageSeparator = "__";
function mangleScopedPackageNameWithTrace(packageName, state) {
  const mangled = mangleScopedPackageName(packageName);
  if (state.traceEnabled && mangled !== packageName) {
    trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled);
  }
  return mangled;
}
function getTypesPackageName(packageName) {
  return `@types/${mangleScopedPackageName(packageName)}`;
}
function mangleScopedPackageName(packageName) {
  if (startsWith(packageName, "@")) {
    const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator);
    if (replaceSlash !== packageName) {
      return replaceSlash.slice(1);
    }
  }
  return packageName;
}
function getPackageNameFromTypesPackageName(mangledName) {
  const withoutAtTypePrefix = removePrefix(mangledName, "@types/");
  if (withoutAtTypePrefix !== mangledName) {
    return unmangleScopedPackageName(withoutAtTypePrefix);
  }
  return mangledName;
}
function unmangleScopedPackageName(typesPackageName) {
  return typesPackageName.includes(mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName;
}
function tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, containingDirectory, redirectedReference, state) {
  const result = cache && cache.getFromNonRelativeNameCache(moduleName, mode, containingDirectory, redirectedReference);
  if (result) {
    if (state.traceEnabled) {
      trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
    }
    state.resultFromCache = result;
    return {
      value: result.resolvedModule && {
        path: result.resolvedModule.resolvedFileName,
        originalPath: result.resolvedModule.originalPath || true,
        extension: result.resolvedModule.extension,
        packageId: result.resolvedModule.packageId,
        resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension
      }
    };
  }
}
function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  const failedLookupLocations = [];
  const affectingLocations = [];
  const containingDirectory = getDirectoryPath(containingFile);
  const diagnostics = [];
  const state = {
    compilerOptions,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache: cache,
    features: 0 /* None */,
    conditions: [],
    requestContainingDirectory: containingDirectory,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  const resolved = tryResolve(1 /* TypeScript */ | 4 /* Declaration */) || tryResolve(2 /* JavaScript */ | (compilerOptions.resolveJsonModule ? 8 /* Json */ : 0));
  return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
    moduleName,
    resolved && resolved.value,
    (resolved == null ? void 0 : resolved.value) && pathContainsNodeModules(resolved.value.path),
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state,
    cache
  );
  function tryResolve(extensions) {
    const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
    if (resolvedUsingSettings) {
      return { value: resolvedUsingSettings };
    }
    if (!isExternalModuleNameRelative(moduleName)) {
      const resolved2 = forEachAncestorDirectoryStoppingAtGlobalCache(
        state.host,
        containingDirectory,
        (directory) => {
          const resolutionFromCache = tryFindNonRelativeModuleNameInCache(
            cache,
            moduleName,
            /*mode*/
            void 0,
            directory,
            redirectedReference,
            state
          );
          if (resolutionFromCache) {
            return resolutionFromCache;
          }
          const searchName = normalizePath(combinePaths(directory, moduleName));
          return toSearchResult(loadModuleFromFileNoPackageId(
            extensions,
            searchName,
            /*onlyRecordFailures*/
            false,
            state
          ));
        }
      );
      if (resolved2) return resolved2;
      if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) {
        let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
        if (extensions & 4 /* Declaration */) resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state));
        return resolved3;
      }
    } else {
      const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
      return toSearchResult(loadModuleFromFileNoPackageId(
        extensions,
        candidate,
        /*onlyRecordFailures*/
        false,
        state
      ));
    }
  }
}
function resolveFromTypeRoot(moduleName, state) {
  if (!state.compilerOptions.typeRoots) return;
  for (const typeRoot of state.compilerOptions.typeRoots) {
    const candidate = getCandidateFromTypeRoot(typeRoot, moduleName, state);
    const directoryExists = directoryProbablyExists(typeRoot, state.host);
    if (!directoryExists && state.traceEnabled) {
      trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot);
    }
    const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, state);
    if (resolvedFromFile) {
      const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path);
      const packageInfo = packageDirectory ? getPackageJsonInfo(
        packageDirectory,
        /*onlyRecordFailures*/
        false,
        state
      ) : void 0;
      return toSearchResult(withPackageId(packageInfo, resolvedFromFile, state));
    }
    const resolved = loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, state);
    if (resolved) return toSearchResult(resolved);
  }
}
function shouldAllowImportingTsExtension(compilerOptions, fromFileName) {
  return getAllowImportingTsExtensions(compilerOptions) || !!fromFileName && isDeclarationFileName(fromFileName);
}
function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) {
  const traceEnabled = isTraceEnabled(compilerOptions, host);
  if (traceEnabled) {
    trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
  }
  const failedLookupLocations = [];
  const affectingLocations = [];
  const diagnostics = [];
  const state = {
    compilerOptions,
    host,
    traceEnabled,
    failedLookupLocations,
    affectingLocations,
    packageJsonInfoCache,
    features: 0 /* None */,
    conditions: [],
    requestContainingDirectory: void 0,
    reportDiagnostic: (diag2) => void diagnostics.push(diag2),
    isConfigLookup: false,
    candidateIsFromPackageJsonField: false,
    resolvedPackageDirectory: false
  };
  const resolved = loadModuleFromImmediateNodeModulesDirectory(
    4 /* Declaration */,
    moduleName,
    globalCache,
    state,
    /*typesScopeOnly*/
    false,
    /*cache*/
    void 0,
    /*redirectedReference*/
    void 0
  );
  return createResolvedModuleWithFailedLookupLocations(
    resolved,
    /*isExternalLibraryImport*/
    true,
    failedLookupLocations,
    affectingLocations,
    diagnostics,
    state.resultFromCache,
    /*cache*/
    void 0
  );
}
function toSearchResult(value) {
  return value !== void 0 ? { value } : void 0;
}
function traceIfEnabled(state, diagnostic, ...args) {
  if (state.traceEnabled) {
    trace(state.host, diagnostic, ...args);
  }
}
function useCaseSensitiveFileNames(state) {
  return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames();
}

// src/compiler/binder.ts
function getModuleInstanceState(node, visited) {
  if (node.body && !node.body.parent) {
    setParent(node.body, node);
    setParentRecursive(
      node.body,
      /*incremental*/
      false
    );
  }
  return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
}
function getModuleInstanceStateCached(node, visited = /* @__PURE__ */ new Map()) {
  const nodeId = getNodeId(node);
  if (visited.has(nodeId)) {
    return visited.get(nodeId) || 0 /* NonInstantiated */;
  }
  visited.set(nodeId, void 0);
  const result = getModuleInstanceStateWorker(node, visited);
  visited.set(nodeId, result);
  return result;
}
function getModuleInstanceStateWorker(node, visited) {
  switch (node.kind) {
    // 1. interface declarations, type alias declarations
    case 264 /* InterfaceDeclaration */:
    case 265 /* TypeAliasDeclaration */:
      return 0 /* NonInstantiated */;
    // 2. const enum declarations
    case 266 /* EnumDeclaration */:
      if (isEnumConst(node)) {
        return 2 /* ConstEnumOnly */;
      }
      break;
    // 3. non-exported import declarations
    case 272 /* ImportDeclaration */:
    case 271 /* ImportEqualsDeclaration */:
      if (!hasSyntacticModifier(node, 32 /* Export */)) {
        return 0 /* NonInstantiated */;
      }
      break;
    // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
    case 278 /* ExportDeclaration */:
      const exportDeclaration = node;
      if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 279 /* NamedExports */) {
        let state = 0 /* NonInstantiated */;
        for (const specifier of exportDeclaration.exportClause.elements) {
          const specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
          if (specifierState > state) {
            state = specifierState;
          }
          if (state === 1 /* Instantiated */) {
            return state;
          }
        }
        return state;
      }
      break;
    // 5. other uninstantiated module declarations.
    case 268 /* ModuleBlock */: {
      let state = 0 /* NonInstantiated */;
      forEachChild(node, (n) => {
        const childState = getModuleInstanceStateCached(n, visited);
        switch (childState) {
          case 0 /* NonInstantiated */:
            return;
          case 2 /* ConstEnumOnly */:
            state = 2 /* ConstEnumOnly */;
            return;
          case 1 /* Instantiated */:
            state = 1 /* Instantiated */;
            return true;
          default:
            Debug.assertNever(childState);
        }
      });
      return state;
    }
    case 267 /* ModuleDeclaration */:
      return getModuleInstanceState(node, visited);
    case 80 /* Identifier */:
      if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) {
        return 0 /* NonInstantiated */;
      }
  }
  return 1 /* Instantiated */;
}
function getModuleInstanceStateForAliasTarget(specifier, visited) {
  const name = specifier.propertyName || specifier.name;
  if (name.kind !== 80 /* Identifier */) {
    return 1 /* Instantiated */;
  }
  let p = specifier.parent;
  while (p) {
    if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) {
      const statements = p.statements;
      let found;
      for (const statement of statements) {
        if (nodeHasName(statement, name)) {
          if (!statement.parent) {
            setParent(statement, p);
            setParentRecursive(
              statement,
              /*incremental*/
              false
            );
          }
          const state = getModuleInstanceStateCached(statement, visited);
          if (found === void 0 || state > found) {
            found = state;
          }
          if (found === 1 /* Instantiated */) {
            return found;
          }
          if (statement.kind === 271 /* ImportEqualsDeclaration */) {
            found = 1 /* Instantiated */;
          }
        }
      }
      if (found !== void 0) {
        return found;
      }
    }
    p = p.parent;
  }
  return 1 /* Instantiated */;
}
function createFlowNode(flags, node, antecedent) {
  return Debug.attachFlowNodeDebugInfo({ flags, id: 0, node, antecedent });
}
var binder = /* @__PURE__ */ createBinder();
function bindSourceFile(file, options) {
  mark("beforeBind");
  binder(file, options);
  mark("afterBind");
  measure("Bind", "beforeBind", "afterBind");
}
function createBinder() {
  var file;
  var options;
  var languageVersion;
  var parent;
  var container;
  var thisParentContainer;
  var blockScopeContainer;
  var lastContainer;
  var delayedTypeAliases;
  var seenThisKeyword;
  var jsDocImports;
  var currentFlow;
  var currentBreakTarget;
  var currentContinueTarget;
  var currentReturnTarget;
  var currentTrueTarget;
  var currentFalseTarget;
  var currentExceptionTarget;
  var preSwitchCaseFlow;
  var activeLabelList;
  var hasExplicitReturn;
  var hasFlowEffects;
  var emitFlags;
  var inStrictMode;
  var inAssignmentPattern = false;
  var symbolCount = 0;
  var Symbol13;
  var classifiableNames;
  var unreachableFlow = createFlowNode(
    1 /* Unreachable */,
    /*node*/
    void 0,
    /*antecedent*/
    void 0
  );
  var reportedUnreachableFlow = createFlowNode(
    1 /* Unreachable */,
    /*node*/
    void 0,
    /*antecedent*/
    void 0
  );
  var bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
  return bindSourceFile2;
  function createDiagnosticForNode2(node, message, ...args) {
    return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, ...args);
  }
  function bindSourceFile2(f, opts) {
    var _a, _b;
    file = f;
    options = opts;
    languageVersion = getEmitScriptTarget(options);
    inStrictMode = bindInStrictMode(file, opts);
    classifiableNames = /* @__PURE__ */ new Set();
    symbolCount = 0;
    Symbol13 = objectAllocator.getSymbolConstructor();
    Debug.attachFlowNodeDebugInfo(unreachableFlow);
    Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
    if (!file.locals) {
      (_a = tracing) == null ? void 0 : _a.push(
        tracing.Phase.Bind,
        "bindSourceFile",
        { path: file.path },
        /*separateBeginAndEnd*/
        true
      );
      bind(file);
      (_b = tracing) == null ? void 0 : _b.pop();
      file.symbolCount = symbolCount;
      file.classifiableNames = classifiableNames;
      delayedBindJSDocTypedefTag();
      bindJSDocImports();
    }
    file = void 0;
    options = void 0;
    languageVersion = void 0;
    parent = void 0;
    container = void 0;
    thisParentContainer = void 0;
    blockScopeContainer = void 0;
    lastContainer = void 0;
    delayedTypeAliases = void 0;
    jsDocImports = void 0;
    seenThisKeyword = false;
    currentFlow = void 0;
    currentBreakTarget = void 0;
    currentContinueTarget = void 0;
    currentReturnTarget = void 0;
    currentTrueTarget = void 0;
    currentFalseTarget = void 0;
    currentExceptionTarget = void 0;
    activeLabelList = void 0;
    hasExplicitReturn = false;
    hasFlowEffects = false;
    inAssignmentPattern = false;
    emitFlags = 0 /* None */;
  }
  function bindInStrictMode(file2, opts) {
    if (getStrictOptionValue(opts, "alwaysStrict") && !file2.isDeclarationFile) {
      return true;
    } else {
      return !!file2.externalModuleIndicator;
    }
  }
  function createSymbol(flags, name) {
    symbolCount++;
    return new Symbol13(flags, name);
  }
  function addDeclarationToSymbol(symbol, node, symbolFlags) {
    symbol.flags |= symbolFlags;
    node.symbol = symbol;
    symbol.declarations = appendIfUnique(symbol.declarations, node);
    if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
      symbol.exports = createSymbolTable();
    }
    if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
      symbol.members = createSymbolTable();
    }
    if (symbol.constEnumOnlyModule && symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
      symbol.constEnumOnlyModule = false;
    }
    if (symbolFlags & 111551 /* Value */) {
      setValueDeclaration(symbol, node);
    }
  }
  function getDeclarationName(node) {
    if (node.kind === 277 /* ExportAssignment */) {
      return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
    }
    const name = getNameOfDeclaration(node);
    if (name) {
      if (isAmbientModule(node)) {
        const moduleName = getTextOfIdentifierOrLiteral(name);
        return isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`;
      }
      if (name.kind === 167 /* ComputedPropertyName */) {
        const nameExpression = name.expression;
        if (isStringOrNumericLiteralLike(nameExpression)) {
          return escapeLeadingUnderscores(nameExpression.text);
        }
        if (isSignedNumericLiteral(nameExpression)) {
          return tokenToString(nameExpression.operator) + nameExpression.operand.text;
        } else {
          Debug.fail("Only computed properties with literal names have declaration names");
        }
      }
      if (isPrivateIdentifier(name)) {
        const containingClass = getContainingClass(node);
        if (!containingClass) {
          return void 0;
        }
        const containingClassSymbol = containingClass.symbol;
        return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
      }
      if (isJsxNamespacedName(name)) {
        return getEscapedTextOfJsxNamespacedName(name);
      }
      return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0;
    }
    switch (node.kind) {
      case 176 /* Constructor */:
        return "__constructor" /* Constructor */;
      case 184 /* FunctionType */:
      case 179 /* CallSignature */:
      case 323 /* JSDocSignature */:
        return "__call" /* Call */;
      case 185 /* ConstructorType */:
      case 180 /* ConstructSignature */:
        return "__new" /* New */;
      case 181 /* IndexSignature */:
        return "__index" /* Index */;
      case 278 /* ExportDeclaration */:
        return "__export" /* ExportStar */;
      case 307 /* SourceFile */:
        return "export=" /* ExportEquals */;
      case 226 /* BinaryExpression */:
        if (getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
          return "export=" /* ExportEquals */;
        }
        Debug.fail("Unknown binary declaration kind");
        break;
      case 317 /* JSDocFunctionType */:
        return isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */;
      case 169 /* Parameter */:
        Debug.assert(node.parent.kind === 317 /* JSDocFunctionType */, "Impossible parameter parent kind", () => `parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`);
        const functionType = node.parent;
        const index = functionType.parameters.indexOf(node);
        return "arg" + index;
    }
  }
  function getDisplayName(node) {
    return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node)));
  }
  function declareSymbol(symbolTable, parent2, node, includes, excludes, isReplaceableByMethod, isComputedName) {
    Debug.assert(isComputedName || !hasDynamicName(node));
    const isDefaultExport = hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) && moduleExportNameIsDefault(node.name);
    const name = isComputedName ? "__computed" /* Computed */ : isDefaultExport && parent2 ? "default" /* Default */ : getDeclarationName(node);
    let symbol;
    if (name === void 0) {
      symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
    } else {
      symbol = symbolTable.get(name);
      if (includes & 2885600 /* Classifiable */) {
        classifiableNames.add(name);
      }
      if (!symbol) {
        symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
        if (isReplaceableByMethod) symbol.isReplaceableByMethod = true;
      } else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
        return symbol;
      } else if (symbol.flags & excludes) {
        if (symbol.isReplaceableByMethod) {
          symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
        } else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
          if (isNamedDeclaration(node)) {
            setParent(node.name, node);
          }
          let message = symbol.flags & 2 /* BlockScopedVariable */ ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
          let messageNeedsName = true;
          if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
            message = Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
            messageNeedsName = false;
          }
          let multipleDefaultExports = false;
          if (length(symbol.declarations)) {
            if (isDefaultExport) {
              message = Diagnostics.A_module_cannot_have_multiple_default_exports;
              messageNeedsName = false;
              multipleDefaultExports = true;
            } else {
              if (symbol.declarations && symbol.declarations.length && (node.kind === 277 /* ExportAssignment */ && !node.isExportEquals)) {
                message = Diagnostics.A_module_cannot_have_multiple_default_exports;
                messageNeedsName = false;
                multipleDefaultExports = true;
              }
            }
          }
          const relatedInformation = [];
          if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasSyntacticModifier(node, 32 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
            relatedInformation.push(createDiagnosticForNode2(node, Diagnostics.Did_you_mean_0, `export type { ${unescapeLeadingUnderscores(node.name.escapedText)} }`));
          }
          const declarationName = getNameOfDeclaration(node) || node;
          forEach(symbol.declarations, (declaration, index) => {
            const decl = getNameOfDeclaration(declaration) || declaration;
            const diag3 = messageNeedsName ? createDiagnosticForNode2(decl, message, getDisplayName(declaration)) : createDiagnosticForNode2(decl, message);
            file.bindDiagnostics.push(
              multipleDefaultExports ? addRelatedInfo(diag3, createDiagnosticForNode2(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag3
            );
            if (multipleDefaultExports) {
              relatedInformation.push(createDiagnosticForNode2(decl, Diagnostics.The_first_export_default_is_here));
            }
          });
          const diag2 = messageNeedsName ? createDiagnosticForNode2(declarationName, message, getDisplayName(node)) : createDiagnosticForNode2(declarationName, message);
          file.bindDiagnostics.push(addRelatedInfo(diag2, ...relatedInformation));
          symbol = createSymbol(0 /* None */, name);
        }
      }
    }
    addDeclarationToSymbol(symbol, node, includes);
    if (symbol.parent) {
      Debug.assert(symbol.parent === parent2, "Existing symbol parent should match new one");
    } else {
      symbol.parent = parent2;
    }
    return symbol;
  }
  function declareModuleMember(node, symbolFlags, symbolExcludes) {
    const hasExportModifier = !!(getCombinedModifierFlags(node) & 32 /* Export */) || jsdocTreatAsExported(node);
    if (symbolFlags & 2097152 /* Alias */) {
      if (node.kind === 281 /* ExportSpecifier */ || node.kind === 271 /* ImportEqualsDeclaration */ && hasExportModifier) {
        return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
      } else {
        Debug.assertNode(container, canHaveLocals);
        return declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
      }
    } else {
      if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node));
      if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */)) {
        if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 2048 /* Default */) && !getDeclarationName(node)) {
          return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
        }
        const exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
        const local = declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          exportKind,
          symbolExcludes
        );
        local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
        node.localSymbol = local;
        return local;
      } else {
        Debug.assertNode(container, canHaveLocals);
        return declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
      }
    }
  }
  function jsdocTreatAsExported(node) {
    if (node.parent && isModuleDeclaration(node)) {
      node = node.parent;
    }
    if (!isJSDocTypeAlias(node)) return false;
    if (!isJSDocEnumTag(node) && !!node.fullName) return true;
    const declName = getNameOfDeclaration(node);
    if (!declName) return false;
    if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true;
    if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) return true;
    return false;
  }
  function bindContainer(node, containerFlags) {
    const saveContainer = container;
    const saveThisParentContainer = thisParentContainer;
    const savedBlockScopeContainer = blockScopeContainer;
    if (containerFlags & 1 /* IsContainer */) {
      if (node.kind !== 219 /* ArrowFunction */) {
        thisParentContainer = container;
      }
      container = blockScopeContainer = node;
      if (containerFlags & 32 /* HasLocals */) {
        container.locals = createSymbolTable();
        addToContainerChain(container);
      }
    } else if (containerFlags & 2 /* IsBlockScopedContainer */) {
      blockScopeContainer = node;
      if (containerFlags & 32 /* HasLocals */) {
        blockScopeContainer.locals = void 0;
      }
    }
    if (containerFlags & 4 /* IsControlFlowContainer */) {
      const saveCurrentFlow = currentFlow;
      const saveBreakTarget = currentBreakTarget;
      const saveContinueTarget = currentContinueTarget;
      const saveReturnTarget = currentReturnTarget;
      const saveExceptionTarget = currentExceptionTarget;
      const saveActiveLabelList = activeLabelList;
      const saveHasExplicitReturn = hasExplicitReturn;
      const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 1024 /* Async */) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */;
      if (!isImmediatelyInvoked) {
        currentFlow = createFlowNode(
          2 /* Start */,
          /*node*/
          void 0,
          /*antecedent*/
          void 0
        );
        if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) {
          currentFlow.node = node;
        }
      }
      currentReturnTarget = isImmediatelyInvoked || node.kind === 176 /* Constructor */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */) ? createBranchLabel() : void 0;
      currentExceptionTarget = void 0;
      currentBreakTarget = void 0;
      currentContinueTarget = void 0;
      activeLabelList = void 0;
      hasExplicitReturn = false;
      bindChildren(node);
      node.flags &= ~5632 /* ReachabilityAndEmitFlags */;
      if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && nodeIsPresent(node.body)) {
        node.flags |= 512 /* HasImplicitReturn */;
        if (hasExplicitReturn) node.flags |= 1024 /* HasExplicitReturn */;
        node.endFlowNode = currentFlow;
      }
      if (node.kind === 307 /* SourceFile */) {
        node.flags |= emitFlags;
        node.endFlowNode = currentFlow;
      }
      if (currentReturnTarget) {
        addAntecedent(currentReturnTarget, currentFlow);
        currentFlow = finishFlowLabel(currentReturnTarget);
        if (node.kind === 176 /* Constructor */ || node.kind === 175 /* ClassStaticBlockDeclaration */ || isInJSFile(node) && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */)) {
          node.returnFlowNode = currentFlow;
        }
      }
      if (!isImmediatelyInvoked) {
        currentFlow = saveCurrentFlow;
      }
      currentBreakTarget = saveBreakTarget;
      currentContinueTarget = saveContinueTarget;
      currentReturnTarget = saveReturnTarget;
      currentExceptionTarget = saveExceptionTarget;
      activeLabelList = saveActiveLabelList;
      hasExplicitReturn = saveHasExplicitReturn;
    } else if (containerFlags & 64 /* IsInterface */) {
      seenThisKeyword = false;
      bindChildren(node);
      Debug.assertNotNode(node, isIdentifier);
      node.flags = seenThisKeyword ? node.flags | 256 /* ContainsThis */ : node.flags & ~256 /* ContainsThis */;
    } else {
      bindChildren(node);
    }
    container = saveContainer;
    thisParentContainer = saveThisParentContainer;
    blockScopeContainer = savedBlockScopeContainer;
  }
  function bindEachFunctionsFirst(nodes) {
    bindEach(nodes, (n) => n.kind === 262 /* FunctionDeclaration */ ? bind(n) : void 0);
    bindEach(nodes, (n) => n.kind !== 262 /* FunctionDeclaration */ ? bind(n) : void 0);
  }
  function bindEach(nodes, bindFunction = bind) {
    if (nodes === void 0) {
      return;
    }
    forEach(nodes, bindFunction);
  }
  function bindEachChild(node) {
    forEachChild(node, bind, bindEach);
  }
  function bindChildren(node) {
    const saveInAssignmentPattern = inAssignmentPattern;
    inAssignmentPattern = false;
    if (checkUnreachable(node)) {
      bindEachChild(node);
      bindJSDoc(node);
      inAssignmentPattern = saveInAssignmentPattern;
      return;
    }
    if (node.kind >= 243 /* FirstStatement */ && node.kind <= 259 /* LastStatement */ && (!options.allowUnreachableCode || node.kind === 253 /* ReturnStatement */)) {
      node.flowNode = currentFlow;
    }
    switch (node.kind) {
      case 247 /* WhileStatement */:
        bindWhileStatement(node);
        break;
      case 246 /* DoStatement */:
        bindDoStatement(node);
        break;
      case 248 /* ForStatement */:
        bindForStatement(node);
        break;
      case 249 /* ForInStatement */:
      case 250 /* ForOfStatement */:
        bindForInOrForOfStatement(node);
        break;
      case 245 /* IfStatement */:
        bindIfStatement(node);
        break;
      case 253 /* ReturnStatement */:
      case 257 /* ThrowStatement */:
        bindReturnOrThrow(node);
        break;
      case 252 /* BreakStatement */:
      case 251 /* ContinueStatement */:
        bindBreakOrContinueStatement(node);
        break;
      case 258 /* TryStatement */:
        bindTryStatement(node);
        break;
      case 255 /* SwitchStatement */:
        bindSwitchStatement(node);
        break;
      case 269 /* CaseBlock */:
        bindCaseBlock(node);
        break;
      case 296 /* CaseClause */:
        bindCaseClause(node);
        break;
      case 244 /* ExpressionStatement */:
        bindExpressionStatement(node);
        break;
      case 256 /* LabeledStatement */:
        bindLabeledStatement(node);
        break;
      case 224 /* PrefixUnaryExpression */:
        bindPrefixUnaryExpressionFlow(node);
        break;
      case 225 /* PostfixUnaryExpression */:
        bindPostfixUnaryExpressionFlow(node);
        break;
      case 226 /* BinaryExpression */:
        if (isDestructuringAssignment(node)) {
          inAssignmentPattern = saveInAssignmentPattern;
          bindDestructuringAssignmentFlow(node);
          return;
        }
        bindBinaryExpressionFlow(node);
        break;
      case 220 /* DeleteExpression */:
        bindDeleteExpressionFlow(node);
        break;
      case 227 /* ConditionalExpression */:
        bindConditionalExpressionFlow(node);
        break;
      case 260 /* VariableDeclaration */:
        bindVariableDeclarationFlow(node);
        break;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        bindAccessExpressionFlow(node);
        break;
      case 213 /* CallExpression */:
        bindCallExpressionFlow(node);
        break;
      case 235 /* NonNullExpression */:
        bindNonNullExpressionFlow(node);
        break;
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
      case 340 /* JSDocEnumTag */:
        bindJSDocTypeAlias(node);
        break;
      case 351 /* JSDocImportTag */:
        bindJSDocImportTag(node);
        break;
      // In source files and blocks, bind functions first to match hoisting that occurs at runtime
      case 307 /* SourceFile */: {
        bindEachFunctionsFirst(node.statements);
        bind(node.endOfFileToken);
        break;
      }
      case 241 /* Block */:
      case 268 /* ModuleBlock */:
        bindEachFunctionsFirst(node.statements);
        break;
      case 208 /* BindingElement */:
        bindBindingElementFlow(node);
        break;
      case 169 /* Parameter */:
        bindParameterFlow(node);
        break;
      case 210 /* ObjectLiteralExpression */:
      case 209 /* ArrayLiteralExpression */:
      case 303 /* PropertyAssignment */:
      case 230 /* SpreadElement */:
        inAssignmentPattern = saveInAssignmentPattern;
      // falls through
      default:
        bindEachChild(node);
        break;
    }
    bindJSDoc(node);
    inAssignmentPattern = saveInAssignmentPattern;
  }
  function isNarrowingExpression(expr) {
    switch (expr.kind) {
      case 80 /* Identifier */:
      case 110 /* ThisKeyword */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return containsNarrowableReference(expr);
      case 213 /* CallExpression */:
        return hasNarrowableArgument(expr);
      case 217 /* ParenthesizedExpression */:
        if (isJSDocTypeAssertion(expr)) {
          return false;
        }
      // fallthrough
      case 235 /* NonNullExpression */:
        return isNarrowingExpression(expr.expression);
      case 226 /* BinaryExpression */:
        return isNarrowingBinaryExpression(expr);
      case 224 /* PrefixUnaryExpression */:
        return expr.operator === 54 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
      case 221 /* TypeOfExpression */:
        return isNarrowingExpression(expr.expression);
    }
    return false;
  }
  function isNarrowableReference(expr) {
    switch (expr.kind) {
      case 80 /* Identifier */:
      case 110 /* ThisKeyword */:
      case 108 /* SuperKeyword */:
      case 236 /* MetaProperty */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 217 /* ParenthesizedExpression */:
      case 235 /* NonNullExpression */:
        return isNarrowableReference(expr.expression);
      case 212 /* ElementAccessExpression */:
        return (isStringOrNumericLiteralLike(expr.argumentExpression) || isEntityNameExpression(expr.argumentExpression)) && isNarrowableReference(expr.expression);
      case 226 /* BinaryExpression */:
        return expr.operatorToken.kind === 28 /* CommaToken */ && isNarrowableReference(expr.right) || isAssignmentOperator(expr.operatorToken.kind) && isLeftHandSideExpression(expr.left);
    }
    return false;
  }
  function containsNarrowableReference(expr) {
    return isNarrowableReference(expr) || isOptionalChain(expr) && containsNarrowableReference(expr.expression);
  }
  function hasNarrowableArgument(expr) {
    if (expr.arguments) {
      for (const argument of expr.arguments) {
        if (containsNarrowableReference(argument)) {
          return true;
        }
      }
    }
    if (expr.expression.kind === 211 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) {
      return true;
    }
    return false;
  }
  function isNarrowingTypeofOperands(expr1, expr2) {
    return isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && isStringLiteralLike(expr2);
  }
  function isNarrowingBinaryExpression(expr) {
    switch (expr.operatorToken.kind) {
      case 64 /* EqualsToken */:
      case 76 /* BarBarEqualsToken */:
      case 77 /* AmpersandAmpersandEqualsToken */:
      case 78 /* QuestionQuestionEqualsToken */:
        return containsNarrowableReference(expr.left);
      case 35 /* EqualsEqualsToken */:
      case 36 /* ExclamationEqualsToken */:
      case 37 /* EqualsEqualsEqualsToken */:
      case 38 /* ExclamationEqualsEqualsToken */:
        return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || (isBooleanLiteral(expr.right) && isNarrowingExpression(expr.left) || isBooleanLiteral(expr.left) && isNarrowingExpression(expr.right));
      case 104 /* InstanceOfKeyword */:
        return isNarrowableOperand(expr.left);
      case 103 /* InKeyword */:
        return isNarrowingExpression(expr.right);
      case 28 /* CommaToken */:
        return isNarrowingExpression(expr.right);
    }
    return false;
  }
  function isNarrowableOperand(expr) {
    switch (expr.kind) {
      case 217 /* ParenthesizedExpression */:
        return isNarrowableOperand(expr.expression);
      case 226 /* BinaryExpression */:
        switch (expr.operatorToken.kind) {
          case 64 /* EqualsToken */:
            return isNarrowableOperand(expr.left);
          case 28 /* CommaToken */:
            return isNarrowableOperand(expr.right);
        }
    }
    return containsNarrowableReference(expr);
  }
  function createBranchLabel() {
    return createFlowNode(
      4 /* BranchLabel */,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
  }
  function createLoopLabel() {
    return createFlowNode(
      8 /* LoopLabel */,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
  }
  function createReduceLabel(target, antecedents, antecedent) {
    return createFlowNode(1024 /* ReduceLabel */, { target, antecedents }, antecedent);
  }
  function setFlowNodeReferenced(flow) {
    flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
  }
  function addAntecedent(label, antecedent) {
    if (!(antecedent.flags & 1 /* Unreachable */) && !contains(label.antecedent, antecedent)) {
      (label.antecedent || (label.antecedent = [])).push(antecedent);
      setFlowNodeReferenced(antecedent);
    }
  }
  function createFlowCondition(flags, antecedent, expression) {
    if (antecedent.flags & 1 /* Unreachable */) {
      return antecedent;
    }
    if (!expression) {
      return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
    }
    if ((expression.kind === 112 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 97 /* FalseKeyword */ && flags & 32 /* TrueCondition */) && !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) {
      return unreachableFlow;
    }
    if (!isNarrowingExpression(expression)) {
      return antecedent;
    }
    setFlowNodeReferenced(antecedent);
    return createFlowNode(flags, expression, antecedent);
  }
  function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
    setFlowNodeReferenced(antecedent);
    return createFlowNode(128 /* SwitchClause */, { switchStatement, clauseStart, clauseEnd }, antecedent);
  }
  function createFlowMutation(flags, antecedent, node) {
    setFlowNodeReferenced(antecedent);
    hasFlowEffects = true;
    const result = createFlowNode(flags, node, antecedent);
    if (currentExceptionTarget) {
      addAntecedent(currentExceptionTarget, result);
    }
    return result;
  }
  function createFlowCall(antecedent, node) {
    setFlowNodeReferenced(antecedent);
    hasFlowEffects = true;
    return createFlowNode(512 /* Call */, node, antecedent);
  }
  function finishFlowLabel(flow) {
    const antecedents = flow.antecedent;
    if (!antecedents) {
      return unreachableFlow;
    }
    if (antecedents.length === 1) {
      return antecedents[0];
    }
    return flow;
  }
  function isStatementCondition(node) {
    const parent2 = node.parent;
    switch (parent2.kind) {
      case 245 /* IfStatement */:
      case 247 /* WhileStatement */:
      case 246 /* DoStatement */:
        return parent2.expression === node;
      case 248 /* ForStatement */:
      case 227 /* ConditionalExpression */:
        return parent2.condition === node;
    }
    return false;
  }
  function isLogicalExpression(node) {
    while (true) {
      if (node.kind === 217 /* ParenthesizedExpression */) {
        node = node.expression;
      } else if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 54 /* ExclamationToken */) {
        node = node.operand;
      } else {
        return isLogicalOrCoalescingBinaryExpression(node);
      }
    }
  }
  function isLogicalAssignmentExpression(node) {
    return isLogicalOrCoalescingAssignmentExpression(skipParentheses(node));
  }
  function isTopLevelLogicalExpression(node) {
    while (isParenthesizedExpression(node.parent) || isPrefixUnaryExpression(node.parent) && node.parent.operator === 54 /* ExclamationToken */) {
      node = node.parent;
    }
    return !isStatementCondition(node) && !isLogicalExpression(node.parent) && !(isOptionalChain(node.parent) && node.parent.expression === node);
  }
  function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
    const savedTrueTarget = currentTrueTarget;
    const savedFalseTarget = currentFalseTarget;
    currentTrueTarget = trueTarget;
    currentFalseTarget = falseTarget;
    action(value);
    currentTrueTarget = savedTrueTarget;
    currentFalseTarget = savedFalseTarget;
  }
  function bindCondition(node, trueTarget, falseTarget) {
    doWithConditionalBranches(bind, node, trueTarget, falseTarget);
    if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(isOptionalChain(node) && isOutermostOptionalChain(node))) {
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    }
  }
  function bindIterativeStatement(node, breakTarget, continueTarget) {
    const saveBreakTarget = currentBreakTarget;
    const saveContinueTarget = currentContinueTarget;
    currentBreakTarget = breakTarget;
    currentContinueTarget = continueTarget;
    bind(node);
    currentBreakTarget = saveBreakTarget;
    currentContinueTarget = saveContinueTarget;
  }
  function setContinueTarget(node, target) {
    let label = activeLabelList;
    while (label && node.parent.kind === 256 /* LabeledStatement */) {
      label.continueTarget = target;
      label = label.next;
      node = node.parent;
    }
    return target;
  }
  function bindWhileStatement(node) {
    const preWhileLabel = setContinueTarget(node, createLoopLabel());
    const preBodyLabel = createBranchLabel();
    const postWhileLabel = createBranchLabel();
    addAntecedent(preWhileLabel, currentFlow);
    currentFlow = preWhileLabel;
    bindCondition(node.expression, preBodyLabel, postWhileLabel);
    currentFlow = finishFlowLabel(preBodyLabel);
    bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
    addAntecedent(preWhileLabel, currentFlow);
    currentFlow = finishFlowLabel(postWhileLabel);
  }
  function bindDoStatement(node) {
    const preDoLabel = createLoopLabel();
    const preConditionLabel = setContinueTarget(node, createBranchLabel());
    const postDoLabel = createBranchLabel();
    addAntecedent(preDoLabel, currentFlow);
    currentFlow = preDoLabel;
    bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
    addAntecedent(preConditionLabel, currentFlow);
    currentFlow = finishFlowLabel(preConditionLabel);
    bindCondition(node.expression, preDoLabel, postDoLabel);
    currentFlow = finishFlowLabel(postDoLabel);
  }
  function bindForStatement(node) {
    const preLoopLabel = setContinueTarget(node, createLoopLabel());
    const preBodyLabel = createBranchLabel();
    const postLoopLabel = createBranchLabel();
    bind(node.initializer);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = preLoopLabel;
    bindCondition(node.condition, preBodyLabel, postLoopLabel);
    currentFlow = finishFlowLabel(preBodyLabel);
    bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
    bind(node.incrementor);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = finishFlowLabel(postLoopLabel);
  }
  function bindForInOrForOfStatement(node) {
    const preLoopLabel = setContinueTarget(node, createLoopLabel());
    const postLoopLabel = createBranchLabel();
    bind(node.expression);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = preLoopLabel;
    if (node.kind === 250 /* ForOfStatement */) {
      bind(node.awaitModifier);
    }
    addAntecedent(postLoopLabel, currentFlow);
    bind(node.initializer);
    if (node.initializer.kind !== 261 /* VariableDeclarationList */) {
      bindAssignmentTargetFlow(node.initializer);
    }
    bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
    addAntecedent(preLoopLabel, currentFlow);
    currentFlow = finishFlowLabel(postLoopLabel);
  }
  function bindIfStatement(node) {
    const thenLabel = createBranchLabel();
    const elseLabel = createBranchLabel();
    const postIfLabel = createBranchLabel();
    bindCondition(node.expression, thenLabel, elseLabel);
    currentFlow = finishFlowLabel(thenLabel);
    bind(node.thenStatement);
    addAntecedent(postIfLabel, currentFlow);
    currentFlow = finishFlowLabel(elseLabel);
    bind(node.elseStatement);
    addAntecedent(postIfLabel, currentFlow);
    currentFlow = finishFlowLabel(postIfLabel);
  }
  function bindReturnOrThrow(node) {
    bind(node.expression);
    if (node.kind === 253 /* ReturnStatement */) {
      hasExplicitReturn = true;
      if (currentReturnTarget) {
        addAntecedent(currentReturnTarget, currentFlow);
      }
    }
    currentFlow = unreachableFlow;
    hasFlowEffects = true;
  }
  function findActiveLabel(name) {
    for (let label = activeLabelList; label; label = label.next) {
      if (label.name === name) {
        return label;
      }
    }
    return void 0;
  }
  function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
    const flowLabel = node.kind === 252 /* BreakStatement */ ? breakTarget : continueTarget;
    if (flowLabel) {
      addAntecedent(flowLabel, currentFlow);
      currentFlow = unreachableFlow;
      hasFlowEffects = true;
    }
  }
  function bindBreakOrContinueStatement(node) {
    bind(node.label);
    if (node.label) {
      const activeLabel = findActiveLabel(node.label.escapedText);
      if (activeLabel) {
        activeLabel.referenced = true;
        bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
      }
    } else {
      bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
    }
  }
  function bindTryStatement(node) {
    const saveReturnTarget = currentReturnTarget;
    const saveExceptionTarget = currentExceptionTarget;
    const normalExitLabel = createBranchLabel();
    const returnLabel = createBranchLabel();
    let exceptionLabel = createBranchLabel();
    if (node.finallyBlock) {
      currentReturnTarget = returnLabel;
    }
    addAntecedent(exceptionLabel, currentFlow);
    currentExceptionTarget = exceptionLabel;
    bind(node.tryBlock);
    addAntecedent(normalExitLabel, currentFlow);
    if (node.catchClause) {
      currentFlow = finishFlowLabel(exceptionLabel);
      exceptionLabel = createBranchLabel();
      addAntecedent(exceptionLabel, currentFlow);
      currentExceptionTarget = exceptionLabel;
      bind(node.catchClause);
      addAntecedent(normalExitLabel, currentFlow);
    }
    currentReturnTarget = saveReturnTarget;
    currentExceptionTarget = saveExceptionTarget;
    if (node.finallyBlock) {
      const finallyLabel = createBranchLabel();
      finallyLabel.antecedent = concatenate(concatenate(normalExitLabel.antecedent, exceptionLabel.antecedent), returnLabel.antecedent);
      currentFlow = finallyLabel;
      bind(node.finallyBlock);
      if (currentFlow.flags & 1 /* Unreachable */) {
        currentFlow = unreachableFlow;
      } else {
        if (currentReturnTarget && returnLabel.antecedent) {
          addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedent, currentFlow));
        }
        if (currentExceptionTarget && exceptionLabel.antecedent) {
          addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedent, currentFlow));
        }
        currentFlow = normalExitLabel.antecedent ? createReduceLabel(finallyLabel, normalExitLabel.antecedent, currentFlow) : unreachableFlow;
      }
    } else {
      currentFlow = finishFlowLabel(normalExitLabel);
    }
  }
  function bindSwitchStatement(node) {
    const postSwitchLabel = createBranchLabel();
    bind(node.expression);
    const saveBreakTarget = currentBreakTarget;
    const savePreSwitchCaseFlow = preSwitchCaseFlow;
    currentBreakTarget = postSwitchLabel;
    preSwitchCaseFlow = currentFlow;
    bind(node.caseBlock);
    addAntecedent(postSwitchLabel, currentFlow);
    const hasDefault = forEach(node.caseBlock.clauses, (c) => c.kind === 297 /* DefaultClause */);
    node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedent;
    if (!hasDefault) {
      addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
    }
    currentBreakTarget = saveBreakTarget;
    preSwitchCaseFlow = savePreSwitchCaseFlow;
    currentFlow = finishFlowLabel(postSwitchLabel);
  }
  function bindCaseBlock(node) {
    const clauses = node.clauses;
    const isNarrowingSwitch = node.parent.expression.kind === 112 /* TrueKeyword */ || isNarrowingExpression(node.parent.expression);
    let fallthroughFlow = unreachableFlow;
    for (let i = 0; i < clauses.length; i++) {
      const clauseStart = i;
      while (!clauses[i].statements.length && i + 1 < clauses.length) {
        if (fallthroughFlow === unreachableFlow) {
          currentFlow = preSwitchCaseFlow;
        }
        bind(clauses[i]);
        i++;
      }
      const preCaseLabel = createBranchLabel();
      addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
      addAntecedent(preCaseLabel, fallthroughFlow);
      currentFlow = finishFlowLabel(preCaseLabel);
      const clause = clauses[i];
      bind(clause);
      fallthroughFlow = currentFlow;
      if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
        clause.fallthroughFlowNode = currentFlow;
      }
    }
  }
  function bindCaseClause(node) {
    const saveCurrentFlow = currentFlow;
    currentFlow = preSwitchCaseFlow;
    bind(node.expression);
    currentFlow = saveCurrentFlow;
    bindEach(node.statements);
  }
  function bindExpressionStatement(node) {
    bind(node.expression);
    maybeBindExpressionFlowIfCall(node.expression);
  }
  function maybeBindExpressionFlowIfCall(node) {
    if (node.kind === 213 /* CallExpression */) {
      const call = node;
      if (call.expression.kind !== 108 /* SuperKeyword */ && isDottedName(call.expression)) {
        currentFlow = createFlowCall(currentFlow, call);
      }
    }
  }
  function bindLabeledStatement(node) {
    const postStatementLabel = createBranchLabel();
    activeLabelList = {
      next: activeLabelList,
      name: node.label.escapedText,
      breakTarget: postStatementLabel,
      continueTarget: void 0,
      referenced: false
    };
    bind(node.label);
    bind(node.statement);
    if (!activeLabelList.referenced && !options.allowUnusedLabels) {
      errorOrSuggestionOnNode(unusedLabelIsError(options), node.label, Diagnostics.Unused_label);
    }
    activeLabelList = activeLabelList.next;
    addAntecedent(postStatementLabel, currentFlow);
    currentFlow = finishFlowLabel(postStatementLabel);
  }
  function bindDestructuringTargetFlow(node) {
    if (node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */) {
      bindAssignmentTargetFlow(node.left);
    } else {
      bindAssignmentTargetFlow(node);
    }
  }
  function bindAssignmentTargetFlow(node) {
    if (isNarrowableReference(node)) {
      currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
    } else if (node.kind === 209 /* ArrayLiteralExpression */) {
      for (const e of node.elements) {
        if (e.kind === 230 /* SpreadElement */) {
          bindAssignmentTargetFlow(e.expression);
        } else {
          bindDestructuringTargetFlow(e);
        }
      }
    } else if (node.kind === 210 /* ObjectLiteralExpression */) {
      for (const p of node.properties) {
        if (p.kind === 303 /* PropertyAssignment */) {
          bindDestructuringTargetFlow(p.initializer);
        } else if (p.kind === 304 /* ShorthandPropertyAssignment */) {
          bindAssignmentTargetFlow(p.name);
        } else if (p.kind === 305 /* SpreadAssignment */) {
          bindAssignmentTargetFlow(p.expression);
        }
      }
    }
  }
  function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
    const preRightLabel = createBranchLabel();
    if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 77 /* AmpersandAmpersandEqualsToken */) {
      bindCondition(node.left, preRightLabel, falseTarget);
    } else {
      bindCondition(node.left, trueTarget, preRightLabel);
    }
    currentFlow = finishFlowLabel(preRightLabel);
    bind(node.operatorToken);
    if (isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
      doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
      bindAssignmentTargetFlow(node.left);
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    } else {
      bindCondition(node.right, trueTarget, falseTarget);
    }
  }
  function bindPrefixUnaryExpressionFlow(node) {
    if (node.operator === 54 /* ExclamationToken */) {
      const saveTrueTarget = currentTrueTarget;
      currentTrueTarget = currentFalseTarget;
      currentFalseTarget = saveTrueTarget;
      bindEachChild(node);
      currentFalseTarget = currentTrueTarget;
      currentTrueTarget = saveTrueTarget;
    } else {
      bindEachChild(node);
      if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
        bindAssignmentTargetFlow(node.operand);
      }
    }
  }
  function bindPostfixUnaryExpressionFlow(node) {
    bindEachChild(node);
    if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
      bindAssignmentTargetFlow(node.operand);
    }
  }
  function bindDestructuringAssignmentFlow(node) {
    if (inAssignmentPattern) {
      inAssignmentPattern = false;
      bind(node.operatorToken);
      bind(node.right);
      inAssignmentPattern = true;
      bind(node.left);
    } else {
      inAssignmentPattern = true;
      bind(node.left);
      inAssignmentPattern = false;
      bind(node.operatorToken);
      bind(node.right);
    }
    bindAssignmentTargetFlow(node.left);
  }
  function createBindBinaryExpressionFlow() {
    return createBinaryExpressionTrampoline(
      onEnter,
      onLeft,
      onOperator,
      onRight,
      onExit,
      /*foldState*/
      void 0
    );
    function onEnter(node, state) {
      if (state) {
        state.stackIndex++;
        setParent(node, parent);
        const saveInStrictMode = inStrictMode;
        bindWorker(node);
        const saveParent = parent;
        parent = node;
        state.skip = false;
        state.inStrictModeStack[state.stackIndex] = saveInStrictMode;
        state.parentStack[state.stackIndex] = saveParent;
      } else {
        state = {
          stackIndex: 0,
          skip: false,
          inStrictModeStack: [void 0],
          parentStack: [void 0]
        };
      }
      const operator = node.operatorToken.kind;
      if (isLogicalOrCoalescingBinaryOperator(operator) || isLogicalOrCoalescingAssignmentOperator(operator)) {
        if (isTopLevelLogicalExpression(node)) {
          const postExpressionLabel = createBranchLabel();
          const saveCurrentFlow = currentFlow;
          const saveHasFlowEffects = hasFlowEffects;
          hasFlowEffects = false;
          bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
          currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow;
          hasFlowEffects || (hasFlowEffects = saveHasFlowEffects);
        } else {
          bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
        }
        state.skip = true;
      }
      return state;
    }
    function onLeft(left, state, node) {
      if (!state.skip) {
        const maybeBound = maybeBind2(left);
        if (node.operatorToken.kind === 28 /* CommaToken */) {
          maybeBindExpressionFlowIfCall(left);
        }
        return maybeBound;
      }
    }
    function onOperator(operatorToken, state, _node) {
      if (!state.skip) {
        bind(operatorToken);
      }
    }
    function onRight(right, state, node) {
      if (!state.skip) {
        const maybeBound = maybeBind2(right);
        if (node.operatorToken.kind === 28 /* CommaToken */) {
          maybeBindExpressionFlowIfCall(right);
        }
        return maybeBound;
      }
    }
    function onExit(node, state) {
      if (!state.skip) {
        const operator = node.operatorToken.kind;
        if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
          bindAssignmentTargetFlow(node.left);
          if (operator === 64 /* EqualsToken */ && node.left.kind === 212 /* ElementAccessExpression */) {
            const elementAccess = node.left;
            if (isNarrowableOperand(elementAccess.expression)) {
              currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
            }
          }
        }
      }
      const savedInStrictMode = state.inStrictModeStack[state.stackIndex];
      const savedParent = state.parentStack[state.stackIndex];
      if (savedInStrictMode !== void 0) {
        inStrictMode = savedInStrictMode;
      }
      if (savedParent !== void 0) {
        parent = savedParent;
      }
      state.skip = false;
      state.stackIndex--;
    }
    function maybeBind2(node) {
      if (node && isBinaryExpression(node) && !isDestructuringAssignment(node)) {
        return node;
      }
      bind(node);
    }
  }
  function bindDeleteExpressionFlow(node) {
    bindEachChild(node);
    if (node.expression.kind === 211 /* PropertyAccessExpression */) {
      bindAssignmentTargetFlow(node.expression);
    }
  }
  function bindConditionalExpressionFlow(node) {
    const trueLabel = createBranchLabel();
    const falseLabel = createBranchLabel();
    const postExpressionLabel = createBranchLabel();
    const saveCurrentFlow = currentFlow;
    const saveHasFlowEffects = hasFlowEffects;
    hasFlowEffects = false;
    bindCondition(node.condition, trueLabel, falseLabel);
    currentFlow = finishFlowLabel(trueLabel);
    bind(node.questionToken);
    bind(node.whenTrue);
    addAntecedent(postExpressionLabel, currentFlow);
    currentFlow = finishFlowLabel(falseLabel);
    bind(node.colonToken);
    bind(node.whenFalse);
    addAntecedent(postExpressionLabel, currentFlow);
    currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow;
    hasFlowEffects || (hasFlowEffects = saveHasFlowEffects);
  }
  function bindInitializedVariableFlow(node) {
    const name = !isOmittedExpression(node) ? node.name : void 0;
    if (isBindingPattern(name)) {
      for (const child of name.elements) {
        bindInitializedVariableFlow(child);
      }
    } else {
      currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
    }
  }
  function bindVariableDeclarationFlow(node) {
    bindEachChild(node);
    if (node.initializer || isForInOrOfStatement(node.parent.parent)) {
      bindInitializedVariableFlow(node);
    }
  }
  function bindBindingElementFlow(node) {
    bind(node.dotDotDotToken);
    bind(node.propertyName);
    bindInitializer(node.initializer);
    bind(node.name);
  }
  function bindParameterFlow(node) {
    bindEach(node.modifiers);
    bind(node.dotDotDotToken);
    bind(node.questionToken);
    bind(node.type);
    bindInitializer(node.initializer);
    bind(node.name);
  }
  function bindInitializer(node) {
    if (!node) {
      return;
    }
    const entryFlow = currentFlow;
    bind(node);
    if (entryFlow === unreachableFlow || entryFlow === currentFlow) {
      return;
    }
    const exitFlow = createBranchLabel();
    addAntecedent(exitFlow, entryFlow);
    addAntecedent(exitFlow, currentFlow);
    currentFlow = finishFlowLabel(exitFlow);
  }
  function bindJSDocTypeAlias(node) {
    bind(node.tagName);
    if (node.kind !== 340 /* JSDocEnumTag */ && node.fullName) {
      setParent(node.fullName, node);
      setParentRecursive(
        node.fullName,
        /*incremental*/
        false
      );
    }
    if (typeof node.comment !== "string") {
      bindEach(node.comment);
    }
  }
  function bindJSDocClassTag(node) {
    bindEachChild(node);
    const host = getHostSignatureFromJSDoc(node);
    if (host && host.kind !== 174 /* MethodDeclaration */) {
      addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
    }
  }
  function bindJSDocImportTag(node) {
    bind(node.tagName);
    bind(node.moduleSpecifier);
    bind(node.attributes);
    if (typeof node.comment !== "string") {
      bindEach(node.comment);
    }
  }
  function bindOptionalExpression(node, trueTarget, falseTarget) {
    doWithConditionalBranches(bind, node, trueTarget, falseTarget);
    if (!isOptionalChain(node) || isOutermostOptionalChain(node)) {
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    }
  }
  function bindOptionalChainRest(node) {
    switch (node.kind) {
      case 211 /* PropertyAccessExpression */:
        bind(node.questionDotToken);
        bind(node.name);
        break;
      case 212 /* ElementAccessExpression */:
        bind(node.questionDotToken);
        bind(node.argumentExpression);
        break;
      case 213 /* CallExpression */:
        bind(node.questionDotToken);
        bindEach(node.typeArguments);
        bindEach(node.arguments);
        break;
    }
  }
  function bindOptionalChain(node, trueTarget, falseTarget) {
    const preChainLabel = isOptionalChainRoot(node) ? createBranchLabel() : void 0;
    bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
    if (preChainLabel) {
      currentFlow = finishFlowLabel(preChainLabel);
    }
    doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
    if (isOutermostOptionalChain(node)) {
      addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
      addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
    }
  }
  function bindOptionalChainFlow(node) {
    if (isTopLevelLogicalExpression(node)) {
      const postExpressionLabel = createBranchLabel();
      const saveCurrentFlow = currentFlow;
      const saveHasFlowEffects = hasFlowEffects;
      bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
      currentFlow = hasFlowEffects ? finishFlowLabel(postExpressionLabel) : saveCurrentFlow;
      hasFlowEffects || (hasFlowEffects = saveHasFlowEffects);
    } else {
      bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
    }
  }
  function bindNonNullExpressionFlow(node) {
    if (isOptionalChain(node)) {
      bindOptionalChainFlow(node);
    } else {
      bindEachChild(node);
    }
  }
  function bindAccessExpressionFlow(node) {
    if (isOptionalChain(node)) {
      bindOptionalChainFlow(node);
    } else {
      bindEachChild(node);
    }
  }
  function bindCallExpressionFlow(node) {
    if (isOptionalChain(node)) {
      bindOptionalChainFlow(node);
    } else {
      const expr = skipParentheses(node.expression);
      if (expr.kind === 218 /* FunctionExpression */ || expr.kind === 219 /* ArrowFunction */) {
        bindEach(node.typeArguments);
        bindEach(node.arguments);
        bind(node.expression);
      } else {
        bindEachChild(node);
        if (node.expression.kind === 108 /* SuperKeyword */) {
          currentFlow = createFlowCall(currentFlow, node);
        }
      }
    }
    if (node.expression.kind === 211 /* PropertyAccessExpression */) {
      const propertyAccess = node.expression;
      if (isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) {
        currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
      }
    }
  }
  function addToContainerChain(next) {
    if (lastContainer) {
      lastContainer.nextContainer = next;
    }
    lastContainer = next;
  }
  function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
    switch (container.kind) {
      // Modules, source files, and classes need specialized handling for how their
      // members are declared (for example, a member of a class will go into a specific
      // symbol table depending on if it is static or not). We defer to specialized
      // handlers to take care of declaring these child members.
      case 267 /* ModuleDeclaration */:
        return declareModuleMember(node, symbolFlags, symbolExcludes);
      case 307 /* SourceFile */:
        return declareSourceFileMember(node, symbolFlags, symbolExcludes);
      case 231 /* ClassExpression */:
      case 263 /* ClassDeclaration */:
        return declareClassMember(node, symbolFlags, symbolExcludes);
      case 266 /* EnumDeclaration */:
        return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
      case 187 /* TypeLiteral */:
      case 322 /* JSDocTypeLiteral */:
      case 210 /* ObjectLiteralExpression */:
      case 264 /* InterfaceDeclaration */:
      case 292 /* JsxAttributes */:
        return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
      case 184 /* FunctionType */:
      case 185 /* ConstructorType */:
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 323 /* JSDocSignature */:
      case 181 /* IndexSignature */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 317 /* JSDocFunctionType */:
      case 175 /* ClassStaticBlockDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 200 /* MappedType */:
        if (container.locals) Debug.assertNode(container, canHaveLocals);
        return declareSymbol(
          container.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
    }
  }
  function declareClassMember(node, symbolFlags, symbolExcludes) {
    return isStatic(node) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
  }
  function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
    return isExternalModule(file) ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(
      file.locals,
      /*parent*/
      void 0,
      node,
      symbolFlags,
      symbolExcludes
    );
  }
  function hasExportDeclarations(node) {
    const body = isSourceFile(node) ? node : tryCast(node.body, isModuleBlock);
    return !!body && body.statements.some((s) => isExportDeclaration(s) || isExportAssignment(s));
  }
  function setExportContextFlag(node) {
    if (node.flags & 33554432 /* Ambient */ && !hasExportDeclarations(node)) {
      node.flags |= 128 /* ExportContext */;
    } else {
      node.flags &= ~128 /* ExportContext */;
    }
  }
  function bindModuleDeclaration(node) {
    setExportContextFlag(node);
    if (isAmbientModule(node)) {
      if (hasSyntacticModifier(node, 32 /* Export */)) {
        errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
      }
      if (isModuleAugmentationExternal(node)) {
        declareModuleSymbol(node);
      } else {
        let pattern;
        if (node.name.kind === 11 /* StringLiteral */) {
          const { text } = node.name;
          pattern = tryParsePattern(text);
          if (pattern === void 0) {
            errorOnFirstToken(node.name, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
          }
        }
        const symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
        file.patternAmbientModules = append(file.patternAmbientModules, pattern && !isString(pattern) ? { pattern, symbol } : void 0);
      }
    } else {
      const state = declareModuleSymbol(node);
      if (state !== 0 /* NonInstantiated */) {
        const { symbol } = node;
        symbol.constEnumOnlyModule = !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) && state === 2 /* ConstEnumOnly */ && symbol.constEnumOnlyModule !== false;
      }
    }
  }
  function declareModuleSymbol(node) {
    const state = getModuleInstanceState(node);
    const instantiated = state !== 0 /* NonInstantiated */;
    declareSymbolAndAddToSymbolTable(
      node,
      instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */,
      instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */
    );
    return state;
  }
  function bindFunctionOrConstructorType(node) {
    const symbol = createSymbol(131072 /* Signature */, getDeclarationName(node));
    addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
    const typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
    addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
    typeLiteralSymbol.members = createSymbolTable();
    typeLiteralSymbol.members.set(symbol.escapedName, symbol);
  }
  function bindObjectLiteralExpression(node) {
    return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
  }
  function bindJsxAttributes(node) {
    return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
  }
  function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
    return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
  }
  function bindAnonymousDeclaration(node, symbolFlags, name) {
    const symbol = createSymbol(symbolFlags, name);
    if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
      symbol.parent = container.symbol;
    }
    addDeclarationToSymbol(symbol, node, symbolFlags);
    return symbol;
  }
  function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
    switch (blockScopeContainer.kind) {
      case 267 /* ModuleDeclaration */:
        declareModuleMember(node, symbolFlags, symbolExcludes);
        break;
      case 307 /* SourceFile */:
        if (isExternalOrCommonJsModule(container)) {
          declareModuleMember(node, symbolFlags, symbolExcludes);
          break;
        }
      // falls through
      default:
        Debug.assertNode(blockScopeContainer, canHaveLocals);
        if (!blockScopeContainer.locals) {
          blockScopeContainer.locals = createSymbolTable();
          addToContainerChain(blockScopeContainer);
        }
        declareSymbol(
          blockScopeContainer.locals,
          /*parent*/
          void 0,
          node,
          symbolFlags,
          symbolExcludes
        );
    }
  }
  function delayedBindJSDocTypedefTag() {
    if (!delayedTypeAliases) {
      return;
    }
    const saveContainer = container;
    const saveLastContainer = lastContainer;
    const saveBlockScopeContainer = blockScopeContainer;
    const saveParent = parent;
    const saveCurrentFlow = currentFlow;
    for (const typeAlias of delayedTypeAliases) {
      const host = typeAlias.parent.parent;
      container = getEnclosingContainer(host) || file;
      blockScopeContainer = getEnclosingBlockScopeContainer(host) || file;
      currentFlow = createFlowNode(
        2 /* Start */,
        /*node*/
        void 0,
        /*antecedent*/
        void 0
      );
      parent = typeAlias;
      bind(typeAlias.typeExpression);
      const declName = getNameOfDeclaration(typeAlias);
      if ((isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && isPropertyAccessEntityNameExpression(declName.parent)) {
        const isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
        if (isTopLevel) {
          bindPotentiallyMissingNamespaces(
            file.symbol,
            declName.parent,
            isTopLevel,
            !!findAncestor(declName, (d) => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"),
            /*containerIsClass*/
            false
          );
          const oldContainer = container;
          switch (getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
            case 1 /* ExportsProperty */:
            case 2 /* ModuleExports */:
              if (!isExternalOrCommonJsModule(file)) {
                container = void 0;
              } else {
                container = file;
              }
              break;
            case 4 /* ThisProperty */:
              container = declName.parent.expression;
              break;
            case 3 /* PrototypeProperty */:
              container = declName.parent.expression.name;
              break;
            case 5 /* Property */:
              container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file : isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name : declName.parent.expression;
              break;
            case 0 /* None */:
              return Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
          }
          if (container) {
            declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
          }
          container = oldContainer;
        }
      } else if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 80 /* Identifier */) {
        parent = typeAlias.parent;
        bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
      } else {
        bind(typeAlias.fullName);
      }
    }
    container = saveContainer;
    lastContainer = saveLastContainer;
    blockScopeContainer = saveBlockScopeContainer;
    parent = saveParent;
    currentFlow = saveCurrentFlow;
  }
  function bindJSDocImports() {
    if (jsDocImports === void 0) {
      return;
    }
    const saveContainer = container;
    const saveLastContainer = lastContainer;
    const saveBlockScopeContainer = blockScopeContainer;
    const saveParent = parent;
    const saveCurrentFlow = currentFlow;
    for (const jsDocImportTag of jsDocImports) {
      const host = getJSDocHost(jsDocImportTag);
      const enclosingContainer = host ? getEnclosingContainer(host) : void 0;
      const enclosingBlockScopeContainer = host ? getEnclosingBlockScopeContainer(host) : void 0;
      container = enclosingContainer || file;
      blockScopeContainer = enclosingBlockScopeContainer || file;
      currentFlow = createFlowNode(
        2 /* Start */,
        /*node*/
        void 0,
        /*antecedent*/
        void 0
      );
      parent = jsDocImportTag;
      bind(jsDocImportTag.importClause);
    }
    container = saveContainer;
    lastContainer = saveLastContainer;
    blockScopeContainer = saveBlockScopeContainer;
    parent = saveParent;
    currentFlow = saveCurrentFlow;
  }
  function checkContextualIdentifier(node) {
    if (!file.parseDiagnostics.length && !(node.flags & 33554432 /* Ambient */) && !(node.flags & 16777216 /* JSDoc */) && !isIdentifierName(node)) {
      const originalKeywordKind = identifierToKeywordKind(node);
      if (originalKeywordKind === void 0) {
        return;
      }
      if (inStrictMode && originalKeywordKind >= 119 /* FirstFutureReservedWord */ && originalKeywordKind <= 127 /* LastFutureReservedWord */) {
        file.bindDiagnostics.push(createDiagnosticForNode2(node, getStrictModeIdentifierMessage(node), declarationNameToString(node)));
      } else if (originalKeywordKind === 135 /* AwaitKeyword */) {
        if (isExternalModule(file) && isInTopLevelContext(node)) {
          file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, declarationNameToString(node)));
        } else if (node.flags & 65536 /* AwaitContext */) {
          file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node)));
        }
      } else if (originalKeywordKind === 127 /* YieldKeyword */ && node.flags & 16384 /* YieldContext */) {
        file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node)));
      }
    }
  }
  function getStrictModeIdentifierMessage(node) {
    if (getContainingClass(node)) {
      return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
    }
    if (file.externalModuleIndicator) {
      return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
    }
    return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
  }
  function checkPrivateIdentifier(node) {
    if (node.escapedText === "#constructor") {
      if (!file.parseDiagnostics.length) {
        file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.constructor_is_a_reserved_word, declarationNameToString(node)));
      }
    }
  }
  function checkStrictModeBinaryExpression(node) {
    if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) {
      checkStrictModeEvalOrArguments(node, node.left);
    }
  }
  function checkStrictModeCatchClause(node) {
    if (inStrictMode && node.variableDeclaration) {
      checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
    }
  }
  function checkStrictModeDeleteExpression(node) {
    if (inStrictMode && node.expression.kind === 80 /* Identifier */) {
      const span = getErrorSpanForNode(file, node.expression);
      file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
    }
  }
  function isEvalOrArgumentsIdentifier(node) {
    return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
  }
  function checkStrictModeEvalOrArguments(contextNode, name) {
    if (name && name.kind === 80 /* Identifier */) {
      const identifier = name;
      if (isEvalOrArgumentsIdentifier(identifier)) {
        const span = getErrorSpanForNode(file, name);
        file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), idText(identifier)));
      }
    }
  }
  function getStrictModeEvalOrArgumentsMessage(node) {
    if (getContainingClass(node)) {
      return Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode;
    }
    if (file.externalModuleIndicator) {
      return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
    }
    return Diagnostics.Invalid_use_of_0_in_strict_mode;
  }
  function checkStrictModeFunctionName(node) {
    if (inStrictMode && !(node.flags & 33554432 /* Ambient */)) {
      checkStrictModeEvalOrArguments(node, node.name);
    }
  }
  function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
    if (getContainingClass(node)) {
      return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Class_definitions_are_automatically_in_strict_mode;
    }
    if (file.externalModuleIndicator) {
      return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5_Modules_are_automatically_in_strict_mode;
    }
    return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES5;
  }
  function checkStrictModeFunctionDeclaration(node) {
    if (languageVersion < 2 /* ES2015 */) {
      if (blockScopeContainer.kind !== 307 /* SourceFile */ && blockScopeContainer.kind !== 267 /* ModuleDeclaration */ && !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) {
        const errorSpan = getErrorSpanForNode(file, node);
        file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
      }
    }
  }
  function checkStrictModePostfixUnaryExpression(node) {
    if (inStrictMode) {
      checkStrictModeEvalOrArguments(node, node.operand);
    }
  }
  function checkStrictModePrefixUnaryExpression(node) {
    if (inStrictMode) {
      if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
        checkStrictModeEvalOrArguments(node, node.operand);
      }
    }
  }
  function checkStrictModeWithStatement(node) {
    if (inStrictMode) {
      errorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode);
    }
  }
  function checkStrictModeLabeledStatement(node) {
    if (inStrictMode && getEmitScriptTarget(options) >= 2 /* ES2015 */) {
      if (isDeclarationStatement(node.statement) || isVariableStatement(node.statement)) {
        errorOnFirstToken(node.label, Diagnostics.A_label_is_not_allowed_here);
      }
    }
  }
  function errorOnFirstToken(node, message, ...args) {
    const span = getSpanOfTokenAtPosition(file, node.pos);
    file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, ...args));
  }
  function errorOrSuggestionOnNode(isError, node, message) {
    errorOrSuggestionOnRange(isError, node, node, message);
  }
  function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
    addErrorOrSuggestionDiagnostic(isError, { pos: getTokenPosOfNode(startNode, file), end: endNode.end }, message);
  }
  function addErrorOrSuggestionDiagnostic(isError, range, message) {
    const diag2 = createFileDiagnostic(file, range.pos, range.end - range.pos, message);
    if (isError) {
      file.bindDiagnostics.push(diag2);
    } else {
      file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { ...diag2, category: 2 /* Suggestion */ });
    }
  }
  function bind(node) {
    if (!node) {
      return;
    }
    setParent(node, parent);
    if (tracing) node.tracingPath = file.path;
    const saveInStrictMode = inStrictMode;
    bindWorker(node);
    if (node.kind > 165 /* LastToken */) {
      const saveParent = parent;
      parent = node;
      const containerFlags = getContainerFlags(node);
      if (containerFlags === 0 /* None */) {
        bindChildren(node);
      } else {
        bindContainer(node, containerFlags);
      }
      parent = saveParent;
    } else {
      const saveParent = parent;
      if (node.kind === 1 /* EndOfFileToken */) parent = node;
      bindJSDoc(node);
      parent = saveParent;
    }
    inStrictMode = saveInStrictMode;
  }
  function bindJSDoc(node) {
    if (hasJSDocNodes(node)) {
      if (isInJSFile(node)) {
        for (const j of node.jsDoc) {
          bind(j);
        }
      } else {
        for (const j of node.jsDoc) {
          setParent(j, node);
          setParentRecursive(
            j,
            /*incremental*/
            false
          );
        }
      }
    }
  }
  function updateStrictModeStatementList(statements) {
    if (!inStrictMode) {
      for (const statement of statements) {
        if (!isPrologueDirective(statement)) {
          return;
        }
        if (isUseStrictPrologueDirective(statement)) {
          inStrictMode = true;
          return;
        }
      }
    }
  }
  function isUseStrictPrologueDirective(node) {
    const nodeText = getSourceTextOfNodeFromSourceFile(file, node.expression);
    return nodeText === '"use strict"' || nodeText === "'use strict'";
  }
  function bindWorker(node) {
    switch (node.kind) {
      /* Strict mode checks */
      case 80 /* Identifier */:
        if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) {
          let parentNode = node.parent;
          while (parentNode && !isJSDocTypeAlias(parentNode)) {
            parentNode = parentNode.parent;
          }
          bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
          break;
        }
      // falls through
      case 110 /* ThisKeyword */:
        if (currentFlow && (isExpression(node) || parent.kind === 304 /* ShorthandPropertyAssignment */)) {
          node.flowNode = currentFlow;
        }
        return checkContextualIdentifier(node);
      case 166 /* QualifiedName */:
        if (currentFlow && isPartOfTypeQuery(node)) {
          node.flowNode = currentFlow;
        }
        break;
      case 236 /* MetaProperty */:
      case 108 /* SuperKeyword */:
        node.flowNode = currentFlow;
        break;
      case 81 /* PrivateIdentifier */:
        return checkPrivateIdentifier(node);
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        const expr = node;
        if (currentFlow && isNarrowableReference(expr)) {
          expr.flowNode = currentFlow;
        }
        if (isSpecialPropertyDeclaration(expr)) {
          bindSpecialPropertyDeclaration(expr);
        }
        if (isInJSFile(expr) && file.commonJsModuleIndicator && isModuleExportsAccessExpression(expr) && !lookupSymbolForName(blockScopeContainer, "module")) {
          declareSymbol(
            file.locals,
            /*parent*/
            void 0,
            expr.expression,
            1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */,
            111550 /* FunctionScopedVariableExcludes */
          );
        }
        break;
      case 226 /* BinaryExpression */:
        const specialKind = getAssignmentDeclarationKind(node);
        switch (specialKind) {
          case 1 /* ExportsProperty */:
            bindExportsPropertyAssignment(node);
            break;
          case 2 /* ModuleExports */:
            bindModuleExportsAssignment(node);
            break;
          case 3 /* PrototypeProperty */:
            bindPrototypePropertyAssignment(node.left, node);
            break;
          case 6 /* Prototype */:
            bindPrototypeAssignment(node);
            break;
          case 4 /* ThisProperty */:
            bindThisPropertyAssignment(node);
            break;
          case 5 /* Property */:
            const expression = node.left.expression;
            if (isInJSFile(node) && isIdentifier(expression)) {
              const symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
              if (isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration)) {
                bindThisPropertyAssignment(node);
                break;
              }
            }
            bindSpecialPropertyAssignment(node);
            break;
          case 0 /* None */:
            break;
          default:
            Debug.fail("Unknown binary expression special property assignment kind");
        }
        return checkStrictModeBinaryExpression(node);
      case 299 /* CatchClause */:
        return checkStrictModeCatchClause(node);
      case 220 /* DeleteExpression */:
        return checkStrictModeDeleteExpression(node);
      case 225 /* PostfixUnaryExpression */:
        return checkStrictModePostfixUnaryExpression(node);
      case 224 /* PrefixUnaryExpression */:
        return checkStrictModePrefixUnaryExpression(node);
      case 254 /* WithStatement */:
        return checkStrictModeWithStatement(node);
      case 256 /* LabeledStatement */:
        return checkStrictModeLabeledStatement(node);
      case 197 /* ThisType */:
        seenThisKeyword = true;
        return;
      case 182 /* TypePredicate */:
        break;
      // Binding the children will handle everything
      case 168 /* TypeParameter */:
        return bindTypeParameter(node);
      case 169 /* Parameter */:
        return bindParameter(node);
      case 260 /* VariableDeclaration */:
        return bindVariableDeclarationOrBindingElement(node);
      case 208 /* BindingElement */:
        node.flowNode = currentFlow;
        return bindVariableDeclarationOrBindingElement(node);
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
        return bindPropertyWorker(node);
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
        return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
      case 306 /* EnumMember */:
        return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 181 /* IndexSignature */:
        return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
      case 262 /* FunctionDeclaration */:
        return bindFunctionDeclaration(node);
      case 176 /* Constructor */:
        return declareSymbolAndAddToSymbolTable(
          node,
          16384 /* Constructor */,
          /*symbolExcludes:*/
          0 /* None */
        );
      case 177 /* GetAccessor */:
        return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
      case 178 /* SetAccessor */:
        return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
      case 184 /* FunctionType */:
      case 317 /* JSDocFunctionType */:
      case 323 /* JSDocSignature */:
      case 185 /* ConstructorType */:
        return bindFunctionOrConstructorType(node);
      case 187 /* TypeLiteral */:
      case 322 /* JSDocTypeLiteral */:
      case 200 /* MappedType */:
        return bindAnonymousTypeWorker(node);
      case 332 /* JSDocClassTag */:
        return bindJSDocClassTag(node);
      case 210 /* ObjectLiteralExpression */:
        return bindObjectLiteralExpression(node);
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return bindFunctionExpression(node);
      case 213 /* CallExpression */:
        const assignmentKind = getAssignmentDeclarationKind(node);
        switch (assignmentKind) {
          case 7 /* ObjectDefinePropertyValue */:
            return bindObjectDefinePropertyAssignment(node);
          case 8 /* ObjectDefinePropertyExports */:
            return bindObjectDefinePropertyExport(node);
          case 9 /* ObjectDefinePrototypeProperty */:
            return bindObjectDefinePrototypeProperty(node);
          case 0 /* None */:
            break;
          // Nothing to do
          default:
            return Debug.fail("Unknown call expression assignment declaration kind");
        }
        if (isInJSFile(node)) {
          bindCallExpression(node);
        }
        break;
      // Members of classes, interfaces, and modules
      case 231 /* ClassExpression */:
      case 263 /* ClassDeclaration */:
        inStrictMode = true;
        return bindClassLikeDeclaration(node);
      case 264 /* InterfaceDeclaration */:
        return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
      case 265 /* TypeAliasDeclaration */:
        return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
      case 266 /* EnumDeclaration */:
        return bindEnumDeclaration(node);
      case 267 /* ModuleDeclaration */:
        return bindModuleDeclaration(node);
      // Jsx-attributes
      case 292 /* JsxAttributes */:
        return bindJsxAttributes(node);
      case 291 /* JsxAttribute */:
        return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
      // Imports and exports
      case 271 /* ImportEqualsDeclaration */:
      case 274 /* NamespaceImport */:
      case 276 /* ImportSpecifier */:
      case 281 /* ExportSpecifier */:
        return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
      case 270 /* NamespaceExportDeclaration */:
        return bindNamespaceExportDeclaration(node);
      case 273 /* ImportClause */:
        return bindImportClause(node);
      case 278 /* ExportDeclaration */:
        return bindExportDeclaration(node);
      case 277 /* ExportAssignment */:
        return bindExportAssignment(node);
      case 307 /* SourceFile */:
        updateStrictModeStatementList(node.statements);
        return bindSourceFileIfExternalModule();
      case 241 /* Block */:
        if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) {
          return;
        }
      // falls through
      case 268 /* ModuleBlock */:
        return updateStrictModeStatementList(node.statements);
      case 341 /* JSDocParameterTag */:
        if (node.parent.kind === 323 /* JSDocSignature */) {
          return bindParameter(node);
        }
        if (node.parent.kind !== 322 /* JSDocTypeLiteral */) {
          break;
        }
      // falls through
      case 348 /* JSDocPropertyTag */:
        const propTag = node;
        const flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 316 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */;
        return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
      case 340 /* JSDocEnumTag */:
        return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
      case 339 /* JSDocOverloadTag */:
        return bind(node.typeExpression);
      case 351 /* JSDocImportTag */:
        return (jsDocImports || (jsDocImports = [])).push(node);
    }
  }
  function bindPropertyWorker(node) {
    const isAutoAccessor = isAutoAccessorPropertyDeclaration(node);
    const includes = isAutoAccessor ? 98304 /* Accessor */ : 4 /* Property */;
    const excludes = isAutoAccessor ? 13247 /* AccessorExcludes */ : 0 /* PropertyExcludes */;
    return bindPropertyOrMethodOrAccessor(node, includes | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), excludes);
  }
  function bindAnonymousTypeWorker(node) {
    return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
  }
  function bindSourceFileIfExternalModule() {
    setExportContextFlag(file);
    if (isExternalModule(file)) {
      bindSourceFileAsExternalModule();
    } else if (isJsonSourceFile(file)) {
      bindSourceFileAsExternalModule();
      const originalSymbol = file.symbol;
      declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, -1 /* All */);
      file.symbol = originalSymbol;
    }
  }
  function bindSourceFileAsExternalModule() {
    bindAnonymousDeclaration(file, 512 /* ValueModule */, `"${removeFileExtension(file.fileName)}"`);
  }
  function bindExportAssignment(node) {
    if (!container.symbol || !container.symbol.exports) {
      bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node));
    } else {
      const flags = exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */;
      const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, -1 /* All */);
      if (node.isExportEquals) {
        setValueDeclaration(symbol, node);
      }
    }
  }
  function bindNamespaceExportDeclaration(node) {
    if (some(node.modifiers)) {
      file.bindDiagnostics.push(createDiagnosticForNode2(node, Diagnostics.Modifiers_cannot_appear_here));
    }
    const diag2 = !isSourceFile(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_at_top_level : !isExternalModule(node.parent) ? Diagnostics.Global_module_exports_may_only_appear_in_module_files : !node.parent.isDeclarationFile ? Diagnostics.Global_module_exports_may_only_appear_in_declaration_files : void 0;
    if (diag2) {
      file.bindDiagnostics.push(createDiagnosticForNode2(node, diag2));
    } else {
      file.symbol.globalExports = file.symbol.globalExports || createSymbolTable();
      declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
    }
  }
  function bindExportDeclaration(node) {
    if (!container.symbol || !container.symbol.exports) {
      bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
    } else if (!node.exportClause) {
      declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
    } else if (isNamespaceExport(node.exportClause)) {
      setParent(node.exportClause, node);
      declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
    }
  }
  function bindImportClause(node) {
    if (node.name) {
      declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
    }
  }
  function setCommonJsModuleIndicator(node) {
    if (file.externalModuleIndicator && file.externalModuleIndicator !== true) {
      return false;
    }
    if (!file.commonJsModuleIndicator) {
      file.commonJsModuleIndicator = node;
      if (!file.externalModuleIndicator) {
        bindSourceFileAsExternalModule();
      }
    }
    return true;
  }
  function bindObjectDefinePropertyExport(node) {
    if (!setCommonJsModuleIndicator(node)) {
      return;
    }
    const symbol = forEachIdentifierInEntityName(
      node.arguments[0],
      /*parent*/
      void 0,
      (id, symbol2) => {
        if (symbol2) {
          addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */);
        }
        return symbol2;
      }
    );
    if (symbol) {
      const flags = 4 /* Property */ | 1048576 /* ExportValue */;
      declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
    }
  }
  function bindExportsPropertyAssignment(node) {
    if (!setCommonJsModuleIndicator(node)) {
      return;
    }
    const symbol = forEachIdentifierInEntityName(
      node.left.expression,
      /*parent*/
      void 0,
      (id, symbol2) => {
        if (symbol2) {
          addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */);
        }
        return symbol2;
      }
    );
    if (symbol) {
      const isAlias = isAliasableExpression(node.right) && (isExportsIdentifier(node.left.expression) || isModuleExportsAccessExpression(node.left.expression));
      const flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
      setParent(node.left, node);
      declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
    }
  }
  function bindModuleExportsAssignment(node) {
    if (!setCommonJsModuleIndicator(node)) {
      return;
    }
    const assignedExpression = getRightMostAssignedExpression(node.right);
    if (isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
      return;
    }
    if (isObjectLiteralExpression(assignedExpression) && every(assignedExpression.properties, isShorthandPropertyAssignment)) {
      forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
      return;
    }
    const flags = exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
    const symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
    setValueDeclaration(symbol, node);
  }
  function bindExportAssignedObjectMemberAlias(node) {
    declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
  }
  function bindThisPropertyAssignment(node) {
    Debug.assert(isInJSFile(node));
    const hasPrivateIdentifier = isBinaryExpression(node) && isPropertyAccessExpression(node.left) && isPrivateIdentifier(node.left.name) || isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
    if (hasPrivateIdentifier) {
      return;
    }
    const thisContainer = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    switch (thisContainer.kind) {
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
        let constructorSymbol = thisContainer.symbol;
        if (isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 64 /* EqualsToken */) {
          const l = thisContainer.parent.left;
          if (isBindableStaticAccessExpression(l) && isPrototypeAccess(l.expression)) {
            constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
          }
        }
        if (constructorSymbol && constructorSymbol.valueDeclaration) {
          constructorSymbol.members = constructorSymbol.members || createSymbolTable();
          if (hasDynamicName(node)) {
            bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol, constructorSymbol.members);
          } else {
            declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
          }
          addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
        }
        break;
      case 176 /* Constructor */:
      case 172 /* PropertyDeclaration */:
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 175 /* ClassStaticBlockDeclaration */:
        const containingClass = thisContainer.parent;
        const symbolTable = isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members;
        if (hasDynamicName(node)) {
          bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable);
        } else {
          declareSymbol(
            symbolTable,
            containingClass.symbol,
            node,
            4 /* Property */ | 67108864 /* Assignment */,
            0 /* None */,
            /*isReplaceableByMethod*/
            true
          );
        }
        break;
      case 307 /* SourceFile */:
        if (hasDynamicName(node)) {
          break;
        } else if (thisContainer.commonJsModuleIndicator) {
          declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
        } else {
          declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
        }
        break;
      // Namespaces are not allowed in javascript files, so do nothing here
      case 267 /* ModuleDeclaration */:
        break;
      default:
        Debug.failBadSyntaxKind(thisContainer);
    }
  }
  function bindDynamicallyNamedThisPropertyAssignment(node, symbol, symbolTable) {
    declareSymbol(
      symbolTable,
      symbol,
      node,
      4 /* Property */,
      0 /* None */,
      /*isReplaceableByMethod*/
      true,
      /*isComputedName*/
      true
    );
    addLateBoundAssignmentDeclarationToSymbol(node, symbol);
  }
  function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
    if (symbol) {
      (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = /* @__PURE__ */ new Map())).set(getNodeId(node), node);
    }
  }
  function bindSpecialPropertyDeclaration(node) {
    if (node.expression.kind === 110 /* ThisKeyword */) {
      bindThisPropertyAssignment(node);
    } else if (isBindableStaticAccessExpression(node) && node.parent.parent.kind === 307 /* SourceFile */) {
      if (isPrototypeAccess(node.expression)) {
        bindPrototypePropertyAssignment(node, node.parent);
      } else {
        bindStaticPropertyAssignment(node);
      }
    }
  }
  function bindPrototypeAssignment(node) {
    setParent(node.left, node);
    setParent(node.right, node);
    bindPropertyAssignment(
      node.left.expression,
      node.left,
      /*isPrototypeProperty*/
      false,
      /*containerIsClass*/
      true
    );
  }
  function bindObjectDefinePrototypeProperty(node) {
    const namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
    if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
      addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
    }
    bindPotentiallyNewExpandoMemberToNamespace(
      node,
      namespaceSymbol,
      /*isPrototypeProperty*/
      true
    );
  }
  function bindPrototypePropertyAssignment(lhs, parent2) {
    const classPrototype = lhs.expression;
    const constructorFunction = classPrototype.expression;
    setParent(constructorFunction, classPrototype);
    setParent(classPrototype, lhs);
    setParent(lhs, parent2);
    bindPropertyAssignment(
      constructorFunction,
      lhs,
      /*isPrototypeProperty*/
      true,
      /*containerIsClass*/
      true
    );
  }
  function bindObjectDefinePropertyAssignment(node) {
    let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
    const isToplevel = node.parent.parent.kind === 307 /* SourceFile */;
    namespaceSymbol = bindPotentiallyMissingNamespaces(
      namespaceSymbol,
      node.arguments[0],
      isToplevel,
      /*isPrototypeProperty*/
      false,
      /*containerIsClass*/
      false
    );
    bindPotentiallyNewExpandoMemberToNamespace(
      node,
      namespaceSymbol,
      /*isPrototypeProperty*/
      false
    );
  }
  function bindSpecialPropertyAssignment(node) {
    var _a;
    const parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer) || lookupSymbolForPropertyAccess(node.left.expression, container);
    if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) {
      return;
    }
    const rootExpr = getLeftmostAccessExpression(node.left);
    if (isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) == null ? void 0 : _a.flags) & 2097152 /* Alias */) {
      return;
    }
    setParent(node.left, node);
    setParent(node.right, node);
    if (isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
      bindExportsPropertyAssignment(node);
    } else if (hasDynamicName(node)) {
      bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
      const sym = bindPotentiallyMissingNamespaces(
        parentSymbol,
        node.left.expression,
        isTopLevelNamespaceAssignment(node.left),
        /*isPrototypeProperty*/
        false,
        /*containerIsClass*/
        false
      );
      addLateBoundAssignmentDeclarationToSymbol(node, sym);
    } else {
      bindStaticPropertyAssignment(cast(node.left, isBindableStaticNameExpression));
    }
  }
  function bindStaticPropertyAssignment(node) {
    Debug.assert(!isIdentifier(node));
    setParent(node.expression, node);
    bindPropertyAssignment(
      node.expression,
      node,
      /*isPrototypeProperty*/
      false,
      /*containerIsClass*/
      false
    );
  }
  function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
    if ((namespaceSymbol == null ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
      return namespaceSymbol;
    }
    if (isToplevel && !isPrototypeProperty) {
      const flags = 1536 /* Module */ | 67108864 /* Assignment */;
      const excludeFlags = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
      namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, (id, symbol, parent2) => {
        if (symbol) {
          addDeclarationToSymbol(symbol, id, flags);
          return symbol;
        } else {
          const table = parent2 ? parent2.exports : file.jsGlobalAugmentations || (file.jsGlobalAugmentations = createSymbolTable());
          return declareSymbol(table, parent2, id, flags, excludeFlags);
        }
      });
    }
    if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
      addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
    }
    return namespaceSymbol;
  }
  function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
    if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
      return;
    }
    const symbolTable = isPrototypeProperty ? namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable()) : namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable());
    let includes = 0 /* None */;
    let excludes = 0 /* None */;
    if (isFunctionLikeDeclaration(getAssignedExpandoInitializer(declaration))) {
      includes = 8192 /* Method */;
      excludes = 103359 /* MethodExcludes */;
    } else if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) {
      if (some(declaration.arguments[2].properties, (p) => {
        const id = getNameOfDeclaration(p);
        return !!id && isIdentifier(id) && idText(id) === "set";
      })) {
        includes |= 65536 /* SetAccessor */ | 4 /* Property */;
        excludes |= 78783 /* SetAccessorExcludes */;
      }
      if (some(declaration.arguments[2].properties, (p) => {
        const id = getNameOfDeclaration(p);
        return !!id && isIdentifier(id) && idText(id) === "get";
      })) {
        includes |= 32768 /* GetAccessor */ | 4 /* Property */;
        excludes |= 46015 /* GetAccessorExcludes */;
      }
    }
    if (includes === 0 /* None */) {
      includes = 4 /* Property */;
      excludes = 0 /* PropertyExcludes */;
    }
    declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
  }
  function isTopLevelNamespaceAssignment(propertyAccess) {
    return isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 307 /* SourceFile */ : propertyAccess.parent.parent.kind === 307 /* SourceFile */;
  }
  function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
    let namespaceSymbol = lookupSymbolForPropertyAccess(name, blockScopeContainer) || lookupSymbolForPropertyAccess(name, container);
    const isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
    namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
    bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
  }
  function isExpandoSymbol(symbol) {
    if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
      return true;
    }
    const node = symbol.valueDeclaration;
    if (node && isCallExpression(node)) {
      return !!getAssignedExpandoInitializer(node);
    }
    let init = !node ? void 0 : isVariableDeclaration(node) ? node.initializer : isBinaryExpression(node) ? node.right : isPropertyAccessExpression(node) && isBinaryExpression(node.parent) ? node.parent.right : void 0;
    init = init && getRightMostAssignedExpression(init);
    if (init) {
      const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node);
      return !!getExpandoInitializer(isBinaryExpression(init) && (init.operatorToken.kind === 57 /* BarBarToken */ || init.operatorToken.kind === 61 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
    }
    return false;
  }
  function getParentOfBinaryExpression(expr) {
    while (isBinaryExpression(expr.parent)) {
      expr = expr.parent;
    }
    return expr.parent;
  }
  function lookupSymbolForPropertyAccess(node, lookupContainer = container) {
    if (isIdentifier(node)) {
      return lookupSymbolForName(lookupContainer, node.escapedText);
    } else {
      const symbol = lookupSymbolForPropertyAccess(node.expression);
      return symbol && symbol.exports && symbol.exports.get(getElementOrPropertyAccessName(node));
    }
  }
  function forEachIdentifierInEntityName(e, parent2, action) {
    if (isExportsOrModuleExportsOrAlias(file, e)) {
      return file.symbol;
    } else if (isIdentifier(e)) {
      return action(e, lookupSymbolForPropertyAccess(e), parent2);
    } else {
      const s = forEachIdentifierInEntityName(e.expression, parent2, action);
      const name = getNameOrArgument(e);
      if (isPrivateIdentifier(name)) {
        Debug.fail("unexpected PrivateIdentifier");
      }
      return action(name, s && s.exports && s.exports.get(getElementOrPropertyAccessName(e)), s);
    }
  }
  function bindCallExpression(node) {
    if (!file.commonJsModuleIndicator && isRequireCall(
      node,
      /*requireStringLiteralLikeArgument*/
      false
    )) {
      setCommonJsModuleIndicator(node);
    }
  }
  function bindClassLikeDeclaration(node) {
    if (node.kind === 263 /* ClassDeclaration */) {
      bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
    } else {
      const bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
      bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
      if (node.name) {
        classifiableNames.add(node.name.escapedText);
      }
    }
    const { symbol } = node;
    const prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
    const symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
    if (symbolExport) {
      if (node.name) {
        setParent(node.name, node);
      }
      file.bindDiagnostics.push(createDiagnosticForNode2(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol)));
    }
    symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
    prototypeSymbol.parent = symbol;
  }
  function bindEnumDeclaration(node) {
    return isEnumConst(node) ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
  }
  function bindVariableDeclarationOrBindingElement(node) {
    if (inStrictMode) {
      checkStrictModeEvalOrArguments(node, node.name);
    }
    if (!isBindingPattern(node.name)) {
      const possibleVariableDecl = node.kind === 260 /* VariableDeclaration */ ? node : node.parent.parent;
      if (isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & 32 /* Export */)) {
        declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
      } else if (isBlockOrCatchScoped(node)) {
        bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
      } else if (isPartOfParameterDeclaration(node)) {
        declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
      } else {
        declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
      }
    }
  }
  function bindParameter(node) {
    if (node.kind === 341 /* JSDocParameterTag */ && container.kind !== 323 /* JSDocSignature */) {
      return;
    }
    if (inStrictMode && !(node.flags & 33554432 /* Ambient */)) {
      checkStrictModeEvalOrArguments(node, node.name);
    }
    if (isBindingPattern(node.name)) {
      bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
    } else {
      declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
    }
    if (isParameterPropertyDeclaration(node, node.parent)) {
      const classDeclaration = node.parent.parent;
      declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
    }
  }
  function bindFunctionDeclaration(node) {
    if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) {
      if (isAsyncFunction(node)) {
        emitFlags |= 4096 /* HasAsyncFunctions */;
      }
    }
    checkStrictModeFunctionName(node);
    if (inStrictMode) {
      checkStrictModeFunctionDeclaration(node);
      bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
    } else {
      declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
    }
  }
  function bindFunctionExpression(node) {
    if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) {
      if (isAsyncFunction(node)) {
        emitFlags |= 4096 /* HasAsyncFunctions */;
      }
    }
    if (currentFlow) {
      node.flowNode = currentFlow;
    }
    checkStrictModeFunctionName(node);
    const bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
    return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
  }
  function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
    if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */) && isAsyncFunction(node)) {
      emitFlags |= 4096 /* HasAsyncFunctions */;
    }
    if (currentFlow && isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
      node.flowNode = currentFlow;
    }
    return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
  }
  function getInferTypeContainer(node) {
    const extendsType = findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n);
    return extendsType && extendsType.parent;
  }
  function bindTypeParameter(node) {
    if (isJSDocTemplateTag(node.parent)) {
      const container2 = getEffectiveContainerForJSDocTemplateTag(node.parent);
      if (container2) {
        Debug.assertNode(container2, canHaveLocals);
        container2.locals ?? (container2.locals = createSymbolTable());
        declareSymbol(
          container2.locals,
          /*parent*/
          void 0,
          node,
          262144 /* TypeParameter */,
          526824 /* TypeParameterExcludes */
        );
      } else {
        declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
      }
    } else if (node.parent.kind === 195 /* InferType */) {
      const container2 = getInferTypeContainer(node.parent);
      if (container2) {
        Debug.assertNode(container2, canHaveLocals);
        container2.locals ?? (container2.locals = createSymbolTable());
        declareSymbol(
          container2.locals,
          /*parent*/
          void 0,
          node,
          262144 /* TypeParameter */,
          526824 /* TypeParameterExcludes */
        );
      } else {
        bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node));
      }
    } else {
      declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
    }
  }
  function shouldReportErrorOnModuleDeclaration(node) {
    const instanceState = getModuleInstanceState(node);
    return instanceState === 1 /* Instantiated */ || instanceState === 2 /* ConstEnumOnly */ && shouldPreserveConstEnums(options);
  }
  function checkUnreachable(node) {
    if (!(currentFlow.flags & 1 /* Unreachable */)) {
      return false;
    }
    if (currentFlow === unreachableFlow) {
      const reportError = (
        // report error on all statements except empty ones
        isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || // report error on class declarations
        node.kind === 263 /* ClassDeclaration */ || // report errors on enums with preserved emit
        isEnumDeclarationWithPreservedEmit(node, options) || // report error on instantiated modules
        node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)
      );
      if (reportError) {
        currentFlow = reportedUnreachableFlow;
        if (!options.allowUnreachableCode) {
          const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */) || node.declarationList.declarations.some((d) => !!d.initializer));
          eachUnreachableRange(node, options, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected));
        }
      }
    }
    return true;
  }
}
function isEnumDeclarationWithPreservedEmit(node, options) {
  return node.kind === 266 /* EnumDeclaration */ && (!isEnumConst(node) || shouldPreserveConstEnums(options));
}
function eachUnreachableRange(node, options, cb) {
  if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) {
    const { statements } = node.parent;
    const slice = sliceAfter(statements, node);
    getRangesWhere(slice, isExecutableStatement, (start, afterEnd) => cb(slice[start], slice[afterEnd - 1]));
  } else {
    cb(node, node);
  }
  function isExecutableStatement(s) {
    return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && // `var x;` may declare a variable used above
    !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some((d) => !d.initializer));
  }
  function isPurelyTypeDeclaration(s) {
    switch (s.kind) {
      case 264 /* InterfaceDeclaration */:
      case 265 /* TypeAliasDeclaration */:
        return true;
      case 267 /* ModuleDeclaration */:
        return getModuleInstanceState(s) !== 1 /* Instantiated */;
      case 266 /* EnumDeclaration */:
        return !isEnumDeclarationWithPreservedEmit(s, options);
      default:
        return false;
    }
  }
}
function isExportsOrModuleExportsOrAlias(sourceFile, node) {
  let i = 0;
  const q = createQueue();
  q.enqueue(node);
  while (!q.isEmpty() && i < 100) {
    i++;
    node = q.dequeue();
    if (isExportsIdentifier(node) || isModuleExportsAccessExpression(node)) {
      return true;
    } else if (isIdentifier(node)) {
      const symbol = lookupSymbolForName(sourceFile, node.escapedText);
      if (!!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
        const init = symbol.valueDeclaration.initializer;
        q.enqueue(init);
        if (isAssignmentExpression(
          init,
          /*excludeCompoundAssignment*/
          true
        )) {
          q.enqueue(init.left);
          q.enqueue(init.right);
        }
      }
    }
  }
  return false;
}
function getContainerFlags(node) {
  switch (node.kind) {
    case 231 /* ClassExpression */:
    case 263 /* ClassDeclaration */:
    case 266 /* EnumDeclaration */:
    case 210 /* ObjectLiteralExpression */:
    case 187 /* TypeLiteral */:
    case 322 /* JSDocTypeLiteral */:
    case 292 /* JsxAttributes */:
      return 1 /* IsContainer */;
    case 264 /* InterfaceDeclaration */:
      return 1 /* IsContainer */ | 64 /* IsInterface */;
    case 267 /* ModuleDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 200 /* MappedType */:
    case 181 /* IndexSignature */:
      return 1 /* IsContainer */ | 32 /* HasLocals */;
    case 307 /* SourceFile */:
      return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 174 /* MethodDeclaration */:
      if (isObjectLiteralOrClassExpressionMethodOrAccessor(node)) {
        return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */;
      }
    // falls through
    case 176 /* Constructor */:
    case 262 /* FunctionDeclaration */:
    case 173 /* MethodSignature */:
    case 179 /* CallSignature */:
    case 323 /* JSDocSignature */:
    case 317 /* JSDocFunctionType */:
    case 184 /* FunctionType */:
    case 180 /* ConstructSignature */:
    case 185 /* ConstructorType */:
    case 175 /* ClassStaticBlockDeclaration */:
      return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
    case 218 /* FunctionExpression */:
    case 219 /* ArrowFunction */:
      return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
    case 268 /* ModuleBlock */:
      return 4 /* IsControlFlowContainer */;
    case 172 /* PropertyDeclaration */:
      return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
    case 299 /* CatchClause */:
    case 248 /* ForStatement */:
    case 249 /* ForInStatement */:
    case 250 /* ForOfStatement */:
    case 269 /* CaseBlock */:
      return 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */;
    case 241 /* Block */:
      return isFunctionLike(node.parent) || isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */;
  }
  return 0 /* None */;
}
function lookupSymbolForName(container, name) {
  var _a, _b, _c, _d;
  const local = (_b = (_a = tryCast(container, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name);
  if (local) {
    return local.exportSymbol ?? local;
  }
  if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
    return container.jsGlobalAugmentations.get(name);
  }
  if (canHaveSymbol(container)) {
    return (_d = (_c = container.symbol) == null ? void 0 : _c.exports) == null ? void 0 : _d.get(name);
  }
}

// src/compiler/symbolWalker.ts
function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, getFirstIdentifier2, getTypeArguments) {
  return getSymbolWalker;
  function getSymbolWalker(accept = () => true) {
    const visitedTypes = [];
    const visitedSymbols = [];
    return {
      walkType: (type) => {
        try {
          visitType(type);
          return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) };
        } finally {
          clear(visitedTypes);
          clear(visitedSymbols);
        }
      },
      walkSymbol: (symbol) => {
        try {
          visitSymbol(symbol);
          return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) };
        } finally {
          clear(visitedTypes);
          clear(visitedSymbols);
        }
      }
    };
    function visitType(type) {
      if (!type) {
        return;
      }
      if (visitedTypes[type.id]) {
        return;
      }
      visitedTypes[type.id] = type;
      const shouldBail = visitSymbol(type.symbol);
      if (shouldBail) return;
      if (type.flags & 524288 /* Object */) {
        const objectType = type;
        const objectFlags = objectType.objectFlags;
        if (objectFlags & 4 /* Reference */) {
          visitTypeReference(type);
        }
        if (objectFlags & 32 /* Mapped */) {
          visitMappedType(type);
        }
        if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
          visitInterfaceType(type);
        }
        if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
          visitObjectType(objectType);
        }
      }
      if (type.flags & 262144 /* TypeParameter */) {
        visitTypeParameter(type);
      }
      if (type.flags & 3145728 /* UnionOrIntersection */) {
        visitUnionOrIntersectionType(type);
      }
      if (type.flags & 4194304 /* Index */) {
        visitIndexType(type);
      }
      if (type.flags & 8388608 /* IndexedAccess */) {
        visitIndexedAccessType(type);
      }
    }
    function visitTypeReference(type) {
      visitType(type.target);
      forEach(getTypeArguments(type), visitType);
    }
    function visitTypeParameter(type) {
      visitType(getConstraintOfTypeParameter(type));
    }
    function visitUnionOrIntersectionType(type) {
      forEach(type.types, visitType);
    }
    function visitIndexType(type) {
      visitType(type.type);
    }
    function visitIndexedAccessType(type) {
      visitType(type.objectType);
      visitType(type.indexType);
      visitType(type.constraint);
    }
    function visitMappedType(type) {
      visitType(type.typeParameter);
      visitType(type.constraintType);
      visitType(type.templateType);
      visitType(type.modifiersType);
    }
    function visitSignature(signature) {
      const typePredicate = getTypePredicateOfSignature(signature);
      if (typePredicate) {
        visitType(typePredicate.type);
      }
      forEach(signature.typeParameters, visitType);
      for (const parameter of signature.parameters) {
        visitSymbol(parameter);
      }
      visitType(getRestTypeOfSignature(signature));
      visitType(getReturnTypeOfSignature(signature));
    }
    function visitInterfaceType(interfaceT) {
      visitObjectType(interfaceT);
      forEach(interfaceT.typeParameters, visitType);
      forEach(getBaseTypes(interfaceT), visitType);
      visitType(interfaceT.thisType);
    }
    function visitObjectType(type) {
      const resolved = resolveStructuredTypeMembers(type);
      for (const info of resolved.indexInfos) {
        visitType(info.keyType);
        visitType(info.type);
      }
      for (const signature of resolved.callSignatures) {
        visitSignature(signature);
      }
      for (const signature of resolved.constructSignatures) {
        visitSignature(signature);
      }
      for (const p of resolved.properties) {
        visitSymbol(p);
      }
    }
    function visitSymbol(symbol) {
      if (!symbol) {
        return false;
      }
      const symbolId = getSymbolId(symbol);
      if (visitedSymbols[symbolId]) {
        return false;
      }
      visitedSymbols[symbolId] = symbol;
      if (!accept(symbol)) {
        return true;
      }
      const t = getTypeOfSymbol(symbol);
      visitType(t);
      if (symbol.exports) {
        symbol.exports.forEach(visitSymbol);
      }
      forEach(symbol.declarations, (d) => {
        if (d.type && d.type.kind === 186 /* TypeQuery */) {
          const query = d.type;
          const entity = getResolvedSymbol(getFirstIdentifier2(query.exprName));
          visitSymbol(entity);
        }
      });
      return false;
    }
  }
}

// src/compiler/moduleSpecifiers.ts
var stringToRegex = memoizeOne((pattern) => {
  try {
    let slash = pattern.indexOf("/");
    if (slash !== 0) {
      return new RegExp(pattern);
    }
    const lastSlash = pattern.lastIndexOf("/");
    if (slash === lastSlash) {
      return new RegExp(pattern);
    }
    while ((slash = pattern.indexOf("/", slash + 1)) !== lastSlash) {
      if (pattern[slash - 1] !== "\\") {
        return new RegExp(pattern);
      }
    }
    const flags = pattern.substring(lastSlash + 1).replace(/[^iu]/g, "");
    pattern = pattern.substring(1, lastSlash);
    return new RegExp(pattern, flags);
  } catch {
    return void 0;
  }
});
function getModuleSpecifierPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding, autoImportSpecifierExcludeRegexes }, host, compilerOptions, importingSourceFile, oldImportSpecifier) {
  const filePreferredEnding = getPreferredEnding();
  return {
    excludeRegexes: autoImportSpecifierExcludeRegexes,
    relativePreference: oldImportSpecifier !== void 0 ? isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */ : importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ : 2 /* Shortest */,
    getAllowedEndingsInPreferredOrder: (syntaxImpliedNodeFormat) => {
      const impliedNodeFormat = getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions);
      const preferredEnding = syntaxImpliedNodeFormat !== impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding;
      const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
      if ((syntaxImpliedNodeFormat ?? impliedNodeFormat) === 99 /* ESNext */ && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) {
        if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) {
          return [3 /* TsExtension */, 2 /* JsExtension */];
        }
        return [2 /* JsExtension */];
      }
      if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) {
        return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */];
      }
      const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName);
      switch (preferredEnding) {
        case 2 /* JsExtension */:
          return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */];
        case 3 /* TsExtension */:
          return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */];
        case 1 /* Index */:
          return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */];
        case 0 /* Minimal */:
          return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */];
        default:
          Debug.assertNever(preferredEnding);
      }
    }
  };
  function getPreferredEnding(resolutionMode) {
    if (oldImportSpecifier !== void 0) {
      if (hasJSFileExtension(oldImportSpecifier)) return 2 /* JsExtension */;
      if (endsWith(oldImportSpecifier, "/index")) return 1 /* Index */;
    }
    return getModuleSpecifierEndingPreference(
      importModuleSpecifierEnding,
      resolutionMode ?? getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions),
      compilerOptions,
      isFullSourceFile(importingSourceFile) ? importingSourceFile : void 0
    );
  }
}
function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) {
  var _a;
  const moduleSourceFile = getSourceFileOfModule(moduleSymbol);
  if (!moduleSourceFile) {
    return emptyArray;
  }
  const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host);
  const cached = cache == null ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options);
  return [cached == null ? void 0 : cached.kind, cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache];
}
function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}) {
  return getModuleSpecifiersWithCacheInfo(
    moduleSymbol,
    checker,
    compilerOptions,
    importingSourceFile,
    host,
    userPreferences,
    options,
    /*forAutoImport*/
    false
  ).moduleSpecifiers;
}
function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) {
  let computedWithoutCache = false;
  const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
  if (ambient) {
    return {
      kind: "ambient",
      moduleSpecifiers: !(forAutoImport && isExcludedByRegex(ambient, userPreferences.autoImportSpecifierExcludeRegexes)) ? [ambient] : emptyArray,
      computedWithoutCache
    };
  }
  let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(
    moduleSymbol,
    importingSourceFile,
    host,
    userPreferences,
    options
  );
  if (specifiers) return { kind, moduleSpecifiers: specifiers, computedWithoutCache };
  if (!moduleSourceFile) return { kind: void 0, moduleSpecifiers: emptyArray, computedWithoutCache };
  computedWithoutCache = true;
  modulePaths || (modulePaths = getAllModulePathsWorker(getInfo(importingSourceFile.fileName, host), moduleSourceFile.originalFileName, host, compilerOptions, options));
  const result = computeModuleSpecifiers(
    modulePaths,
    compilerOptions,
    importingSourceFile,
    host,
    userPreferences,
    options,
    forAutoImport
  );
  cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers);
  return result;
}
function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) {
  const info = getInfo(importingSourceFile.fileName, host);
  const preferences = getModuleSpecifierPreferences(userPreferences, host, compilerOptions, importingSourceFile);
  const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, (modulePath) => forEach(
    host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)),
    (reason) => {
      if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) return void 0;
      const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index);
      const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile);
      if (existingMode !== targetMode && existingMode !== void 0 && targetMode !== void 0) {
        return void 0;
      }
      const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
      return preferences.relativePreference !== 1 /* NonRelative */ || !pathIsRelative(specifier) ? specifier : void 0;
    }
  ));
  if (existingSpecifier) {
    return { kind: void 0, moduleSpecifiers: [existingSpecifier], computedWithoutCache: true };
  }
  const importedFileIsInNodeModules = some(modulePaths, (p) => p.isInNodeModules);
  let nodeModulesSpecifiers;
  let pathsSpecifiers;
  let redirectPathsSpecifiers;
  let relativeSpecifiers;
  for (const modulePath of modulePaths) {
    const specifier = modulePath.isInNodeModules ? tryGetModuleNameAsNodeModule(
      modulePath,
      info,
      importingSourceFile,
      host,
      compilerOptions,
      userPreferences,
      /*packageNameOnly*/
      void 0,
      options.overrideImportMode
    ) : void 0;
    if (specifier && !(forAutoImport && isExcludedByRegex(specifier, preferences.excludeRegexes))) {
      nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier);
      if (modulePath.isRedirect) {
        return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true };
      }
    }
    const local = getLocalModuleSpecifier(
      modulePath.path,
      info,
      compilerOptions,
      host,
      options.overrideImportMode || importingSourceFile.impliedNodeFormat,
      preferences,
      /*pathsOnly*/
      modulePath.isRedirect || !!specifier
    );
    if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) {
      continue;
    }
    if (modulePath.isRedirect) {
      redirectPathsSpecifiers = append(redirectPathsSpecifiers, local);
    } else if (pathIsBareSpecifier(local)) {
      if (pathContainsNodeModules(local)) {
        relativeSpecifiers = append(relativeSpecifiers, local);
      } else {
        pathsSpecifiers = append(pathsSpecifiers, local);
      }
    } else if (forAutoImport || !importedFileIsInNodeModules || modulePath.isInNodeModules) {
      relativeSpecifiers = append(relativeSpecifiers, local);
    }
  }
  return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: relativeSpecifiers ?? emptyArray, computedWithoutCache: true };
}
function isExcludedByRegex(moduleSpecifier, excludeRegexes) {
  return some(excludeRegexes, (pattern) => {
    var _a;
    return !!((_a = stringToRegex(pattern)) == null ? void 0 : _a.test(moduleSpecifier));
  });
}
function getInfo(importingSourceFileName, host) {
  importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory());
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
  const sourceDirectory = getDirectoryPath(importingSourceFileName);
  return {
    getCanonicalFileName,
    importingSourceFileName,
    sourceDirectory,
    canonicalSourceDirectory: getCanonicalFileName(sourceDirectory)
  };
}
function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference, excludeRegexes }, pathsOnly) {
  const { baseUrl, paths, rootDirs } = compilerOptions;
  if (pathsOnly && !paths) {
    return void 0;
  }
  const { sourceDirectory, canonicalSourceDirectory, getCanonicalFileName } = info;
  const allowedEndings = getAllowedEndingsInPrefererredOrder(importMode);
  const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) || processEnding(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), allowedEndings, compilerOptions);
  if (!baseUrl && !paths && !getResolvePackageJsonImports(compilerOptions) || relativePreference === 0 /* Relative */) {
    return pathsOnly ? void 0 : relativePath;
  }
  const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory());
  const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName);
  if (!relativeToBaseUrl) {
    return pathsOnly ? void 0 : relativePath;
  }
  const fromPackageJsonImports = pathsOnly ? void 0 : tryGetModuleNameFromPackageJsonImports(
    moduleFileName,
    sourceDirectory,
    compilerOptions,
    host,
    importMode,
    prefersTsExtension(allowedEndings)
  );
  const fromPaths = pathsOnly || fromPackageJsonImports === void 0 ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) : void 0;
  if (pathsOnly) {
    return fromPaths;
  }
  const maybeNonRelative = fromPackageJsonImports ?? (fromPaths === void 0 && baseUrl !== void 0 ? processEnding(relativeToBaseUrl, allowedEndings, compilerOptions) : fromPaths);
  if (!maybeNonRelative) {
    return relativePath;
  }
  const relativeIsExcluded = isExcludedByRegex(relativePath, excludeRegexes);
  const nonRelativeIsExcluded = isExcludedByRegex(maybeNonRelative, excludeRegexes);
  if (!relativeIsExcluded && nonRelativeIsExcluded) {
    return relativePath;
  }
  if (relativeIsExcluded && !nonRelativeIsExcluded) {
    return maybeNonRelative;
  }
  if (relativePreference === 1 /* NonRelative */ && !pathIsRelative(maybeNonRelative)) {
    return maybeNonRelative;
  }
  if (relativePreference === 3 /* ExternalNonRelative */ && !pathIsRelative(maybeNonRelative)) {
    const projectDirectory = compilerOptions.configFilePath ? toPath(getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : info.getCanonicalFileName(host.getCurrentDirectory());
    const modulePath = toPath(moduleFileName, projectDirectory, getCanonicalFileName);
    const sourceIsInternal = startsWith(canonicalSourceDirectory, projectDirectory);
    const targetIsInternal = startsWith(modulePath, projectDirectory);
    if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) {
      return maybeNonRelative;
    }
    const nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, getDirectoryPath(modulePath));
    const nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
    const ignoreCase = !hostUsesCaseSensitiveFileNames(host);
    if (!packageJsonPathsAreEqual(nearestTargetPackageJson, nearestSourcePackageJson, ignoreCase)) {
      return maybeNonRelative;
    }
    return relativePath;
  }
  return isPathRelativeToParent(maybeNonRelative) || countPathComponents(relativePath) < countPathComponents(maybeNonRelative) ? relativePath : maybeNonRelative;
}
function packageJsonPathsAreEqual(a, b, ignoreCase) {
  if (a === b) return true;
  if (a === void 0 || b === void 0) return false;
  return comparePaths(a, b, ignoreCase) === 0 /* EqualTo */;
}
function countPathComponents(path) {
  let count = 0;
  for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
    if (path.charCodeAt(i) === 47 /* slash */) count++;
  }
  return count;
}
function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
  return compareBooleans(b.isRedirect, a.isRedirect) || compareNumberOfDirectorySeparators(a.path, b.path);
}
function getNearestAncestorDirectoryWithPackageJson(host, fileName) {
  if (host.getNearestAncestorDirectoryWithPackageJson) {
    return host.getNearestAncestorDirectoryWithPackageJson(fileName);
  }
  return forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    fileName,
    (directory) => host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0
  );
}
function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
  var _a;
  const getCanonicalFileName = hostGetCanonicalFileName(host);
  const cwd = host.getCurrentDirectory();
  const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : void 0;
  const importedPath = toPath(importedFileName, cwd, getCanonicalFileName);
  const redirects = host.redirectTargetsMap.get(importedPath) || emptyArray;
  const importedFileNames = [...referenceRedirect ? [referenceRedirect] : emptyArray, importedFileName, ...redirects];
  const targets = importedFileNames.map((f) => getNormalizedAbsolutePath(f, cwd));
  let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath);
  if (!preferSymlinks) {
    const result2 = forEach(targets, (p) => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p));
    if (result2) return result2;
  }
  const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath();
  const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd);
  const result = symlinkedDirectories && forEachAncestorDirectoryStoppingAtGlobalCache(
    host,
    getDirectoryPath(fullImportedFileName),
    (realPathDirectory) => {
      const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName)));
      if (!symlinkDirectories) return void 0;
      if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
        return false;
      }
      return forEach(targets, (target) => {
        if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
          return;
        }
        const relative = getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
        for (const symlinkDirectory of symlinkDirectories) {
          const option = resolvePath(symlinkDirectory, relative);
          const result2 = cb(option, target === referenceRedirect);
          shouldFilterIgnoredPaths = true;
          if (result2) return result2;
        }
      });
    }
  );
  return result || (preferSymlinks ? forEach(targets, (p) => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0);
}
var runtimeDependencyFields = ["dependencies", "peerDependencies", "optionalDependencies"];
function getAllRuntimeDependencies(packageJson) {
  let result;
  for (const field of runtimeDependencyFields) {
    const deps = packageJson[field];
    if (deps && typeof deps === "object") {
      result = concatenate(result, getOwnKeys(deps));
    }
  }
  return result;
}
function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, options) {
  var _a, _b;
  const cache = (_a = host.getModuleResolutionCache) == null ? void 0 : _a.call(host);
  const links = (_b = host.getSymlinkCache) == null ? void 0 : _b.call(host);
  if (cache && links && host.readFile && !pathContainsNodeModules(info.importingSourceFileName)) {
    Debug.type(host);
    const state = getTemporaryModuleResolutionState(cache.getPackageJsonInfoCache(), host, {});
    const packageJson = getPackageScopeForPath(getDirectoryPath(info.importingSourceFileName), state);
    if (packageJson) {
      const toResolve = getAllRuntimeDependencies(packageJson.contents.packageJsonContent);
      for (const depName of toResolve || emptyArray) {
        const resolved = resolveModuleName(
          depName,
          combinePaths(packageJson.packageDirectory, "package.json"),
          compilerOptions,
          host,
          cache,
          /*redirectedReference*/
          void 0,
          options.overrideImportMode
        );
        links.setSymlinksFromResolution(resolved.resolvedModule);
      }
    }
  }
  const allFileNames = /* @__PURE__ */ new Map();
  let importedFileFromNodeModules = false;
  forEachFileNameOfModule(
    info.importingSourceFileName,
    importedFileName,
    host,
    /*preferSymlinks*/
    true,
    (path, isRedirect) => {
      const isInNodeModules = pathContainsNodeModules(path);
      allFileNames.set(path, { path: info.getCanonicalFileName(path), isRedirect, isInNodeModules });
      importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
    }
  );
  const sortedPaths = [];
  for (let directory = info.canonicalSourceDirectory; allFileNames.size !== 0; ) {
    const directoryStart = ensureTrailingDirectorySeparator(directory);
    let pathsInDirectory;
    allFileNames.forEach(({ path, isRedirect, isInNodeModules }, fileName) => {
      if (startsWith(path, directoryStart)) {
        (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect, isInNodeModules });
        allFileNames.delete(fileName);
      }
    });
    if (pathsInDirectory) {
      if (pathsInDirectory.length > 1) {
        pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
      }
      sortedPaths.push(...pathsInDirectory);
    }
    const newDirectory = getDirectoryPath(directory);
    if (newDirectory === directory) break;
    directory = newDirectory;
  }
  if (allFileNames.size) {
    const remainingPaths = arrayFrom(
      allFileNames.entries(),
      ([fileName, { isRedirect, isInNodeModules }]) => ({ path: fileName, isRedirect, isInNodeModules })
    );
    if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
    sortedPaths.push(...remainingPaths);
  }
  return sortedPaths;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) {
  var _a;
  const decl = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(
    (d) => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))
  );
  if (decl) {
    return decl.name.text;
  }
  const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => {
    var _a2, _b, _c, _d;
    if (!isModuleDeclaration(d)) return;
    const topNamespace = getTopNamespace(d);
    if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return;
    const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression;
    if (!exportAssignment) return;
    const exportSymbol = checker.getSymbolAtLocation(exportAssignment);
    if (!exportSymbol) return;
    const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
    if (originalExportSymbol === d.symbol) return topNamespace.parent.parent;
    function getTopNamespace(namespaceDeclaration) {
      while (namespaceDeclaration.flags & 8 /* NestedNamespace */) {
        namespaceDeclaration = namespaceDeclaration.parent;
      }
      return namespaceDeclaration;
    }
  });
  const ambientModuleDeclare = ambientModuleDeclareCandidates[0];
  if (ambientModuleDeclare) {
    return ambientModuleDeclare.name.text;
  }
}
function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) {
  for (const key in paths) {
    for (const patternText2 of paths[key]) {
      const normalized = normalizePath(patternText2);
      const pattern = getRelativePathIfInSameVolume(normalized, baseDirectory, getCanonicalFileName) ?? normalized;
      const indexOfStar = pattern.indexOf("*");
      const candidates = allowedEndings.map((ending) => ({
        ending,
        value: processEnding(relativeToBaseUrl, [ending], compilerOptions)
      }));
      if (tryGetExtensionFromPath2(pattern)) {
        candidates.push({ ending: void 0, value: relativeToBaseUrl });
      }
      if (indexOfStar !== -1) {
        const prefix = pattern.substring(0, indexOfStar);
        const suffix = pattern.substring(indexOfStar + 1);
        for (const { ending, value } of candidates) {
          if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) {
            const matchedStar = value.substring(prefix.length, value.length - suffix.length);
            if (!pathIsRelative(matchedStar)) {
              return replaceFirstStar(key, matchedStar);
            }
          }
        }
      } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) {
        return key;
      }
    }
  }
  function validateEnding({ ending, value }) {
    return ending !== 0 /* Minimal */ || value === processEnding(relativeToBaseUrl, [ending], compilerOptions, host);
  }
}
function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions, mode, isImports, preferTsExtension) {
  if (typeof exports2 === "string") {
    const ignoreCase = !hostUsesCaseSensitiveFileNames(host);
    const getCommonSourceDirectory2 = () => host.getCommonSourceDirectory();
    const outputFile = isImports && getOutputJSFileNameWorker(targetFilePath, options, ignoreCase, getCommonSourceDirectory2);
    const declarationFile = isImports && getOutputDeclarationFileNameWorker(targetFilePath, options, ignoreCase, getCommonSourceDirectory2);
    const pathOrPattern = getNormalizedAbsolutePath(
      combinePaths(packageDirectory, exports2),
      /*currentDirectory*/
      void 0
    );
    const extensionSwappedTarget = hasTSFileExtension(targetFilePath) ? removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : void 0;
    const canTryTsExtension = preferTsExtension && hasImplementationTSFileExtension(targetFilePath);
    switch (mode) {
      case 0 /* Exact */:
        if (extensionSwappedTarget && comparePaths(extensionSwappedTarget, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || comparePaths(targetFilePath, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || outputFile && comparePaths(outputFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || declarationFile && comparePaths(declarationFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */) {
          return { moduleFileToTry: packageName };
        }
        break;
      case 1 /* Directory */:
        if (canTryTsExtension && containsPath(targetFilePath, pathOrPattern, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            targetFilePath,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: getNormalizedAbsolutePath(
            combinePaths(combinePaths(packageName, exports2), fragment),
            /*currentDirectory*/
            void 0
          ) };
        }
        if (extensionSwappedTarget && containsPath(pathOrPattern, extensionSwappedTarget, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            extensionSwappedTarget,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: getNormalizedAbsolutePath(
            combinePaths(combinePaths(packageName, exports2), fragment),
            /*currentDirectory*/
            void 0
          ) };
        }
        if (!canTryTsExtension && containsPath(pathOrPattern, targetFilePath, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            targetFilePath,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: getNormalizedAbsolutePath(
            combinePaths(combinePaths(packageName, exports2), fragment),
            /*currentDirectory*/
            void 0
          ) };
        }
        if (outputFile && containsPath(pathOrPattern, outputFile, ignoreCase)) {
          const fragment = getRelativePathFromDirectory(
            pathOrPattern,
            outputFile,
            /*ignoreCase*/
            false
          );
          return { moduleFileToTry: combinePaths(packageName, fragment) };
        }
        if (declarationFile && containsPath(pathOrPattern, declarationFile, ignoreCase)) {
          const fragment = changeFullExtension(getRelativePathFromDirectory(
            pathOrPattern,
            declarationFile,
            /*ignoreCase*/
            false
          ), getJSExtensionForFile(declarationFile, options));
          return { moduleFileToTry: combinePaths(packageName, fragment) };
        }
        break;
      case 2 /* Pattern */:
        const starPos = pathOrPattern.indexOf("*");
        const leadingSlice = pathOrPattern.slice(0, starPos);
        const trailingSlice = pathOrPattern.slice(starPos + 1);
        if (canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) {
          const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (extensionSwappedTarget && startsWith(extensionSwappedTarget, leadingSlice, ignoreCase) && endsWith(extensionSwappedTarget, trailingSlice, ignoreCase)) {
          const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (!canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) {
          const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (outputFile && startsWith(outputFile, leadingSlice, ignoreCase) && endsWith(outputFile, trailingSlice, ignoreCase)) {
          const starReplacement = outputFile.slice(leadingSlice.length, outputFile.length - trailingSlice.length);
          return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) };
        }
        if (declarationFile && startsWith(declarationFile, leadingSlice, ignoreCase) && endsWith(declarationFile, trailingSlice, ignoreCase)) {
          const starReplacement = declarationFile.slice(leadingSlice.length, declarationFile.length - trailingSlice.length);
          const substituted = replaceFirstStar(packageName, starReplacement);
          const jsExtension = tryGetJSExtensionForFile(declarationFile, options);
          return jsExtension ? { moduleFileToTry: changeFullExtension(substituted, jsExtension) } : void 0;
        }
        break;
    }
  } else if (Array.isArray(exports2)) {
    return forEach(exports2, (e) => tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, e, conditions, mode, isImports, preferTsExtension));
  } else if (typeof exports2 === "object" && exports2 !== null) {
    for (const key of getOwnKeys(exports2)) {
      if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) {
        const subTarget = exports2[key];
        const result = tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode, isImports, preferTsExtension);
        if (result) {
          return result;
        }
      }
    }
  }
  return void 0;
}
function tryGetModuleNameFromExports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions) {
  if (typeof exports2 === "object" && exports2 !== null && !Array.isArray(exports2) && allKeysStartWithDot(exports2)) {
    return forEach(getOwnKeys(exports2), (k) => {
      const subPackageName = getNormalizedAbsolutePath(
        combinePaths(packageName, k),
        /*currentDirectory*/
        void 0
      );
      const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */;
      return tryGetModuleNameFromExportsOrImports(
        options,
        host,
        targetFilePath,
        packageDirectory,
        subPackageName,
        exports2[k],
        conditions,
        mode,
        /*isImports*/
        false,
        /*preferTsExtension*/
        false
      );
    });
  }
  return tryGetModuleNameFromExportsOrImports(
    options,
    host,
    targetFilePath,
    packageDirectory,
    packageName,
    exports2,
    conditions,
    0 /* Exact */,
    /*isImports*/
    false,
    /*preferTsExtension*/
    false
  );
}
function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, options, host, importMode, preferTsExtension) {
  var _a, _b, _c;
  if (!host.readFile || !getResolvePackageJsonImports(options)) {
    return void 0;
  }
  const ancestorDirectoryWithPackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
  if (!ancestorDirectoryWithPackageJson) {
    return void 0;
  }
  const packageJsonPath = combinePaths(ancestorDirectoryWithPackageJson, "package.json");
  const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
  if (isMissingPackageJsonInfo(cachedPackageJson) || !host.fileExists(packageJsonPath)) {
    return void 0;
  }
  const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath));
  const imports = packageJsonContent == null ? void 0 : packageJsonContent.imports;
  if (!imports) {
    return void 0;
  }
  const conditions = getConditions(options, importMode);
  return (_c = forEach(getOwnKeys(imports), (k) => {
    if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) return void 0;
    const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */;
    return tryGetModuleNameFromExportsOrImports(
      options,
      host,
      moduleFileName,
      ancestorDirectoryWithPackageJson,
      k,
      imports[k],
      conditions,
      mode,
      /*isImports*/
      true,
      preferTsExtension
    );
  })) == null ? void 0 : _c.moduleFileToTry;
}
function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) {
  const normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
  if (normalizedTargetPaths === void 0) {
    return void 0;
  }
  const normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
  const relativePaths = flatMap(normalizedSourcePaths, (sourcePath) => {
    return map(normalizedTargetPaths, (targetPath) => ensurePathIsNonModuleName(getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)));
  });
  const shortest = min(relativePaths, compareNumberOfDirectorySeparators);
  if (!shortest) {
    return void 0;
  }
  return processEnding(shortest, allowedEndings, compilerOptions);
}
function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileName, canonicalSourceDirectory }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) {
  if (!host.fileExists || !host.readFile) {
    return void 0;
  }
  const parts = getNodeModulePathParts(path);
  if (!parts) {
    return void 0;
  }
  const preferences = getModuleSpecifierPreferences(userPreferences, host, options, importingSourceFile);
  const allowedEndings = preferences.getAllowedEndingsInPreferredOrder();
  let moduleSpecifier = path;
  let isPackageRootPath = false;
  if (!packageNameOnly) {
    let packageRootIndex = parts.packageRootIndex;
    let moduleFileName;
    while (true) {
      const { moduleFileToTry, packageRootPath, blockedByExports, verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex);
      if (getEmitModuleResolutionKind(options) !== 1 /* Classic */) {
        if (blockedByExports) {
          return void 0;
        }
        if (verbatimFromExports) {
          return moduleFileToTry;
        }
      }
      if (packageRootPath) {
        moduleSpecifier = packageRootPath;
        isPackageRootPath = true;
        break;
      }
      if (!moduleFileName) moduleFileName = moduleFileToTry;
      packageRootIndex = path.indexOf(directorySeparator, packageRootIndex + 1);
      if (packageRootIndex === -1) {
        moduleSpecifier = processEnding(moduleFileName, allowedEndings, options, host);
        break;
      }
    }
  }
  if (isRedirect && !isPackageRootPath) {
    return void 0;
  }
  const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
  const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
  if (!(startsWith(canonicalSourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
    return void 0;
  }
  const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
  const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
  return getEmitModuleResolutionKind(options) === 1 /* Classic */ && packageName === nodeModulesDirectoryName ? void 0 : packageName;
  function tryDirectoryWithPackageJson(packageRootIndex) {
    var _a, _b;
    const packageRootPath = path.substring(0, packageRootIndex);
    const packageJsonPath = combinePaths(packageRootPath, "package.json");
    let moduleFileToTry = path;
    let maybeBlockedByTypesVersions = false;
    const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
    if (isPackageJsonInfo(cachedPackageJson) || cachedPackageJson === void 0 && host.fileExists(packageJsonPath)) {
      const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath));
      const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options);
      if (getResolvePackageJsonExports(options)) {
        const nodeModulesDirectoryName2 = packageRootPath.substring(parts.topLevelPackageNameIndex + 1);
        const packageName2 = getPackageNameFromTypesPackageName(nodeModulesDirectoryName2);
        const conditions = getConditions(options, importMode);
        const fromExports = (packageJsonContent == null ? void 0 : packageJsonContent.exports) ? tryGetModuleNameFromExports(
          options,
          host,
          path,
          packageRootPath,
          packageName2,
          packageJsonContent.exports,
          conditions
        ) : void 0;
        if (fromExports) {
          return { ...fromExports, verbatimFromExports: true };
        }
        if (packageJsonContent == null ? void 0 : packageJsonContent.exports) {
          return { moduleFileToTry: path, blockedByExports: true };
        }
      }
      const versionPaths = (packageJsonContent == null ? void 0 : packageJsonContent.typesVersions) ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) : void 0;
      if (versionPaths) {
        const subModuleName = path.slice(packageRootPath.length + 1);
        const fromPaths = tryGetModuleNameFromPaths(
          subModuleName,
          versionPaths.paths,
          allowedEndings,
          packageRootPath,
          getCanonicalFileName,
          host,
          options
        );
        if (fromPaths === void 0) {
          maybeBlockedByTypesVersions = true;
        } else {
          moduleFileToTry = combinePaths(packageRootPath, fromPaths);
        }
      }
      const mainFileRelative = (packageJsonContent == null ? void 0 : packageJsonContent.typings) || (packageJsonContent == null ? void 0 : packageJsonContent.types) || (packageJsonContent == null ? void 0 : packageJsonContent.main) || "index.js";
      if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) {
        const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
        const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry);
        if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) {
          return { packageRootPath, moduleFileToTry };
        } else if ((packageJsonContent == null ? void 0 : packageJsonContent.type) !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") {
          return { packageRootPath, moduleFileToTry };
        }
      }
    } else {
      const fileName = getCanonicalFileName(moduleFileToTry.substring(parts.packageRootIndex + 1));
      if (fileName === "index.d.ts" || fileName === "index.js" || fileName === "index.ts" || fileName === "index.tsx") {
        return { moduleFileToTry, packageRootPath };
      }
    }
    return { moduleFileToTry };
  }
}
function tryGetAnyFileFromPath(host, path) {
  if (!host.fileExists) return;
  const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]));
  for (const e of extensions) {
    const fullPath = path + e;
    if (host.fileExists(fullPath)) {
      return fullPath;
    }
  }
}
function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
  return mapDefined(rootDirs, (rootDir) => {
    const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName);
    return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath;
  });
}
function processEnding(fileName, allowedEndings, options, host) {
  if (fileExtensionIsOneOf(fileName, [".json" /* Json */, ".mjs" /* Mjs */, ".cjs" /* Cjs */])) {
    return fileName;
  }
  const noExtension = removeFileExtension(fileName);
  if (fileName === noExtension) {
    return fileName;
  }
  const jsPriority = allowedEndings.indexOf(2 /* JsExtension */);
  const tsPriority = allowedEndings.indexOf(3 /* TsExtension */);
  if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) {
    return fileName;
  } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) {
    return noExtension + getJSExtensionForFile(fileName, options);
  } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && fileName.includes(".d.")) {
    return tryGetRealFileNameForNonJsDeclarationFileName(fileName);
  }
  switch (allowedEndings[0]) {
    case 0 /* Minimal */:
      const withoutIndex = removeSuffix(noExtension, "/index");
      if (host && withoutIndex !== noExtension && tryGetAnyFileFromPath(host, withoutIndex)) {
        return noExtension;
      }
      return withoutIndex;
    case 1 /* Index */:
      return noExtension;
    case 2 /* JsExtension */:
      return noExtension + getJSExtensionForFile(fileName, options);
    case 3 /* TsExtension */:
      if (isDeclarationFileName(fileName)) {
        const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */);
        return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options);
      }
      return fileName;
    default:
      return Debug.assertNever(allowedEndings[0]);
  }
}
function tryGetRealFileNameForNonJsDeclarationFileName(fileName) {
  const baseName = getBaseFileName(fileName);
  if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) return void 0;
  const noExtension = removeExtension(fileName, ".ts" /* Ts */);
  const ext = noExtension.substring(noExtension.lastIndexOf("."));
  return noExtension.substring(0, noExtension.indexOf(".d.")) + ext;
}
function getJSExtensionForFile(fileName, options) {
  return tryGetJSExtensionForFile(fileName, options) ?? Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`);
}
function tryGetJSExtensionForFile(fileName, options) {
  const ext = tryGetExtensionFromPath2(fileName);
  switch (ext) {
    case ".ts" /* Ts */:
    case ".d.ts" /* Dts */:
      return ".js" /* Js */;
    case ".tsx" /* Tsx */:
      return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
    case ".js" /* Js */:
    case ".jsx" /* Jsx */:
    case ".json" /* Json */:
      return ext;
    case ".d.mts" /* Dmts */:
    case ".mts" /* Mts */:
    case ".mjs" /* Mjs */:
      return ".mjs" /* Mjs */;
    case ".d.cts" /* Dcts */:
    case ".cts" /* Cts */:
    case ".cjs" /* Cjs */:
      return ".cjs" /* Cjs */;
    default:
      return void 0;
  }
}
function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) {
  const relativePath = getRelativePathToDirectoryOrUrl(
    directoryPath,
    path,
    directoryPath,
    getCanonicalFileName,
    /*isAbsolutePathAnUrl*/
    false
  );
  return isRootedDiskPath(relativePath) ? void 0 : relativePath;
}
function isPathRelativeToParent(path) {
  return startsWith(path, "..");
}
function getDefaultResolutionModeForFile(file, host, compilerOptions) {
  return isFullSourceFile(file) ? host.getDefaultResolutionModeForFile(file) : getDefaultResolutionModeForFileWorker(file, compilerOptions);
}
function prefersTsExtension(allowedEndings) {
  const tsPriority = allowedEndings.indexOf(3 /* TsExtension */);
  return tsPriority > -1 && tsPriority < allowedEndings.indexOf(2 /* JsExtension */);
}

// src/compiler/checker.ts
var ambientModuleSymbolRegex = /^".+"$/;
var anon = "(anonymous)";
var nextSymbolId = 1;
var nextNodeId = 1;
var nextMergeId = 1;
var nextFlowId = 1;
var TypeFacts = /* @__PURE__ */ ((TypeFacts3) => {
  TypeFacts3[TypeFacts3["None"] = 0] = "None";
  TypeFacts3[TypeFacts3["TypeofEQString"] = 1] = "TypeofEQString";
  TypeFacts3[TypeFacts3["TypeofEQNumber"] = 2] = "TypeofEQNumber";
  TypeFacts3[TypeFacts3["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
  TypeFacts3[TypeFacts3["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
  TypeFacts3[TypeFacts3["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
  TypeFacts3[TypeFacts3["TypeofEQObject"] = 32] = "TypeofEQObject";
  TypeFacts3[TypeFacts3["TypeofEQFunction"] = 64] = "TypeofEQFunction";
  TypeFacts3[TypeFacts3["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
  TypeFacts3[TypeFacts3["TypeofNEString"] = 256] = "TypeofNEString";
  TypeFacts3[TypeFacts3["TypeofNENumber"] = 512] = "TypeofNENumber";
  TypeFacts3[TypeFacts3["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
  TypeFacts3[TypeFacts3["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
  TypeFacts3[TypeFacts3["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
  TypeFacts3[TypeFacts3["TypeofNEObject"] = 8192] = "TypeofNEObject";
  TypeFacts3[TypeFacts3["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
  TypeFacts3[TypeFacts3["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
  TypeFacts3[TypeFacts3["EQUndefined"] = 65536] = "EQUndefined";
  TypeFacts3[TypeFacts3["EQNull"] = 131072] = "EQNull";
  TypeFacts3[TypeFacts3["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
  TypeFacts3[TypeFacts3["NEUndefined"] = 524288] = "NEUndefined";
  TypeFacts3[TypeFacts3["NENull"] = 1048576] = "NENull";
  TypeFacts3[TypeFacts3["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
  TypeFacts3[TypeFacts3["Truthy"] = 4194304] = "Truthy";
  TypeFacts3[TypeFacts3["Falsy"] = 8388608] = "Falsy";
  TypeFacts3[TypeFacts3["IsUndefined"] = 16777216] = "IsUndefined";
  TypeFacts3[TypeFacts3["IsNull"] = 33554432] = "IsNull";
  TypeFacts3[TypeFacts3["IsUndefinedOrNull"] = 50331648] = "IsUndefinedOrNull";
  TypeFacts3[TypeFacts3["All"] = 134217727] = "All";
  TypeFacts3[TypeFacts3["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
  TypeFacts3[TypeFacts3["BaseStringFacts"] = 12582401] = "BaseStringFacts";
  TypeFacts3[TypeFacts3["StringStrictFacts"] = 16317953] = "StringStrictFacts";
  TypeFacts3[TypeFacts3["StringFacts"] = 16776705] = "StringFacts";
  TypeFacts3[TypeFacts3["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
  TypeFacts3[TypeFacts3["EmptyStringFacts"] = 12582401 /* BaseStringFacts */] = "EmptyStringFacts";
  TypeFacts3[TypeFacts3["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
  TypeFacts3[TypeFacts3["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
  TypeFacts3[TypeFacts3["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
  TypeFacts3[TypeFacts3["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
  TypeFacts3[TypeFacts3["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
  TypeFacts3[TypeFacts3["NumberFacts"] = 16776450] = "NumberFacts";
  TypeFacts3[TypeFacts3["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
  TypeFacts3[TypeFacts3["ZeroNumberFacts"] = 12582146 /* BaseNumberFacts */] = "ZeroNumberFacts";
  TypeFacts3[TypeFacts3["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
  TypeFacts3[TypeFacts3["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
  TypeFacts3[TypeFacts3["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
  TypeFacts3[TypeFacts3["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
  TypeFacts3[TypeFacts3["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
  TypeFacts3[TypeFacts3["BigIntFacts"] = 16775940] = "BigIntFacts";
  TypeFacts3[TypeFacts3["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
  TypeFacts3[TypeFacts3["ZeroBigIntFacts"] = 12581636 /* BaseBigIntFacts */] = "ZeroBigIntFacts";
  TypeFacts3[TypeFacts3["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
  TypeFacts3[TypeFacts3["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
  TypeFacts3[TypeFacts3["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
  TypeFacts3[TypeFacts3["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
  TypeFacts3[TypeFacts3["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
  TypeFacts3[TypeFacts3["BooleanFacts"] = 16774920] = "BooleanFacts";
  TypeFacts3[TypeFacts3["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
  TypeFacts3[TypeFacts3["FalseFacts"] = 12580616 /* BaseBooleanFacts */] = "FalseFacts";
  TypeFacts3[TypeFacts3["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
  TypeFacts3[TypeFacts3["TrueFacts"] = 16774920] = "TrueFacts";
  TypeFacts3[TypeFacts3["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
  TypeFacts3[TypeFacts3["SymbolFacts"] = 16772880] = "SymbolFacts";
  TypeFacts3[TypeFacts3["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
  TypeFacts3[TypeFacts3["ObjectFacts"] = 16736160] = "ObjectFacts";
  TypeFacts3[TypeFacts3["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
  TypeFacts3[TypeFacts3["FunctionFacts"] = 16728e3] = "FunctionFacts";
  TypeFacts3[TypeFacts3["VoidFacts"] = 9830144] = "VoidFacts";
  TypeFacts3[TypeFacts3["UndefinedFacts"] = 26607360] = "UndefinedFacts";
  TypeFacts3[TypeFacts3["NullFacts"] = 42917664] = "NullFacts";
  TypeFacts3[TypeFacts3["EmptyObjectStrictFacts"] = 83427327] = "EmptyObjectStrictFacts";
  TypeFacts3[TypeFacts3["EmptyObjectFacts"] = 83886079] = "EmptyObjectFacts";
  TypeFacts3[TypeFacts3["UnknownFacts"] = 83886079] = "UnknownFacts";
  TypeFacts3[TypeFacts3["AllTypeofNE"] = 556800] = "AllTypeofNE";
  TypeFacts3[TypeFacts3["OrFactsMask"] = 8256] = "OrFactsMask";
  TypeFacts3[TypeFacts3["AndFactsMask"] = 134209471] = "AndFactsMask";
  return TypeFacts3;
})(TypeFacts || {});
var typeofNEFacts = new Map(Object.entries({
  string: 256 /* TypeofNEString */,
  number: 512 /* TypeofNENumber */,
  bigint: 1024 /* TypeofNEBigInt */,
  boolean: 2048 /* TypeofNEBoolean */,
  symbol: 4096 /* TypeofNESymbol */,
  undefined: 524288 /* NEUndefined */,
  object: 8192 /* TypeofNEObject */,
  function: 16384 /* TypeofNEFunction */
}));
var CheckMode = /* @__PURE__ */ ((CheckMode3) => {
  CheckMode3[CheckMode3["Normal"] = 0] = "Normal";
  CheckMode3[CheckMode3["Contextual"] = 1] = "Contextual";
  CheckMode3[CheckMode3["Inferential"] = 2] = "Inferential";
  CheckMode3[CheckMode3["SkipContextSensitive"] = 4] = "SkipContextSensitive";
  CheckMode3[CheckMode3["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
  CheckMode3[CheckMode3["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
  CheckMode3[CheckMode3["RestBindingElement"] = 32] = "RestBindingElement";
  CheckMode3[CheckMode3["TypeOnly"] = 64] = "TypeOnly";
  return CheckMode3;
})(CheckMode || {});
var SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode3) => {
  SignatureCheckMode3[SignatureCheckMode3["None"] = 0] = "None";
  SignatureCheckMode3[SignatureCheckMode3["BivariantCallback"] = 1] = "BivariantCallback";
  SignatureCheckMode3[SignatureCheckMode3["StrictCallback"] = 2] = "StrictCallback";
  SignatureCheckMode3[SignatureCheckMode3["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
  SignatureCheckMode3[SignatureCheckMode3["StrictArity"] = 8] = "StrictArity";
  SignatureCheckMode3[SignatureCheckMode3["StrictTopSignature"] = 16] = "StrictTopSignature";
  SignatureCheckMode3[SignatureCheckMode3["Callback"] = 3] = "Callback";
  return SignatureCheckMode3;
})(SignatureCheckMode || {});
var isNotOverloadAndNotAccessor = and(isNotOverload, isNotAccessor);
var intrinsicTypeKinds = new Map(Object.entries({
  Uppercase: 0 /* Uppercase */,
  Lowercase: 1 /* Lowercase */,
  Capitalize: 2 /* Capitalize */,
  Uncapitalize: 3 /* Uncapitalize */,
  NoInfer: 4 /* NoInfer */
}));
var SymbolLinks = class {
};
function NodeLinks() {
  this.flags = 0 /* None */;
}
function getNodeId(node) {
  if (!node.id) {
    node.id = nextNodeId;
    nextNodeId++;
  }
  return node.id;
}
function getSymbolId(symbol) {
  if (!symbol.id) {
    symbol.id = nextSymbolId;
    nextSymbolId++;
  }
  return symbol.id;
}
function isInstantiatedModule(node, preserveConstEnums) {
  const moduleState = getModuleInstanceState(node);
  return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */;
}
function createTypeChecker(host) {
  var deferredDiagnosticsCallbacks = [];
  var addLazyDiagnostic = (arg) => {
    deferredDiagnosticsCallbacks.push(arg);
  };
  var cancellationToken;
  var scanner;
  var Symbol13 = objectAllocator.getSymbolConstructor();
  var Type7 = objectAllocator.getTypeConstructor();
  var Signature5 = objectAllocator.getSignatureConstructor();
  var typeCount = 0;
  var symbolCount = 0;
  var totalInstantiationCount = 0;
  var instantiationCount = 0;
  var instantiationDepth = 0;
  var inlineLevel = 0;
  var currentNode;
  var varianceTypeParameter;
  var isInferencePartiallyBlocked = false;
  var emptySymbols = createSymbolTable();
  var arrayVariances = [1 /* Covariant */];
  var compilerOptions = host.getCompilerOptions();
  var languageVersion = getEmitScriptTarget(compilerOptions);
  var moduleKind = getEmitModuleKind(compilerOptions);
  var legacyDecorators = !!compilerOptions.experimentalDecorators;
  var useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
  var emitStandardClassFields = getEmitStandardClassFields(compilerOptions);
  var allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions);
  var strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
  var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes");
  var strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply");
  var strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
  var strictBuiltinIteratorReturn = getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn");
  var noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny");
  var noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis");
  var useUnknownInCatchVariables = getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables");
  var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes;
  var noUncheckedSideEffectImports = !!compilerOptions.noUncheckedSideEffectImports;
  var checkBinaryExpression = createCheckBinaryExpression();
  var emitResolver = createResolver();
  var nodeBuilder = createNodeBuilder();
  var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, nodeBuilder.syntacticBuilderResolver);
  var evaluate = createEvaluator({
    evaluateElementAccessExpression,
    evaluateEntityNameExpression
  });
  var globals = createSymbolTable();
  var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
  undefinedSymbol.declarations = [];
  var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
  globalThisSymbol.exports = globals;
  globalThisSymbol.declarations = [];
  globals.set(globalThisSymbol.escapedName, globalThisSymbol);
  var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
  var requireSymbol = createSymbol(4 /* Property */, "require");
  var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules";
  var canCollectSymbolAliasAccessabilityData = !compilerOptions.verbatimModuleSyntax;
  var apparentArgumentCount;
  var lastGetCombinedNodeFlagsNode;
  var lastGetCombinedNodeFlagsResult = 0 /* None */;
  var lastGetCombinedModifierFlagsNode;
  var lastGetCombinedModifierFlagsResult = 0 /* None */;
  var resolveName = createNameResolver({
    compilerOptions,
    requireSymbol,
    argumentsSymbol,
    globals,
    getSymbolOfDeclaration,
    error,
    getRequiresScopeChangeCache,
    setRequiresScopeChangeCache,
    lookup: getSymbol,
    onPropertyWithInvalidInitializer: checkAndReportErrorForInvalidInitializer,
    onFailedToResolveSymbol,
    onSuccessfullyResolvedSymbol
  });
  var resolveNameForSymbolSuggestion = createNameResolver({
    compilerOptions,
    requireSymbol,
    argumentsSymbol,
    globals,
    getSymbolOfDeclaration,
    error,
    getRequiresScopeChangeCache,
    setRequiresScopeChangeCache,
    lookup: getSuggestionForSymbolNameLookup
  });
  const checker = {
    getNodeCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.nodeCount, 0),
    getIdentifierCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.identifierCount, 0),
    getSymbolCount: () => reduceLeft(host.getSourceFiles(), (n, s) => n + s.symbolCount, symbolCount),
    getTypeCount: () => typeCount,
    getInstantiationCount: () => totalInstantiationCount,
    getRelationCacheSizes: () => ({
      assignable: assignableRelation.size,
      identity: identityRelation.size,
      subtype: subtypeRelation.size,
      strictSubtype: strictSubtypeRelation.size
    }),
    isUndefinedSymbol: (symbol) => symbol === undefinedSymbol,
    isArgumentsSymbol: (symbol) => symbol === argumentsSymbol,
    isUnknownSymbol: (symbol) => symbol === unknownSymbol,
    getMergedSymbol,
    symbolIsValue,
    getDiagnostics,
    getGlobalDiagnostics,
    getRecursionIdentity,
    getUnmatchedProperties,
    getTypeOfSymbolAtLocation: (symbol, locationIn) => {
      const location = getParseTreeNode(locationIn);
      return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
    },
    getTypeOfSymbol,
    getSymbolsOfParameterPropertyDeclaration: (parameterIn, parameterName) => {
      const parameter = getParseTreeNode(parameterIn, isParameter);
      if (parameter === void 0) return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
      Debug.assert(isParameterPropertyDeclaration(parameter, parameter.parent));
      return getSymbolsOfParameterPropertyDeclaration(parameter, escapeLeadingUnderscores(parameterName));
    },
    getDeclaredTypeOfSymbol,
    getPropertiesOfType,
    getPropertyOfType: (type, name) => getPropertyOfType(type, escapeLeadingUnderscores(name)),
    getPrivateIdentifierPropertyOfType: (leftType, name, location) => {
      const node = getParseTreeNode(location);
      if (!node) {
        return void 0;
      }
      const propName = escapeLeadingUnderscores(name);
      const lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
      return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : void 0;
    },
    getTypeOfPropertyOfType: (type, name) => getTypeOfPropertyOfType(type, escapeLeadingUnderscores(name)),
    getIndexInfoOfType: (type, kind) => getIndexInfoOfType(type, kind === 0 /* String */ ? stringType : numberType),
    getIndexInfosOfType,
    getIndexInfosOfIndexSymbol,
    getSignaturesOfType,
    getIndexTypeOfType: (type, kind) => getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType),
    getIndexType: (type) => getIndexType(type),
    getBaseTypes,
    getBaseTypeOfLiteralType,
    getWidenedType,
    getWidenedLiteralType,
    fillMissingTypeArguments,
    getTypeFromTypeNode: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isTypeNode);
      return node ? getTypeFromTypeNode(node) : errorType;
    },
    getParameterType: getTypeAtPosition,
    getParameterIdentifierInfoAtPosition,
    getPromisedTypeOfPromise,
    getAwaitedType: (type) => getAwaitedType(type),
    getReturnTypeOfSignature,
    isNullableType,
    getNullableType,
    getNonNullableType,
    getNonOptionalType: removeOptionalTypeMarker,
    getTypeArguments,
    typeToTypeNode: nodeBuilder.typeToTypeNode,
    typePredicateToTypePredicateNode: nodeBuilder.typePredicateToTypePredicateNode,
    indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
    signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
    symbolToEntityName: nodeBuilder.symbolToEntityName,
    symbolToExpression: nodeBuilder.symbolToExpression,
    symbolToNode: nodeBuilder.symbolToNode,
    symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
    symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
    typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
    getSymbolsInScope: (locationIn, meaning) => {
      const location = getParseTreeNode(locationIn);
      return location ? getSymbolsInScope(location, meaning) : [];
    },
    getSymbolAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getSymbolAtLocation(
        node,
        /*ignoreErrors*/
        true
      ) : void 0;
    },
    getIndexInfosAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getIndexInfosAtLocation(node) : void 0;
    },
    getShorthandAssignmentValueSymbol: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getShorthandAssignmentValueSymbol(node) : void 0;
    },
    getExportSpecifierLocalTargetSymbol: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isExportSpecifier);
      return node ? getExportSpecifierLocalTargetSymbol(node) : void 0;
    },
    getExportSymbolOfSymbol(symbol) {
      return getMergedSymbol(symbol.exportSymbol || symbol);
    },
    getTypeAtLocation: (nodeIn) => {
      const node = getParseTreeNode(nodeIn);
      return node ? getTypeOfNode(node) : errorType;
    },
    getTypeOfAssignmentPattern: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isAssignmentPattern);
      return node && getTypeOfAssignmentPattern(node) || errorType;
    },
    getPropertySymbolOfDestructuringAssignment: (locationIn) => {
      const location = getParseTreeNode(locationIn, isIdentifier);
      return location ? getPropertySymbolOfDestructuringAssignment(location) : void 0;
    },
    signatureToString: (signature, enclosingDeclaration, flags, kind) => {
      return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind);
    },
    typeToString: (type, enclosingDeclaration, flags) => {
      return typeToString(type, getParseTreeNode(enclosingDeclaration), flags);
    },
    symbolToString: (symbol, enclosingDeclaration, meaning, flags) => {
      return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags);
    },
    typePredicateToString: (predicate, enclosingDeclaration, flags) => {
      return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags);
    },
    writeSignature: (signature, enclosingDeclaration, flags, kind, writer) => {
      return signatureToString(signature, getParseTreeNode(enclosingDeclaration), flags, kind, writer);
    },
    writeType: (type, enclosingDeclaration, flags, writer) => {
      return typeToString(type, getParseTreeNode(enclosingDeclaration), flags, writer);
    },
    writeSymbol: (symbol, enclosingDeclaration, meaning, flags, writer) => {
      return symbolToString(symbol, getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
    },
    writeTypePredicate: (predicate, enclosingDeclaration, flags, writer) => {
      return typePredicateToString(predicate, getParseTreeNode(enclosingDeclaration), flags, writer);
    },
    getAugmentedPropertiesOfType,
    getRootSymbols,
    getSymbolOfExpando,
    getContextualType: (nodeIn, contextFlags) => {
      const node = getParseTreeNode(nodeIn, isExpression);
      if (!node) {
        return void 0;
      }
      if (contextFlags & 4 /* Completions */) {
        return runWithInferenceBlockedFromSourceNode(node, () => getContextualType(node, contextFlags));
      }
      return getContextualType(node, contextFlags);
    },
    getContextualTypeForObjectLiteralElement: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike);
      return node ? getContextualTypeForObjectLiteralElement(
        node,
        /*contextFlags*/
        void 0
      ) : void 0;
    },
    getContextualTypeForArgumentAtIndex: (nodeIn, argIndex) => {
      const node = getParseTreeNode(nodeIn, isCallLikeExpression);
      return node && getContextualTypeForArgumentAtIndex(node, argIndex);
    },
    getContextualTypeForJsxAttribute: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isJsxAttributeLike);
      return node && getContextualTypeForJsxAttribute(
        node,
        /*contextFlags*/
        void 0
      );
    },
    isContextSensitive,
    getTypeOfPropertyOfContextualType,
    getFullyQualifiedName,
    getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */),
    getCandidateSignaturesForStringLiteralCompletions,
    getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */)),
    getExpandedParameters,
    hasEffectiveRestParameter,
    containsArgumentsReference,
    getConstantValue: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, canHaveConstantValue);
      return node ? getConstantValue2(node) : void 0;
    },
    isValidPropertyAccess: (nodeIn, propertyName) => {
      const node = getParseTreeNode(nodeIn, isPropertyAccessOrQualifiedNameOrImportTypeNode);
      return !!node && isValidPropertyAccess(node, escapeLeadingUnderscores(propertyName));
    },
    isValidPropertyAccessForCompletions: (nodeIn, type, property) => {
      const node = getParseTreeNode(nodeIn, isPropertyAccessExpression);
      return !!node && isValidPropertyAccessForCompletions(node, type, property);
    },
    getSignatureFromDeclaration: (declarationIn) => {
      const declaration = getParseTreeNode(declarationIn, isFunctionLike);
      return declaration ? getSignatureFromDeclaration(declaration) : void 0;
    },
    isImplementationOfOverload: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isFunctionLike);
      return node ? isImplementationOfOverload(node) : void 0;
    },
    getImmediateAliasedSymbol,
    getAliasedSymbol: resolveAlias,
    getEmitResolver,
    requiresAddingImplicitUndefined,
    getExportsOfModule: getExportsOfModuleAsArray,
    getExportsAndPropertiesOfModule,
    forEachExportAndPropertyOfModule,
    getSymbolWalker: createGetSymbolWalker(
      getRestTypeOfSignature,
      getTypePredicateOfSignature,
      getReturnTypeOfSignature,
      getBaseTypes,
      resolveStructuredTypeMembers,
      getTypeOfSymbol,
      getResolvedSymbol,
      getConstraintOfTypeParameter,
      getFirstIdentifier,
      getTypeArguments
    ),
    getAmbientModules,
    getJsxIntrinsicTagNamesAt,
    isOptionalParameter: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isParameter);
      return node ? isOptionalParameter(node) : false;
    },
    tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol),
    tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol),
    tryFindAmbientModule: (moduleName) => tryFindAmbientModule(
      moduleName,
      /*withAugmentations*/
      true
    ),
    getApparentType,
    getUnionType,
    isTypeAssignableTo,
    createAnonymousType,
    createSignature,
    createSymbol,
    createIndexInfo,
    getAnyType: () => anyType,
    getStringType: () => stringType,
    getStringLiteralType,
    getNumberType: () => numberType,
    getNumberLiteralType,
    getBigIntType: () => bigintType,
    getBigIntLiteralType,
    createPromiseType,
    createArrayType,
    getElementTypeOfArrayType,
    getBooleanType: () => booleanType,
    getFalseType: (fresh) => fresh ? falseType : regularFalseType,
    getTrueType: (fresh) => fresh ? trueType : regularTrueType,
    getVoidType: () => voidType,
    getUndefinedType: () => undefinedType,
    getNullType: () => nullType,
    getESSymbolType: () => esSymbolType,
    getNeverType: () => neverType,
    getOptionalType: () => optionalType,
    getPromiseType: () => getGlobalPromiseType(
      /*reportErrors*/
      false
    ),
    getPromiseLikeType: () => getGlobalPromiseLikeType(
      /*reportErrors*/
      false
    ),
    getAnyAsyncIterableType: () => {
      const type = getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      );
      if (type === emptyGenericType) return void 0;
      return createTypeReference(type, [anyType, anyType, anyType]);
    },
    isSymbolAccessible,
    isArrayType,
    isTupleType,
    isArrayLikeType,
    isEmptyAnonymousObjectType,
    isTypeInvalidDueToUnionDiscriminant,
    getExactOptionalProperties,
    getAllPossiblePropertiesOfTypes,
    getSuggestedSymbolForNonexistentProperty,
    getSuggestedSymbolForNonexistentJSXAttribute,
    getSuggestedSymbolForNonexistentSymbol: (location, name, meaning) => getSuggestedSymbolForNonexistentSymbol(location, escapeLeadingUnderscores(name), meaning),
    getSuggestedSymbolForNonexistentModule,
    getSuggestedSymbolForNonexistentClassMember,
    getBaseConstraintOfType,
    getDefaultFromTypeParameter: (type) => type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : void 0,
    resolveName(name, location, meaning, excludeGlobals) {
      return resolveName(
        location,
        escapeLeadingUnderscores(name),
        meaning,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false,
        excludeGlobals
      );
    },
    getJsxNamespace: (n) => unescapeLeadingUnderscores(getJsxNamespace(n)),
    getJsxFragmentFactory: (n) => {
      const jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
      return jsxFragmentFactory && unescapeLeadingUnderscores(getFirstIdentifier(jsxFragmentFactory).escapedText);
    },
    getAccessibleSymbolChain,
    getTypePredicateOfSignature,
    resolveExternalModuleName: (moduleSpecifierIn) => {
      const moduleSpecifier = getParseTreeNode(moduleSpecifierIn, isExpression);
      return moduleSpecifier && resolveExternalModuleName(
        moduleSpecifier,
        moduleSpecifier,
        /*ignoreErrors*/
        true
      );
    },
    resolveExternalModuleSymbol,
    tryGetThisTypeAt: (nodeIn, includeGlobalThis, container) => {
      const node = getParseTreeNode(nodeIn);
      return node && tryGetThisTypeAt(node, includeGlobalThis, container);
    },
    getTypeArgumentConstraint: (nodeIn) => {
      const node = getParseTreeNode(nodeIn, isTypeNode);
      return node && getTypeArgumentConstraint(node);
    },
    getSuggestionDiagnostics: (fileIn, ct) => {
      const file = getParseTreeNode(fileIn, isSourceFile) || Debug.fail("Could not determine parsed source file.");
      if (skipTypeChecking(file, compilerOptions, host)) {
        return emptyArray;
      }
      let diagnostics2;
      try {
        cancellationToken = ct;
        checkSourceFileWithEagerDiagnostics(file);
        Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
        diagnostics2 = addRange(diagnostics2, suggestionDiagnostics.getDiagnostics(file.fileName));
        checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (containingNode, kind, diag2) => {
          if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) {
            (diagnostics2 || (diagnostics2 = [])).push({ ...diag2, category: 2 /* Suggestion */ });
          }
        });
        return diagnostics2 || emptyArray;
      } finally {
        cancellationToken = void 0;
      }
    },
    runWithCancellationToken: (token, callback) => {
      try {
        cancellationToken = token;
        return callback(checker);
      } finally {
        cancellationToken = void 0;
      }
    },
    getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
    isDeclarationVisible,
    isPropertyAccessible,
    getTypeOnlyAliasDeclaration,
    getMemberOverrideModifierStatus,
    isTypeParameterPossiblyReferenced,
    typeHasCallOrConstructSignatures,
    getSymbolFlags
  };
  function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) {
    const candidatesSet = /* @__PURE__ */ new Set();
    const candidates = [];
    runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(
      call,
      candidates,
      /*argumentCount*/
      void 0,
      0 /* Normal */
    ));
    for (const candidate of candidates) {
      candidatesSet.add(candidate);
    }
    candidates.length = 0;
    runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(
      call,
      candidates,
      /*argumentCount*/
      void 0,
      0 /* Normal */
    ));
    for (const candidate of candidates) {
      candidatesSet.add(candidate);
    }
    return arrayFrom(candidatesSet);
  }
  function runWithoutResolvedSignatureCaching(node, fn) {
    node = findAncestor(node, isCallLikeOrFunctionLikeExpression);
    if (node) {
      const cachedResolvedSignatures = [];
      const cachedTypes2 = [];
      while (node) {
        const nodeLinks2 = getNodeLinks(node);
        cachedResolvedSignatures.push([nodeLinks2, nodeLinks2.resolvedSignature]);
        nodeLinks2.resolvedSignature = void 0;
        if (isFunctionExpressionOrArrowFunction(node)) {
          const symbolLinks2 = getSymbolLinks(getSymbolOfDeclaration(node));
          const type = symbolLinks2.type;
          cachedTypes2.push([symbolLinks2, type]);
          symbolLinks2.type = void 0;
        }
        node = findAncestor(node.parent, isCallLikeOrFunctionLikeExpression);
      }
      const result = fn();
      for (const [nodeLinks2, resolvedSignature] of cachedResolvedSignatures) {
        nodeLinks2.resolvedSignature = resolvedSignature;
      }
      for (const [symbolLinks2, type] of cachedTypes2) {
        symbolLinks2.type = type;
      }
      return result;
    }
    return fn();
  }
  function runWithInferenceBlockedFromSourceNode(node, fn) {
    const containingCall = findAncestor(node, isCallLikeExpression);
    if (containingCall) {
      let toMarkSkip = node;
      do {
        getNodeLinks(toMarkSkip).skipDirectInference = true;
        toMarkSkip = toMarkSkip.parent;
      } while (toMarkSkip && toMarkSkip !== containingCall);
    }
    isInferencePartiallyBlocked = true;
    const result = runWithoutResolvedSignatureCaching(node, fn);
    isInferencePartiallyBlocked = false;
    if (containingCall) {
      let toMarkSkip = node;
      do {
        getNodeLinks(toMarkSkip).skipDirectInference = void 0;
        toMarkSkip = toMarkSkip.parent;
      } while (toMarkSkip && toMarkSkip !== containingCall);
    }
    return result;
  }
  function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
    const node = getParseTreeNode(nodeIn, isCallLikeExpression);
    apparentArgumentCount = argumentCount;
    const res = !node ? void 0 : getResolvedSignature(node, candidatesOutArray, checkMode);
    apparentArgumentCount = void 0;
    return res;
  }
  var tupleTypes = /* @__PURE__ */ new Map();
  var unionTypes = /* @__PURE__ */ new Map();
  var unionOfUnionTypes = /* @__PURE__ */ new Map();
  var intersectionTypes = /* @__PURE__ */ new Map();
  var stringLiteralTypes = /* @__PURE__ */ new Map();
  var numberLiteralTypes = /* @__PURE__ */ new Map();
  var bigIntLiteralTypes = /* @__PURE__ */ new Map();
  var enumLiteralTypes = /* @__PURE__ */ new Map();
  var indexedAccessTypes = /* @__PURE__ */ new Map();
  var templateLiteralTypes = /* @__PURE__ */ new Map();
  var stringMappingTypes = /* @__PURE__ */ new Map();
  var substitutionTypes = /* @__PURE__ */ new Map();
  var subtypeReductionCache = /* @__PURE__ */ new Map();
  var decoratorContextOverrideTypeCache = /* @__PURE__ */ new Map();
  var cachedTypes = /* @__PURE__ */ new Map();
  var evolvingArrayTypes = [];
  var undefinedProperties = /* @__PURE__ */ new Map();
  var markerTypes = /* @__PURE__ */ new Set();
  var unknownSymbol = createSymbol(4 /* Property */, "unknown");
  var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
  var unresolvedSymbols = /* @__PURE__ */ new Map();
  var errorTypes = /* @__PURE__ */ new Map();
  var seenIntrinsicNames = /* @__PURE__ */ new Set();
  var anyType = createIntrinsicType(1 /* Any */, "any");
  var autoType = createIntrinsicType(1 /* Any */, "any", 262144 /* NonInferrableType */, "auto");
  var wildcardType = createIntrinsicType(
    1 /* Any */,
    "any",
    /*objectFlags*/
    void 0,
    "wildcard"
  );
  var blockedStringType = createIntrinsicType(
    1 /* Any */,
    "any",
    /*objectFlags*/
    void 0,
    "blocked string"
  );
  var errorType = createIntrinsicType(1 /* Any */, "error");
  var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved");
  var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 65536 /* ContainsWideningType */, "non-inferrable");
  var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
  var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
  var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
  var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 65536 /* ContainsWideningType */, "widening");
  var missingType = createIntrinsicType(
    32768 /* Undefined */,
    "undefined",
    /*objectFlags*/
    void 0,
    "missing"
  );
  var undefinedOrMissingType = exactOptionalPropertyTypes ? missingType : undefinedType;
  var optionalType = createIntrinsicType(
    32768 /* Undefined */,
    "undefined",
    /*objectFlags*/
    void 0,
    "optional"
  );
  var nullType = createIntrinsicType(65536 /* Null */, "null");
  var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 65536 /* ContainsWideningType */, "widening");
  var stringType = createIntrinsicType(4 /* String */, "string");
  var numberType = createIntrinsicType(8 /* Number */, "number");
  var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
  var falseType = createIntrinsicType(
    512 /* BooleanLiteral */,
    "false",
    /*objectFlags*/
    void 0,
    "fresh"
  );
  var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
  var trueType = createIntrinsicType(
    512 /* BooleanLiteral */,
    "true",
    /*objectFlags*/
    void 0,
    "fresh"
  );
  var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
  trueType.regularType = regularTrueType;
  trueType.freshType = trueType;
  regularTrueType.regularType = regularTrueType;
  regularTrueType.freshType = trueType;
  falseType.regularType = regularFalseType;
  falseType.freshType = falseType;
  regularFalseType.regularType = regularFalseType;
  regularFalseType.freshType = falseType;
  var booleanType = getUnionType([regularFalseType, regularTrueType]);
  var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
  var voidType = createIntrinsicType(16384 /* Void */, "void");
  var neverType = createIntrinsicType(131072 /* Never */, "never");
  var silentNeverType = createIntrinsicType(131072 /* Never */, "never", 262144 /* NonInferrableType */, "silent");
  var implicitNeverType = createIntrinsicType(
    131072 /* Never */,
    "never",
    /*objectFlags*/
    void 0,
    "implicit"
  );
  var unreachableNeverType = createIntrinsicType(
    131072 /* Never */,
    "never",
    /*objectFlags*/
    void 0,
    "unreachable"
  );
  var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
  var stringOrNumberType = getUnionType([stringType, numberType]);
  var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
  var numberOrBigIntType = getUnionType([numberType, bigintType]);
  var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
  var numericStringType = getTemplateLiteralType(["", ""], [numberType]);
  var restrictiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)");
  var permissiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? wildcardType : t, () => "(permissive mapper)");
  var uniqueLiteralType = createIntrinsicType(
    131072 /* Never */,
    "never",
    /*objectFlags*/
    void 0,
    "unique literal"
  );
  var uniqueLiteralMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? uniqueLiteralType : t, () => "(unique literal mapper)");
  var outofbandVarianceMarkerHandler;
  var reportUnreliableMapper = makeFunctionTypeMapper((t) => {
    if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) {
      outofbandVarianceMarkerHandler(
        /*onlyUnreliable*/
        true
      );
    }
    return t;
  }, () => "(unmeasurable reporter)");
  var reportUnmeasurableMapper = makeFunctionTypeMapper((t) => {
    if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) {
      outofbandVarianceMarkerHandler(
        /*onlyUnreliable*/
        false
      );
    }
    return t;
  }, () => "(unreliable reporter)");
  var emptyObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var emptyJsxObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */;
  var emptyFreshJsxObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyFreshJsxObjectType.objectFlags |= 2048 /* JsxAttributes */ | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
  var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
  emptyTypeLiteralSymbol.members = createSymbolTable();
  var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray);
  var unknownEmptyObjectType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, unknownEmptyObjectType]) : unknownType;
  var emptyGenericType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  emptyGenericType.instantiations = /* @__PURE__ */ new Map();
  var anyFunctionType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  anyFunctionType.objectFlags |= 262144 /* NonInferrableType */;
  var noConstraintType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var circularConstraintType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var resolvingDefaultType = createAnonymousType(
    /*symbol*/
    void 0,
    emptySymbols,
    emptyArray,
    emptyArray,
    emptyArray
  );
  var markerSuperType = createTypeParameter();
  var markerSubType = createTypeParameter();
  markerSubType.constraint = markerSuperType;
  var markerOtherType = createTypeParameter();
  var markerSuperTypeForCheck = createTypeParameter();
  var markerSubTypeForCheck = createTypeParameter();
  markerSubTypeForCheck.constraint = markerSuperTypeForCheck;
  var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
  var anySignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    anyType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var unknownSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    errorType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var resolvingSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    anyType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var silentNeverSignature = createSignature(
    /*declaration*/
    void 0,
    /*typeParameters*/
    void 0,
    /*thisParameter*/
    void 0,
    emptyArray,
    silentNeverType,
    /*resolvedTypePredicate*/
    void 0,
    0,
    0 /* None */
  );
  var enumNumberIndexInfo = createIndexInfo(
    numberType,
    stringType,
    /*isReadonly*/
    true
  );
  var anyBaseTypeIndexInfo = createIndexInfo(
    stringType,
    anyType,
    /*isReadonly*/
    false
  );
  var iterationTypesCache = /* @__PURE__ */ new Map();
  var noIterationTypes = {
    get yieldType() {
      return Debug.fail("Not supported");
    },
    get returnType() {
      return Debug.fail("Not supported");
    },
    get nextType() {
      return Debug.fail("Not supported");
    }
  };
  var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
  var asyncIterationTypesResolver = {
    iterableCacheKey: "iterationTypesOfAsyncIterable",
    iteratorCacheKey: "iterationTypesOfAsyncIterator",
    iteratorSymbolName: "asyncIterator",
    getGlobalIteratorType: getGlobalAsyncIteratorType,
    getGlobalIterableType: getGlobalAsyncIterableType,
    getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
    getGlobalIteratorObjectType: getGlobalAsyncIteratorObjectType,
    getGlobalGeneratorType: getGlobalAsyncGeneratorType,
    getGlobalBuiltinIteratorTypes: getGlobalBuiltinAsyncIteratorTypes,
    resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member),
    mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method,
    mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
    mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property
  };
  var syncIterationTypesResolver = {
    iterableCacheKey: "iterationTypesOfIterable",
    iteratorCacheKey: "iterationTypesOfIterator",
    iteratorSymbolName: "iterator",
    getGlobalIteratorType,
    getGlobalIterableType,
    getGlobalIterableIteratorType,
    getGlobalIteratorObjectType,
    getGlobalGeneratorType,
    getGlobalBuiltinIteratorTypes,
    resolveIterationType: (type, _errorNode) => type,
    mustHaveANextMethodDiagnostic: Diagnostics.An_iterator_must_have_a_next_method,
    mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
    mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property
  };
  var amalgamatedDuplicates;
  var reverseMappedCache = /* @__PURE__ */ new Map();
  var reverseHomomorphicMappedCache = /* @__PURE__ */ new Map();
  var ambientModulesCache;
  var patternAmbientModules;
  var patternAmbientModuleAugmentations;
  var globalObjectType;
  var globalFunctionType;
  var globalCallableFunctionType;
  var globalNewableFunctionType;
  var globalArrayType;
  var globalReadonlyArrayType;
  var globalStringType;
  var globalNumberType;
  var globalBooleanType;
  var globalRegExpType;
  var globalThisType;
  var anyArrayType;
  var autoArrayType;
  var anyReadonlyArrayType;
  var deferredGlobalNonNullableTypeAlias;
  var deferredGlobalESSymbolConstructorSymbol;
  var deferredGlobalESSymbolConstructorTypeSymbol;
  var deferredGlobalESSymbolType;
  var deferredGlobalTypedPropertyDescriptorType;
  var deferredGlobalPromiseType;
  var deferredGlobalPromiseLikeType;
  var deferredGlobalPromiseConstructorSymbol;
  var deferredGlobalPromiseConstructorLikeType;
  var deferredGlobalIterableType;
  var deferredGlobalIteratorType;
  var deferredGlobalIterableIteratorType;
  var deferredGlobalIteratorObjectType;
  var deferredGlobalGeneratorType;
  var deferredGlobalIteratorYieldResultType;
  var deferredGlobalIteratorReturnResultType;
  var deferredGlobalAsyncIterableType;
  var deferredGlobalAsyncIteratorType;
  var deferredGlobalAsyncIterableIteratorType;
  var deferredGlobalBuiltinIteratorTypes;
  var deferredGlobalBuiltinAsyncIteratorTypes;
  var deferredGlobalAsyncIteratorObjectType;
  var deferredGlobalAsyncGeneratorType;
  var deferredGlobalTemplateStringsArrayType;
  var deferredGlobalImportMetaType;
  var deferredGlobalImportMetaExpressionType;
  var deferredGlobalImportCallOptionsType;
  var deferredGlobalImportAttributesType;
  var deferredGlobalDisposableType;
  var deferredGlobalAsyncDisposableType;
  var deferredGlobalExtractSymbol;
  var deferredGlobalOmitSymbol;
  var deferredGlobalAwaitedSymbol;
  var deferredGlobalBigIntType;
  var deferredGlobalNaNSymbol;
  var deferredGlobalRecordSymbol;
  var deferredGlobalClassDecoratorContextType;
  var deferredGlobalClassMethodDecoratorContextType;
  var deferredGlobalClassGetterDecoratorContextType;
  var deferredGlobalClassSetterDecoratorContextType;
  var deferredGlobalClassAccessorDecoratorContextType;
  var deferredGlobalClassAccessorDecoratorTargetType;
  var deferredGlobalClassAccessorDecoratorResultType;
  var deferredGlobalClassFieldDecoratorContextType;
  var allPotentiallyUnusedIdentifiers = /* @__PURE__ */ new Map();
  var flowLoopStart = 0;
  var flowLoopCount = 0;
  var sharedFlowCount = 0;
  var flowAnalysisDisabled = false;
  var flowInvocationCount = 0;
  var lastFlowNode;
  var lastFlowNodeReachable;
  var flowTypeCache;
  var contextualTypeNodes = [];
  var contextualTypes = [];
  var contextualIsCache = [];
  var contextualTypeCount = 0;
  var contextualBindingPatterns = [];
  var inferenceContextNodes = [];
  var inferenceContexts = [];
  var inferenceContextCount = 0;
  var emptyStringType = getStringLiteralType("");
  var zeroType = getNumberLiteralType(0);
  var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" });
  var resolutionTargets = [];
  var resolutionResults = [];
  var resolutionPropertyNames = [];
  var resolutionStart = 0;
  var inVarianceComputation = false;
  var suggestionCount = 0;
  var maximumSuggestionCount = 10;
  var mergedSymbols = [];
  var symbolLinks = [];
  var nodeLinks = [];
  var flowLoopCaches = [];
  var flowLoopNodes = [];
  var flowLoopKeys = [];
  var flowLoopTypes = [];
  var sharedFlowNodes = [];
  var sharedFlowTypes = [];
  var flowNodeReachable = [];
  var flowNodePostSuper = [];
  var potentialThisCollisions = [];
  var potentialNewTargetCollisions = [];
  var potentialWeakMapSetCollisions = [];
  var potentialReflectCollisions = [];
  var potentialUnusedRenamedBindingElementsInTypes = [];
  var awaitedTypeStack = [];
  var reverseMappedSourceStack = [];
  var reverseMappedTargetStack = [];
  var reverseExpandingFlags = 0 /* None */;
  var diagnostics = createDiagnosticCollection();
  var suggestionDiagnostics = createDiagnosticCollection();
  var typeofType = createTypeofType();
  var _jsxNamespace;
  var _jsxFactoryEntity;
  var subtypeRelation = /* @__PURE__ */ new Map();
  var strictSubtypeRelation = /* @__PURE__ */ new Map();
  var assignableRelation = /* @__PURE__ */ new Map();
  var comparableRelation = /* @__PURE__ */ new Map();
  var identityRelation = /* @__PURE__ */ new Map();
  var enumRelation = /* @__PURE__ */ new Map();
  var suggestedExtensions = [
    [".mts", ".mjs"],
    [".ts", ".js"],
    [".cts", ".cjs"],
    [".mjs", ".mjs"],
    [".js", ".js"],
    [".cjs", ".cjs"],
    [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"],
    [".jsx", ".jsx"],
    [".json", ".json"]
  ];
  initializeTypeChecker();
  return checker;
  function isDefinitelyReferenceToGlobalSymbolObject(node) {
    if (!isPropertyAccessExpression(node)) return false;
    if (!isIdentifier(node.name)) return false;
    if (!isPropertyAccessExpression(node.expression) && !isIdentifier(node.expression)) return false;
    if (isIdentifier(node.expression)) {
      return idText(node.expression) === "Symbol" && getResolvedSymbol(node.expression) === (getGlobalSymbol(
        "Symbol",
        111551 /* Value */ | 1048576 /* ExportValue */,
        /*diagnostic*/
        void 0
      ) || unknownSymbol);
    }
    if (!isIdentifier(node.expression.expression)) return false;
    return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol;
  }
  function getCachedType(key) {
    return key ? cachedTypes.get(key) : void 0;
  }
  function setCachedType(key, type) {
    if (key) cachedTypes.set(key, type);
    return type;
  }
  function getJsxNamespace(location) {
    if (location) {
      const file = getSourceFileOfNode(location);
      if (file) {
        if (isJsxOpeningFragment(location)) {
          if (file.localJsxFragmentNamespace) {
            return file.localJsxFragmentNamespace;
          }
          const jsxFragmentPragma = file.pragmas.get("jsxfrag");
          if (jsxFragmentPragma) {
            const chosenPragma = isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
            file.localJsxFragmentFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
            visitNode(file.localJsxFragmentFactory, markAsSynthetic, isEntityName);
            if (file.localJsxFragmentFactory) {
              return file.localJsxFragmentNamespace = getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
            }
          }
          const entity = getJsxFragmentFactoryEntity(location);
          if (entity) {
            file.localJsxFragmentFactory = entity;
            return file.localJsxFragmentNamespace = getFirstIdentifier(entity).escapedText;
          }
        } else {
          const localJsxNamespace = getLocalJsxNamespace(file);
          if (localJsxNamespace) {
            return file.localJsxNamespace = localJsxNamespace;
          }
        }
      }
    }
    if (!_jsxNamespace) {
      _jsxNamespace = "React";
      if (compilerOptions.jsxFactory) {
        _jsxFactoryEntity = parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
        visitNode(_jsxFactoryEntity, markAsSynthetic);
        if (_jsxFactoryEntity) {
          _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText;
        }
      } else if (compilerOptions.reactNamespace) {
        _jsxNamespace = escapeLeadingUnderscores(compilerOptions.reactNamespace);
      }
    }
    if (!_jsxFactoryEntity) {
      _jsxFactoryEntity = factory.createQualifiedName(factory.createIdentifier(unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
    }
    return _jsxNamespace;
  }
  function getLocalJsxNamespace(file) {
    if (file.localJsxNamespace) {
      return file.localJsxNamespace;
    }
    const jsxPragma = file.pragmas.get("jsx");
    if (jsxPragma) {
      const chosenPragma = isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
      file.localJsxFactory = parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
      visitNode(file.localJsxFactory, markAsSynthetic, isEntityName);
      if (file.localJsxFactory) {
        return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
      }
    }
  }
  function markAsSynthetic(node) {
    setTextRangePosEnd(node, -1, -1);
    return visitEachChild(
      node,
      markAsSynthetic,
      /*context*/
      void 0
    );
  }
  function getEmitResolver(sourceFile, cancellationToken2, skipDiagnostics) {
    if (!skipDiagnostics) getDiagnostics(sourceFile, cancellationToken2);
    return emitResolver;
  }
  function lookupOrIssueError(location, message, ...args) {
    const diagnostic = location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args);
    const existing = diagnostics.lookup(diagnostic);
    if (existing) {
      return existing;
    } else {
      diagnostics.add(diagnostic);
      return diagnostic;
    }
  }
  function errorSkippedOn(key, location, message, ...args) {
    const diagnostic = error(location, message, ...args);
    diagnostic.skippedOn = key;
    return diagnostic;
  }
  function createError(location, message, ...args) {
    return location ? createDiagnosticForNode(location, message, ...args) : createCompilerDiagnostic(message, ...args);
  }
  function error(location, message, ...args) {
    const diagnostic = createError(location, message, ...args);
    diagnostics.add(diagnostic);
    return diagnostic;
  }
  function addErrorOrSuggestion(isError, diagnostic) {
    if (isError) {
      diagnostics.add(diagnostic);
    } else {
      suggestionDiagnostics.add({ ...diagnostic, category: 2 /* Suggestion */ });
    }
  }
  function errorOrSuggestion(isError, location, message, ...args) {
    if (location.pos < 0 || location.end < 0) {
      if (!isError) {
        return;
      }
      const file = getSourceFileOfNode(location);
      addErrorOrSuggestion(isError, "message" in message ? createFileDiagnostic(file, 0, 0, message, ...args) : createDiagnosticForFileFromMessageChain(file, message));
      return;
    }
    addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, ...args) : createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(location), location, message));
  }
  function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, ...args) {
    const diagnostic = error(location, message, ...args);
    if (maybeMissingAwait) {
      const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await);
      addRelatedInfo(diagnostic, related);
    }
    return diagnostic;
  }
  function addDeprecatedSuggestionWorker(declarations, diagnostic) {
    const deprecatedTag = Array.isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations);
    if (deprecatedTag) {
      addRelatedInfo(
        diagnostic,
        createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here)
      );
    }
    suggestionDiagnostics.add(diagnostic);
    return diagnostic;
  }
  function isDeprecatedSymbol(symbol) {
    const parentSymbol = getParentOfSymbol(symbol);
    if (parentSymbol && length(symbol.declarations) > 1) {
      return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration) : every(symbol.declarations, isDeprecatedDeclaration);
    }
    return !!symbol.valueDeclaration && isDeprecatedDeclaration(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration);
  }
  function isDeprecatedDeclaration(declaration) {
    return !!(getCombinedNodeFlagsCached(declaration) & 536870912 /* Deprecated */);
  }
  function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
    const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity);
    return addDeprecatedSuggestionWorker(declarations, diagnostic);
  }
  function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
    const diagnostic = deprecatedEntity ? createDiagnosticForNode(location, Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) : createDiagnosticForNode(location, Diagnostics._0_is_deprecated, signatureString);
    return addDeprecatedSuggestionWorker(declaration, diagnostic);
  }
  function createSymbol(flags, name, checkFlags) {
    symbolCount++;
    const symbol = new Symbol13(flags | 33554432 /* Transient */, name);
    symbol.links = new SymbolLinks();
    symbol.links.checkFlags = checkFlags || 0 /* None */;
    return symbol;
  }
  function createParameter(name, type) {
    const symbol = createSymbol(1 /* FunctionScopedVariable */, name);
    symbol.links.type = type;
    return symbol;
  }
  function createProperty(name, type) {
    const symbol = createSymbol(4 /* Property */, name);
    symbol.links.type = type;
    return symbol;
  }
  function getExcludedSymbolFlags(flags) {
    let result = 0;
    if (flags & 2 /* BlockScopedVariable */) result |= 111551 /* BlockScopedVariableExcludes */;
    if (flags & 1 /* FunctionScopedVariable */) result |= 111550 /* FunctionScopedVariableExcludes */;
    if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */;
    if (flags & 8 /* EnumMember */) result |= 900095 /* EnumMemberExcludes */;
    if (flags & 16 /* Function */) result |= 110991 /* FunctionExcludes */;
    if (flags & 32 /* Class */) result |= 899503 /* ClassExcludes */;
    if (flags & 64 /* Interface */) result |= 788872 /* InterfaceExcludes */;
    if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */;
    if (flags & 128 /* ConstEnum */) result |= 899967 /* ConstEnumExcludes */;
    if (flags & 512 /* ValueModule */) result |= 110735 /* ValueModuleExcludes */;
    if (flags & 8192 /* Method */) result |= 103359 /* MethodExcludes */;
    if (flags & 32768 /* GetAccessor */) result |= 46015 /* GetAccessorExcludes */;
    if (flags & 65536 /* SetAccessor */) result |= 78783 /* SetAccessorExcludes */;
    if (flags & 262144 /* TypeParameter */) result |= 526824 /* TypeParameterExcludes */;
    if (flags & 524288 /* TypeAlias */) result |= 788968 /* TypeAliasExcludes */;
    if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */;
    return result;
  }
  function recordMergedSymbol(target, source) {
    if (!source.mergeId) {
      source.mergeId = nextMergeId;
      nextMergeId++;
    }
    mergedSymbols[source.mergeId] = target;
  }
  function cloneSymbol(symbol) {
    const result = createSymbol(symbol.flags, symbol.escapedName);
    result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
    result.parent = symbol.parent;
    if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
    if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
    if (symbol.members) result.members = new Map(symbol.members);
    if (symbol.exports) result.exports = new Map(symbol.exports);
    recordMergedSymbol(result, symbol);
    return result;
  }
  function mergeSymbol(target, source, unidirectional = false) {
    if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* Assignment */) {
      if (source === target) {
        return target;
      }
      if (!(target.flags & 33554432 /* Transient */)) {
        const resolvedTarget = resolveSymbol(target);
        if (resolvedTarget === unknownSymbol) {
          return source;
        }
        if (!(resolvedTarget.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | resolvedTarget.flags) & 67108864 /* Assignment */) {
          target = cloneSymbol(resolvedTarget);
        } else {
          reportMergeSymbolError(target, source);
          return source;
        }
      }
      if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
        target.constEnumOnlyModule = false;
      }
      target.flags |= source.flags;
      if (source.valueDeclaration) {
        setValueDeclaration(target, source.valueDeclaration);
      }
      addRange(target.declarations, source.declarations);
      if (source.members) {
        if (!target.members) target.members = createSymbolTable();
        mergeSymbolTable(target.members, source.members, unidirectional);
      }
      if (source.exports) {
        if (!target.exports) target.exports = createSymbolTable();
        mergeSymbolTable(target.exports, source.exports, unidirectional, target);
      }
      if (!unidirectional) {
        recordMergedSymbol(target, source);
      }
    } else if (target.flags & 1024 /* NamespaceModule */) {
      if (target !== globalThisSymbol) {
        error(
          source.declarations && getNameOfDeclaration(source.declarations[0]),
          Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity,
          symbolToString(target)
        );
      }
    } else {
      reportMergeSymbolError(target, source);
    }
    return target;
    function reportMergeSymbolError(target2, source2) {
      const isEitherEnum = !!(target2.flags & 384 /* Enum */ || source2.flags & 384 /* Enum */);
      const isEitherBlockScoped = !!(target2.flags & 2 /* BlockScopedVariable */ || source2.flags & 2 /* BlockScopedVariable */);
      const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
      const sourceSymbolFile = source2.declarations && getSourceFileOfNode(source2.declarations[0]);
      const targetSymbolFile = target2.declarations && getSourceFileOfNode(target2.declarations[0]);
      const isSourcePlainJs = isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs);
      const isTargetPlainJs = isPlainJsFile(targetSymbolFile, compilerOptions.checkJs);
      const symbolName2 = symbolToString(source2);
      if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
        const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
        const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
        const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => ({ firstFile, secondFile, conflictingSymbols: /* @__PURE__ */ new Map() }));
        const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName2, () => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] }));
        if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source2);
        if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target2);
      } else {
        if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source2, message, symbolName2, target2);
        if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target2, message, symbolName2, source2);
      }
    }
    function addDuplicateLocations(locs, symbol) {
      if (symbol.declarations) {
        for (const decl of symbol.declarations) {
          pushIfUnique(locs, decl);
        }
      }
    }
  }
  function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source) {
    forEach(target.declarations, (node) => {
      addDuplicateDeclarationError(node, message, symbolName2, source.declarations);
    });
  }
  function addDuplicateDeclarationError(node, message, symbolName2, relatedNodes) {
    const errorNode = (getExpandoInitializer(
      node,
      /*isPrototypeAssignment*/
      false
    ) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node;
    const err = lookupOrIssueError(errorNode, message, symbolName2);
    for (const relatedNode of relatedNodes || emptyArray) {
      const adjustedNode = (getExpandoInitializer(
        relatedNode,
        /*isPrototypeAssignment*/
        false
      ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode;
      if (adjustedNode === errorNode) continue;
      err.relatedInformation = err.relatedInformation || [];
      const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2);
      const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here);
      if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) continue;
      addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage);
    }
  }
  function combineSymbolTables(first2, second) {
    if (!(first2 == null ? void 0 : first2.size)) return second;
    if (!(second == null ? void 0 : second.size)) return first2;
    const combined = createSymbolTable();
    mergeSymbolTable(combined, first2);
    mergeSymbolTable(combined, second);
    return combined;
  }
  function mergeSymbolTable(target, source, unidirectional = false, mergedParent) {
    source.forEach((sourceSymbol, id) => {
      const targetSymbol = target.get(id);
      const merged = targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol);
      if (mergedParent && targetSymbol) {
        merged.parent = mergedParent;
      }
      target.set(id, merged);
    });
  }
  function mergeModuleAugmentation(moduleName) {
    var _a, _b, _c;
    const moduleAugmentation = moduleName.parent;
    if (((_a = moduleAugmentation.symbol.declarations) == null ? void 0 : _a[0]) !== moduleAugmentation) {
      Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
      return;
    }
    if (isGlobalScopeAugmentation(moduleAugmentation)) {
      mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
    } else {
      const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0;
      let mainModule = resolveExternalModuleNameWorker(
        moduleName,
        moduleName,
        moduleNotFoundError,
        /*ignoreErrors*/
        false,
        /*isForAugmentation*/
        true
      );
      if (!mainModule) {
        return;
      }
      mainModule = resolveExternalModuleSymbol(mainModule);
      if (mainModule.flags & 1920 /* Namespace */) {
        if (some(patternAmbientModules, (module2) => mainModule === module2.symbol)) {
          const merged = mergeSymbol(
            moduleAugmentation.symbol,
            mainModule,
            /*unidirectional*/
            true
          );
          if (!patternAmbientModuleAugmentations) {
            patternAmbientModuleAugmentations = /* @__PURE__ */ new Map();
          }
          patternAmbientModuleAugmentations.set(moduleName.text, merged);
        } else {
          if (((_b = mainModule.exports) == null ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) == null ? void 0 : _c.size)) {
            const resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule, "resolvedExports" /* resolvedExports */);
            for (const [key, value] of arrayFrom(moduleAugmentation.symbol.exports.entries())) {
              if (resolvedExports.has(key) && !mainModule.exports.has(key)) {
                mergeSymbol(resolvedExports.get(key), value);
              }
            }
          }
          mergeSymbol(mainModule, moduleAugmentation.symbol);
        }
      } else {
        error(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
      }
    }
  }
  function addUndefinedToGlobalsOrErrorOnRedeclaration() {
    const name = undefinedSymbol.escapedName;
    const targetSymbol = globals.get(name);
    if (targetSymbol) {
      forEach(targetSymbol.declarations, (declaration) => {
        if (!isTypeDeclaration(declaration)) {
          diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name)));
        }
      });
    } else {
      globals.set(name, undefinedSymbol);
    }
  }
  function getSymbolLinks(symbol) {
    if (symbol.flags & 33554432 /* Transient */) return symbol.links;
    const id = getSymbolId(symbol);
    return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks());
  }
  function getNodeLinks(node) {
    const nodeId = getNodeId(node);
    return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
  }
  function getSymbol(symbols, name, meaning) {
    if (meaning) {
      const symbol = getMergedSymbol(symbols.get(name));
      if (symbol) {
        if (symbol.flags & meaning) {
          return symbol;
        }
        if (symbol.flags & 2097152 /* Alias */) {
          const targetFlags = getSymbolFlags(symbol);
          if (targetFlags & meaning) {
            return symbol;
          }
        }
      }
    }
  }
  function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
    const constructorDeclaration = parameter.parent;
    const classDeclaration = parameter.parent.parent;
    const parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
    const propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
    if (parameterSymbol && propertySymbol) {
      return [parameterSymbol, propertySymbol];
    }
    return Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
  }
  function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
    const declarationFile = getSourceFileOfNode(declaration);
    const useFile = getSourceFileOfNode(usage);
    const declContainer = getEnclosingBlockScopeContainer(declaration);
    if (declarationFile !== useFile) {
      if (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator) || !compilerOptions.outFile || isInTypeQuery(usage) || declaration.flags & 33554432 /* Ambient */) {
        return true;
      }
      if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
        return true;
      }
      const sourceFiles = host.getSourceFiles();
      return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
    }
    if (!!(usage.flags & 16777216 /* JSDoc */) || isInTypeQuery(usage) || isInAmbientOrTypeNode(usage)) {
      return true;
    }
    if (declaration.pos <= usage.pos && !(isPropertyDeclaration(declaration) && isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
      if (declaration.kind === 208 /* BindingElement */) {
        const errorBindingElement = getAncestor(usage, 208 /* BindingElement */);
        if (errorBindingElement) {
          return findAncestor(errorBindingElement, isBindingElement) !== findAncestor(declaration, isBindingElement) || declaration.pos < errorBindingElement.pos;
        }
        return isBlockScopedNameDeclaredBeforeUse(getAncestor(declaration, 260 /* VariableDeclaration */), usage);
      } else if (declaration.kind === 260 /* VariableDeclaration */) {
        return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
      } else if (isClassLike(declaration)) {
        const container = findAncestor(usage, (n) => n === declaration ? "quit" : isComputedPropertyName(n) ? n.parent.parent === declaration : !legacyDecorators && isDecorator(n) && (n.parent === declaration || isMethodDeclaration(n.parent) && n.parent.parent === declaration || isGetOrSetAccessorDeclaration(n.parent) && n.parent.parent === declaration || isPropertyDeclaration(n.parent) && n.parent.parent === declaration || isParameter(n.parent) && n.parent.parent.parent === declaration));
        if (!container) {
          return true;
        }
        if (!legacyDecorators && isDecorator(container)) {
          return !!findAncestor(usage, (n) => n === container ? "quit" : isFunctionLike(n) && !getImmediatelyInvokedFunctionExpression(n));
        }
        return false;
      } else if (isPropertyDeclaration(declaration)) {
        return !isPropertyImmediatelyReferencedWithinDeclaration(
          declaration,
          usage,
          /*stopAtAnyPropertyDeclaration*/
          false
        );
      } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) {
        return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration));
      }
      return true;
    }
    if (usage.parent.kind === 281 /* ExportSpecifier */ || usage.parent.kind === 277 /* ExportAssignment */ && usage.parent.isExportEquals) {
      return true;
    }
    if (usage.kind === 277 /* ExportAssignment */ && usage.isExportEquals) {
      return true;
    }
    if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
      if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) {
        return !isPropertyImmediatelyReferencedWithinDeclaration(
          declaration,
          usage,
          /*stopAtAnyPropertyDeclaration*/
          true
        );
      } else {
        return true;
      }
    }
    return false;
    function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration2, usage2) {
      switch (declaration2.parent.parent.kind) {
        case 243 /* VariableStatement */:
        case 248 /* ForStatement */:
        case 250 /* ForOfStatement */:
          if (isSameScopeDescendentOf(usage2, declaration2, declContainer)) {
            return true;
          }
          break;
      }
      const grandparent = declaration2.parent.parent;
      return isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage2, grandparent.expression, declContainer);
    }
    function isUsedInFunctionOrInstanceProperty(usage2, declaration2) {
      return !!findAncestor(usage2, (current) => {
        if (current === declContainer) {
          return "quit";
        }
        if (isFunctionLike(current)) {
          return true;
        }
        if (isClassStaticBlockDeclaration(current)) {
          return declaration2.pos < usage2.pos;
        }
        const propertyDeclaration = tryCast(current.parent, isPropertyDeclaration);
        if (propertyDeclaration) {
          const initializerOfProperty = propertyDeclaration.initializer === current;
          if (initializerOfProperty) {
            if (isStatic(current.parent)) {
              if (declaration2.kind === 174 /* MethodDeclaration */) {
                return true;
              }
              if (isPropertyDeclaration(declaration2) && getContainingClass(usage2) === getContainingClass(declaration2)) {
                const propName = declaration2.name;
                if (isIdentifier(propName) || isPrivateIdentifier(propName)) {
                  const type = getTypeOfSymbol(getSymbolOfDeclaration(declaration2));
                  const staticBlocks = filter(declaration2.parent.members, isClassStaticBlockDeclaration);
                  if (isPropertyInitializedInStaticBlocks(propName, type, staticBlocks, declaration2.parent.pos, current.pos)) {
                    return true;
                  }
                }
              }
            } else {
              const isDeclarationInstanceProperty = declaration2.kind === 172 /* PropertyDeclaration */ && !isStatic(declaration2);
              if (!isDeclarationInstanceProperty || getContainingClass(usage2) !== getContainingClass(declaration2)) {
                return true;
              }
            }
          }
        }
        return false;
      });
    }
    function isPropertyImmediatelyReferencedWithinDeclaration(declaration2, usage2, stopAtAnyPropertyDeclaration) {
      if (usage2.end > declaration2.end) {
        return false;
      }
      const ancestorChangingReferenceScope = findAncestor(usage2, (node) => {
        if (node === declaration2) {
          return "quit";
        }
        switch (node.kind) {
          case 219 /* ArrowFunction */:
            return true;
          case 172 /* PropertyDeclaration */:
            return stopAtAnyPropertyDeclaration && (isPropertyDeclaration(declaration2) && node.parent === declaration2.parent || isParameterPropertyDeclaration(declaration2, declaration2.parent) && node.parent === declaration2.parent.parent) ? "quit" : true;
          case 241 /* Block */:
            switch (node.parent.kind) {
              case 177 /* GetAccessor */:
              case 174 /* MethodDeclaration */:
              case 178 /* SetAccessor */:
                return true;
              default:
                return false;
            }
          default:
            return false;
        }
      });
      return ancestorChangingReferenceScope === void 0;
    }
  }
  function getRequiresScopeChangeCache(node) {
    return getNodeLinks(node).declarationRequiresScopeChange;
  }
  function setRequiresScopeChangeCache(node, value) {
    getNodeLinks(node).declarationRequiresScopeChange = value;
  }
  function checkAndReportErrorForInvalidInitializer(errorLocation, name, propertyWithInvalidInitializer, result) {
    if (!emitStandardClassFields) {
      if (errorLocation && !result && checkAndReportErrorForMissingPrefix(errorLocation, name, name)) {
        return true;
      }
      error(
        errorLocation,
        errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor,
        declarationNameToString(propertyWithInvalidInitializer.name),
        diagnosticName(name)
      );
      return true;
    }
    return false;
  }
  function onFailedToResolveSymbol(errorLocation, nameArg, meaning, nameNotFoundMessage) {
    const name = isString(nameArg) ? nameArg : nameArg.escapedText;
    addLazyDiagnostic(() => {
      if (!errorLocation || errorLocation.parent.kind !== 324 /* JSDocLink */ && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
        let suggestion;
        let suggestedLib;
        if (nameArg) {
          suggestedLib = getSuggestedLibForNonExistentName(nameArg);
          if (suggestedLib) {
            error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), suggestedLib);
          }
        }
        if (!suggestedLib && suggestionCount < maximumSuggestionCount) {
          suggestion = getSuggestedSymbolForNonexistentSymbol(errorLocation, name, meaning);
          const isGlobalScopeAugmentationDeclaration = (suggestion == null ? void 0 : suggestion.valueDeclaration) && isAmbientModule(suggestion.valueDeclaration) && isGlobalScopeAugmentation(suggestion.valueDeclaration);
          if (isGlobalScopeAugmentationDeclaration) {
            suggestion = void 0;
          }
          if (suggestion) {
            const suggestionName = symbolToString(suggestion);
            const isUncheckedJS = isUncheckedJSSuggestion(
              errorLocation,
              suggestion,
              /*excludeClasses*/
              false
            );
            const message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 : Diagnostics.Cannot_find_name_0_Did_you_mean_1;
            const diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName);
            diagnostic.canonicalHead = getCanonicalDiagnostic(nameNotFoundMessage, diagnosticName(nameArg));
            addErrorOrSuggestion(!isUncheckedJS, diagnostic);
            if (suggestion.valueDeclaration) {
              addRelatedInfo(
                diagnostic,
                createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)
              );
            }
          }
        }
        if (!suggestion && !suggestedLib && nameArg) {
          error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
        }
        suggestionCount++;
      }
    });
  }
  function onSuccessfullyResolvedSymbol(errorLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext) {
    addLazyDiagnostic(() => {
      var _a;
      const name = result.escapedName;
      const isInExternalModule = lastLocation && isSourceFile(lastLocation) && isExternalOrCommonJsModule(lastLocation);
      if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || (meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */)) {
        const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
        if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
          checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
        }
      }
      if (isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(errorLocation.flags & 16777216 /* JSDoc */)) {
        const merged = getMergedSymbol(result);
        if (length(merged.declarations) && every(merged.declarations, (d) => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) {
          errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name));
        }
      }
      if (associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
        const candidate = getMergedSymbol(getLateBoundSymbol(result));
        const root = getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
        if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) {
          error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
        } else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && getSymbol(root.parent.locals, candidate.escapedName, meaning) === candidate) {
          error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation));
        }
      }
      if (errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */ && !(result.flags & 111551 /* Value */) && !isValidTypeOnlyAliasUseSite(errorLocation)) {
        const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* Value */);
        if (typeOnlyDeclaration) {
          const message = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
          const unescapedName = unescapeLeadingUnderscores(name);
          addTypeOnlyDeclarationRelatedInfo(
            error(errorLocation, message, unescapedName),
            typeOnlyDeclaration,
            unescapedName
          );
        }
      }
      if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */) {
        const isGlobal = getSymbol(globals, name, meaning) === result;
        const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol(lastLocation.locals, name, ~111551 /* Value */);
        if (nonValueSymbol) {
          const importDecl = (_a = nonValueSymbol.declarations) == null ? void 0 : _a.find((d) => d.kind === 276 /* ImportSpecifier */ || d.kind === 273 /* ImportClause */ || d.kind === 274 /* NamespaceImport */ || d.kind === 271 /* ImportEqualsDeclaration */);
          if (importDecl && !isTypeOnlyImportDeclaration(importDecl)) {
            error(importDecl, Diagnostics.Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled, unescapeLeadingUnderscores(name));
          }
        }
      }
    });
  }
  function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) {
    if (!typeOnlyDeclaration) return diagnostic;
    return addRelatedInfo(
      diagnostic,
      createDiagnosticForNode(
        typeOnlyDeclaration,
        typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here,
        unescapedName
      )
    );
  }
  function diagnosticName(nameArg) {
    return isString(nameArg) ? unescapeLeadingUnderscores(nameArg) : declarationNameToString(nameArg);
  }
  function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
    if (!isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
      return false;
    }
    const container = getThisContainer(
      errorLocation,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    let location = container;
    while (location) {
      if (isClassLike(location.parent)) {
        const classSymbol = getSymbolOfDeclaration(location.parent);
        if (!classSymbol) {
          break;
        }
        const constructorType = getTypeOfSymbol(classSymbol);
        if (getPropertyOfType(constructorType, name)) {
          error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
          return true;
        }
        if (location === container && !isStatic(location)) {
          const instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType;
          if (getPropertyOfType(instanceType, name)) {
            error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
            return true;
          }
        }
      }
      location = location.parent;
    }
    return false;
  }
  function checkAndReportErrorForExtendingInterface(errorLocation) {
    const expression = getEntityNameForExtendingInterface(errorLocation);
    if (expression && resolveEntityName(
      expression,
      64 /* Interface */,
      /*ignoreErrors*/
      true
    )) {
      error(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression));
      return true;
    }
    return false;
  }
  function getEntityNameForExtendingInterface(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
      case 211 /* PropertyAccessExpression */:
        return node.parent ? getEntityNameForExtendingInterface(node.parent) : void 0;
      case 233 /* ExpressionWithTypeArguments */:
        if (isEntityNameExpression(node.expression)) {
          return node.expression;
        }
      // falls through
      default:
        return void 0;
    }
  }
  function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
    const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
    if (meaning === namespaceMeaning) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        788968 /* Type */ & ~namespaceMeaning,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      const parent = errorLocation.parent;
      if (symbol) {
        if (isQualifiedName(parent)) {
          Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
          const propName = parent.right.escapedText;
          const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
          if (propType) {
            error(
              parent,
              Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,
              unescapeLeadingUnderscores(name),
              unescapeLeadingUnderscores(propName)
            );
            return true;
          }
        }
        error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
    if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        ~788968 /* Type */ & 111551 /* Value */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
        error(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function isPrimitiveTypeName(name) {
    return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
  }
  function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
    if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 281 /* ExportSpecifier */) {
      error(errorLocation, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
      return true;
    }
    return false;
  }
  function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
    if (meaning & 111551 /* Value */) {
      if (isPrimitiveTypeName(name)) {
        const grandparent = errorLocation.parent.parent;
        if (grandparent && grandparent.parent && isHeritageClause(grandparent)) {
          const heritageKind = grandparent.token;
          const containerKind = grandparent.parent.kind;
          if (containerKind === 264 /* InterfaceDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) {
            error(errorLocation, Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types, unescapeLeadingUnderscores(name));
          } else if (containerKind === 263 /* ClassDeclaration */ && heritageKind === 96 /* ExtendsKeyword */) {
            error(errorLocation, Diagnostics.A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values, unescapeLeadingUnderscores(name));
          } else if (containerKind === 263 /* ClassDeclaration */ && heritageKind === 119 /* ImplementsKeyword */) {
            error(errorLocation, Diagnostics.A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types, unescapeLeadingUnderscores(name));
          }
        } else {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name));
        }
        return true;
      }
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        788968 /* Type */ & ~111551 /* Value */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      const allFlags = symbol && getSymbolFlags(symbol);
      if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) {
        const rawName = unescapeLeadingUnderscores(name);
        if (isES2015OrLaterConstructorName(name)) {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName);
        } else if (maybeMappedType(errorLocation, symbol)) {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K");
        } else {
          error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
        }
        return true;
      }
    }
    return false;
  }
  function maybeMappedType(node, symbol) {
    const container = findAncestor(node.parent, (n) => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit");
    if (container && container.members.length === 1) {
      const type = getDeclaredTypeOfSymbol(symbol);
      return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(
        type,
        384 /* StringOrNumberLiteral */,
        /*strict*/
        true
      );
    }
    return false;
  }
  function isES2015OrLaterConstructorName(n) {
    switch (n) {
      case "Promise":
      case "Symbol":
      case "Map":
      case "WeakMap":
      case "Set":
      case "WeakSet":
        return true;
    }
    return false;
  }
  function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) {
    if (meaning & (111551 /* Value */ & ~788968 /* Type */)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        1024 /* NamespaceModule */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol) {
        error(
          errorLocation,
          Diagnostics.Cannot_use_namespace_0_as_a_value,
          unescapeLeadingUnderscores(name)
        );
        return true;
      }
    } else if (meaning & (788968 /* Type */ & ~111551 /* Value */)) {
      const symbol = resolveSymbol(resolveName(
        errorLocation,
        name,
        1536 /* Module */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      ));
      if (symbol) {
        error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name));
        return true;
      }
    }
    return false;
  }
  function checkResolvedBlockScopedVariable(result, errorLocation) {
    var _a;
    Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
    if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
      return;
    }
    const declaration = (_a = result.declarations) == null ? void 0 : _a.find(
      (d) => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */
    );
    if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
    if (!(declaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
      let diagnosticMessage;
      const declarationName = declarationNameToString(getNameOfDeclaration(declaration));
      if (result.flags & 2 /* BlockScopedVariable */) {
        diagnosticMessage = error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
      } else if (result.flags & 32 /* Class */) {
        diagnosticMessage = error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName);
      } else if (result.flags & 256 /* RegularEnum */) {
        diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName);
      } else {
        Debug.assert(!!(result.flags & 128 /* ConstEnum */));
        if (getIsolatedModules(compilerOptions)) {
          diagnosticMessage = error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationName);
        }
      }
      if (diagnosticMessage) {
        addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName));
      }
    }
  }
  function isSameScopeDescendentOf(initial, parent, stopAt) {
    return !!parent && !!findAncestor(initial, (n) => n === parent || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & 3 /* AsyncGenerator */) ? "quit" : false));
  }
  function getAnyImportSyntax(node) {
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
        return node;
      case 273 /* ImportClause */:
        return node.parent;
      case 274 /* NamespaceImport */:
        return node.parent.parent;
      case 276 /* ImportSpecifier */:
        return node.parent.parent.parent;
      default:
        return void 0;
    }
  }
  function getDeclarationOfAliasSymbol(symbol) {
    return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration);
  }
  function isAliasSymbolDeclaration(node) {
    return node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) || node.kind === 304 /* ShorthandPropertyAssignment */ || node.kind === 303 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) || node.kind === 260 /* VariableDeclaration */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === 208 /* BindingElement */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent);
  }
  function isAliasableOrJsExpression(e) {
    return isAliasableExpression(e) || isFunctionExpression(e) && isJSConstructor(e);
  }
  function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
    const commonJSPropertyAccess = getCommonJSPropertyAccess(node);
    if (commonJSPropertyAccess) {
      const name = getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
      return isIdentifier(commonJSPropertyAccess.name) ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : void 0;
    }
    if (isVariableDeclaration(node) || node.moduleReference.kind === 283 /* ExternalModuleReference */) {
      const immediate = resolveExternalModuleName(
        node,
        getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node)
      );
      const resolved2 = resolveExternalModuleSymbol(immediate);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        immediate,
        resolved2,
        /*overwriteEmpty*/
        false
      );
      return resolved2;
    }
    const resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
    checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
    return resolved;
  }
  function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
    if (markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    ) && !node.isTypeOnly) {
      const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfDeclaration(node));
      const isExport = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */;
      const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
      const relatedMessage = isExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here;
      const name = typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? "*" : moduleExportNameTextUnescaped(typeOnlyDeclaration.name);
      addRelatedInfo(error(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
    }
  }
  function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
    const exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
    const exportSymbol = exportValue ? getPropertyOfType(
      getTypeOfSymbol(exportValue),
      name,
      /*skipObjectFunctionPropertyAugment*/
      true
    ) : moduleSymbol.exports.get(name);
    const resolved = resolveSymbol(exportSymbol, dontResolveAlias);
    markSymbolOfAliasDeclarationIfTypeOnly(
      sourceNode,
      exportSymbol,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function isSyntacticDefault(node) {
    return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) || isNamespaceExport(node);
  }
  function getEmitSyntaxForModuleSpecifierExpression(usage) {
    return isStringLiteralLike(usage) ? host.getEmitSyntaxForUsageLocation(getSourceFileOfNode(usage), usage) : void 0;
  }
  function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) {
    return usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */;
  }
  function isOnlyImportableAsDefault(usage, resolvedModule) {
    if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) {
      const usageMode = getEmitSyntaxForModuleSpecifierExpression(usage);
      if (usageMode === 99 /* ESNext */) {
        resolvedModule ?? (resolvedModule = resolveExternalModuleName(
          usage,
          usage,
          /*ignoreErrors*/
          true
        ));
        const targetFile = resolvedModule && getSourceFileOfModule(resolvedModule);
        return targetFile && (isJsonSourceFile(targetFile) || getDeclarationFileExtension(targetFile.fileName) === ".d.json.ts");
      }
    }
    return false;
  }
  function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) {
    const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage);
    if (file && usageMode !== void 0) {
      const targetMode = host.getImpliedNodeFormatForEmit(file);
      if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */ && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) {
        return true;
      }
      if (usageMode === 99 /* ESNext */ && targetMode === 99 /* ESNext */) {
        return false;
      }
    }
    if (!allowSyntheticDefaultImports) {
      return false;
    }
    if (!file || file.isDeclarationFile) {
      const defaultExportSymbol = resolveExportByName(
        moduleSymbol,
        "default" /* Default */,
        /*sourceNode*/
        void 0,
        /*dontResolveAlias*/
        true
      );
      if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) {
        return false;
      }
      if (resolveExportByName(
        moduleSymbol,
        escapeLeadingUnderscores("__esModule"),
        /*sourceNode*/
        void 0,
        dontResolveAlias
      )) {
        return false;
      }
      return true;
    }
    if (!isSourceFileJS(file)) {
      return hasExportAssignmentSymbol(moduleSymbol);
    }
    return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(
      moduleSymbol,
      escapeLeadingUnderscores("__esModule"),
      /*sourceNode*/
      void 0,
      dontResolveAlias
    );
  }
  function getTargetOfImportClause(node, dontResolveAlias) {
    const moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
    if (moduleSymbol) {
      return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias);
    }
  }
  function getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias) {
    var _a;
    let exportDefaultSymbol;
    if (isShorthandAmbientModuleSymbol(moduleSymbol)) {
      exportDefaultSymbol = moduleSymbol;
    } else {
      exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
    }
    const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
    const specifier = getModuleSpecifierForImportOrExport(node);
    if (!specifier) {
      return exportDefaultSymbol;
    }
    const hasDefaultOnly = isOnlyImportableAsDefault(specifier, moduleSymbol);
    const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier);
    if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) {
      if (hasExportAssignmentSymbol(moduleSymbol) && !allowSyntheticDefaultImports) {
        const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop";
        const exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
        const exportAssignment = exportEqualsSymbol.valueDeclaration;
        const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
        if (exportAssignment) {
          addRelatedInfo(
            err,
            createDiagnosticForNode(
              exportAssignment,
              Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag,
              compilerOptionName
            )
          );
        }
      } else if (isImportClause(node)) {
        reportNonDefaultExport(moduleSymbol, node);
      } else {
        errorNoModuleMemberSymbol(moduleSymbol, moduleSymbol, node, isImportOrExportSpecifier(node) && node.propertyName || node.name);
      }
    } else if (hasSyntheticDefault || hasDefaultOnly) {
      const resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        moduleSymbol,
        resolved,
        /*overwriteEmpty*/
        false
      );
      return resolved;
    }
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      exportDefaultSymbol,
      /*finalTarget*/
      void 0,
      /*overwriteEmpty*/
      false
    );
    return exportDefaultSymbol;
  }
  function getModuleSpecifierForImportOrExport(node) {
    switch (node.kind) {
      case 273 /* ImportClause */:
        return node.parent.moduleSpecifier;
      case 271 /* ImportEqualsDeclaration */:
        return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : void 0;
      case 274 /* NamespaceImport */:
        return node.parent.parent.moduleSpecifier;
      case 276 /* ImportSpecifier */:
        return node.parent.parent.parent.moduleSpecifier;
      case 281 /* ExportSpecifier */:
        return node.parent.parent.moduleSpecifier;
      default:
        return Debug.assertNever(node);
    }
  }
  function reportNonDefaultExport(moduleSymbol, node) {
    var _a, _b, _c;
    if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has(node.symbol.escapedName)) {
      error(
        node.name,
        Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead,
        symbolToString(moduleSymbol),
        symbolToString(node.symbol)
      );
    } else {
      const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
      const exportStar = (_b = moduleSymbol.exports) == null ? void 0 : _b.get("__export" /* ExportStar */);
      if (exportStar) {
        const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find(
          (decl) => {
            var _a2, _b2;
            return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */)));
          }
        );
        if (defaultExport) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default));
        }
      }
    }
  }
  function getTargetOfNamespaceImport(node, dontResolveAlias) {
    const moduleSpecifier = node.parent.parent.moduleSpecifier;
    const immediate = resolveExternalModuleName(node, moduleSpecifier);
    const resolved = resolveESModuleSymbol(
      immediate,
      moduleSpecifier,
      dontResolveAlias,
      /*suppressInteropError*/
      false
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      immediate,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfNamespaceExport(node, dontResolveAlias) {
    const moduleSpecifier = node.parent.moduleSpecifier;
    const immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
    const resolved = moduleSpecifier && resolveESModuleSymbol(
      immediate,
      moduleSpecifier,
      dontResolveAlias,
      /*suppressInteropError*/
      false
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      immediate,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
    if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
      return unknownSymbol;
    }
    if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
      return valueSymbol;
    }
    const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
    Debug.assert(valueSymbol.declarations || typeSymbol.declarations);
    result.declarations = deduplicate(concatenate(valueSymbol.declarations, typeSymbol.declarations), equateValues);
    result.parent = valueSymbol.parent || typeSymbol.parent;
    if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration;
    if (typeSymbol.members) result.members = new Map(typeSymbol.members);
    if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports);
    return result;
  }
  function getExportOfModule(symbol, nameText, specifier, dontResolveAlias) {
    var _a;
    if (symbol.flags & 1536 /* Module */) {
      const exportSymbol = getExportsOfSymbol(symbol).get(nameText);
      const resolved = resolveSymbol(exportSymbol, dontResolveAlias);
      const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(nameText);
      markSymbolOfAliasDeclarationIfTypeOnly(
        specifier,
        exportSymbol,
        resolved,
        /*overwriteEmpty*/
        false,
        exportStarDeclaration,
        nameText
      );
      return resolved;
    }
  }
  function getPropertyOfVariable(symbol, name) {
    if (symbol.flags & 3 /* Variable */) {
      const typeAnnotation = symbol.valueDeclaration.type;
      if (typeAnnotation) {
        return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
      }
    }
  }
  function getExternalModuleMember(node, specifier, dontResolveAlias = false) {
    var _a;
    const moduleSpecifier = getExternalModuleRequireArgument(node) || node.moduleSpecifier;
    const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier);
    const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
    if (!isIdentifier(name) && name.kind !== 11 /* StringLiteral */) {
      return void 0;
    }
    const nameText = moduleExportNameTextEscaped(name);
    const suppressInteropError = nameText === "default" /* Default */ && allowSyntheticDefaultImports;
    const targetSymbol = resolveESModuleSymbol(
      moduleSymbol,
      moduleSpecifier,
      /*dontResolveAlias*/
      false,
      suppressInteropError
    );
    if (targetSymbol) {
      if (nameText || name.kind === 11 /* StringLiteral */) {
        if (isShorthandAmbientModuleSymbol(moduleSymbol)) {
          return moduleSymbol;
        }
        let symbolFromVariable;
        if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
          symbolFromVariable = getPropertyOfType(
            getTypeOfSymbol(targetSymbol),
            nameText,
            /*skipObjectFunctionPropertyAugment*/
            true
          );
        } else {
          symbolFromVariable = getPropertyOfVariable(targetSymbol, nameText);
        }
        symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
        let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias);
        if (symbolFromModule === void 0 && nameText === "default" /* Default */) {
          const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
          if (isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) {
            symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
          }
        }
        const symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable;
        if (isImportOrExportSpecifier(specifier) && isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) && nameText !== "default" /* Default */) {
          error(name, Diagnostics.Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0, ModuleKind[moduleKind]);
        } else if (!symbol) {
          errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name);
        }
        return symbol;
      }
    }
  }
  function errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name) {
    var _a;
    const moduleName = getFullyQualifiedName(moduleSymbol, node);
    const declarationName = declarationNameToString(name);
    const suggestion = isIdentifier(name) ? getSuggestedSymbolForNonexistentModule(name, targetSymbol) : void 0;
    if (suggestion !== void 0) {
      const suggestionName = symbolToString(suggestion);
      const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
      if (suggestion.valueDeclaration) {
        addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName));
      }
    } else {
      if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has("default" /* Default */)) {
        error(
          name,
          Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead,
          moduleName,
          declarationName
        );
      } else {
        reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
      }
    }
  }
  function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
    var _a, _b;
    const localSymbol = (_b = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(moduleExportNameTextEscaped(name));
    const exports2 = moduleSymbol.exports;
    if (localSymbol) {
      const exportedEqualsSymbol = exports2 == null ? void 0 : exports2.get("export=" /* ExportEquals */);
      if (exportedEqualsSymbol) {
        getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
      } else {
        const exportedSymbol = exports2 ? find(symbolsToArray(exports2), (symbol) => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0;
        const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
        if (localSymbol.declarations) {
          addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName)));
        }
      }
    } else {
      error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
    }
  }
  function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
    if (moduleKind >= 5 /* ES2015 */) {
      const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
      error(name, message, declarationName);
    } else {
      if (isInJSFile(node)) {
        const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
        error(name, message, declarationName);
      } else {
        const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
        error(name, message, declarationName, declarationName, moduleName);
      }
    }
  }
  function getTargetOfImportSpecifier(node, dontResolveAlias) {
    if (isImportSpecifier(node) && moduleExportNameIsDefault(node.propertyName || node.name)) {
      const specifier = getModuleSpecifierForImportOrExport(node);
      const moduleSymbol = specifier && resolveExternalModuleName(node, specifier);
      if (moduleSymbol) {
        return getTargetofModuleDefault(moduleSymbol, node, dontResolveAlias);
      }
    }
    const root = isBindingElement(node) ? getRootDeclaration(node) : node.parent.parent.parent;
    const commonJSPropertyAccess = getCommonJSPropertyAccess(root);
    const resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
    const name = node.propertyName || node.name;
    if (commonJSPropertyAccess && resolved && isIdentifier(name)) {
      return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias);
    }
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getCommonJSPropertyAccess(node) {
    if (isVariableDeclaration(node) && node.initializer && isPropertyAccessExpression(node.initializer)) {
      return node.initializer;
    }
  }
  function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
    if (canHaveSymbol(node.parent)) {
      const resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
      markSymbolOfAliasDeclarationIfTypeOnly(
        node,
        /*immediateTarget*/
        void 0,
        resolved,
        /*overwriteEmpty*/
        false
      );
      return resolved;
    }
  }
  function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
    const name = node.propertyName || node.name;
    if (moduleExportNameIsDefault(name)) {
      const specifier = getModuleSpecifierForImportOrExport(node);
      const moduleSymbol = specifier && resolveExternalModuleName(node, specifier);
      if (moduleSymbol) {
        return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias);
      }
    }
    const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : name.kind === 11 /* StringLiteral */ ? void 0 : (
      // Skip for invalid syntax like this: export { "x" }
      resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      )
    );
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfExportAssignment(node, dontResolveAlias) {
    const expression = isExportAssignment(node) ? node.expression : node.right;
    const resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
    markSymbolOfAliasDeclarationIfTypeOnly(
      node,
      /*immediateTarget*/
      void 0,
      resolved,
      /*overwriteEmpty*/
      false
    );
    return resolved;
  }
  function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
    if (isClassExpression(expression)) {
      return checkExpressionCached(expression).symbol;
    }
    if (!isEntityName(expression) && !isEntityNameExpression(expression)) {
      return void 0;
    }
    const aliasLike = resolveEntityName(
      expression,
      111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
      /*ignoreErrors*/
      true,
      dontResolveAlias
    );
    if (aliasLike) {
      return aliasLike;
    }
    checkExpressionCached(expression);
    return getNodeLinks(expression).resolvedSymbol;
  }
  function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
    if (!(isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */)) {
      return void 0;
    }
    return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
  }
  function getTargetOfAliasDeclaration(node, dontRecursivelyResolve = false) {
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
      case 260 /* VariableDeclaration */:
        return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
      case 273 /* ImportClause */:
        return getTargetOfImportClause(node, dontRecursivelyResolve);
      case 274 /* NamespaceImport */:
        return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
      case 280 /* NamespaceExport */:
        return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
      case 276 /* ImportSpecifier */:
      case 208 /* BindingElement */:
        return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
      case 281 /* ExportSpecifier */:
        return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
      case 277 /* ExportAssignment */:
      case 226 /* BinaryExpression */:
        return getTargetOfExportAssignment(node, dontRecursivelyResolve);
      case 270 /* NamespaceExportDeclaration */:
        return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
      case 304 /* ShorthandPropertyAssignment */:
        return resolveEntityName(
          node.name,
          111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
          /*ignoreErrors*/
          true,
          dontRecursivelyResolve
        );
      case 303 /* PropertyAssignment */:
        return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve);
      case 212 /* ElementAccessExpression */:
      case 211 /* PropertyAccessExpression */:
        return getTargetOfAccessExpression(node, dontRecursivelyResolve);
      default:
        return Debug.fail();
    }
  }
  function isNonLocalAlias(symbol, excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */) {
    if (!symbol) return false;
    return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
  }
  function resolveSymbol(symbol, dontResolveAlias) {
    return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
  }
  function resolveAlias(symbol) {
    Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
    const links = getSymbolLinks(symbol);
    if (!links.aliasTarget) {
      links.aliasTarget = resolvingSymbol;
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      const target = getTargetOfAliasDeclaration(node);
      if (links.aliasTarget === resolvingSymbol) {
        links.aliasTarget = target || unknownSymbol;
      } else {
        error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
      }
    } else if (links.aliasTarget === resolvingSymbol) {
      links.aliasTarget = unknownSymbol;
    }
    return links.aliasTarget;
  }
  function tryResolveAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (links.aliasTarget !== resolvingSymbol) {
      return resolveAlias(symbol);
    }
    return void 0;
  }
  function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) {
    const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol);
    const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration);
    const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName(
      typeOnlyDeclaration.moduleSpecifier,
      typeOnlyDeclaration.moduleSpecifier,
      /*ignoreErrors*/
      true
    ) : resolveAlias(typeOnlyDeclaration.symbol));
    const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0;
    let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags;
    let seenSymbols;
    while (symbol.flags & 2097152 /* Alias */) {
      const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol));
      if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || (typeOnlyExportStarTargets == null ? void 0 : typeOnlyExportStarTargets.get(target.escapedName)) === target) {
        break;
      }
      if (target === unknownSymbol) {
        return -1 /* All */;
      }
      if (target === symbol || (seenSymbols == null ? void 0 : seenSymbols.has(target))) {
        break;
      }
      if (target.flags & 2097152 /* Alias */) {
        if (seenSymbols) {
          seenSymbols.add(target);
        } else {
          seenSymbols = /* @__PURE__ */ new Set([symbol, target]);
        }
      }
      flags |= target.flags;
      symbol = target;
    }
    return flags;
  }
  function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty, exportStarDeclaration, exportStarName) {
    if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false;
    const sourceSymbol = getSymbolOfDeclaration(aliasDeclaration);
    if (isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
      const links2 = getSymbolLinks(sourceSymbol);
      links2.typeOnlyDeclaration = aliasDeclaration;
      return true;
    }
    if (exportStarDeclaration) {
      const links2 = getSymbolLinks(sourceSymbol);
      links2.typeOnlyDeclaration = exportStarDeclaration;
      if (sourceSymbol.escapedName !== exportStarName) {
        links2.typeOnlyExportStarName = exportStarName;
      }
      return true;
    }
    const links = getSymbolLinks(sourceSymbol);
    return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty) || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
  }
  function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
    var _a;
    if (target && (aliasDeclarationLinks.typeOnlyDeclaration === void 0 || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
      const exportSymbol = ((_a = target.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)) ?? target;
      const typeOnly = exportSymbol.declarations && find(exportSymbol.declarations, isTypeOnlyImportOrExportDeclaration);
      aliasDeclarationLinks.typeOnlyDeclaration = typeOnly ?? getSymbolLinks(exportSymbol).typeOnlyDeclaration ?? false;
    }
    return !!aliasDeclarationLinks.typeOnlyDeclaration;
  }
  function getTypeOnlyAliasDeclaration(symbol, include) {
    var _a;
    if (!(symbol.flags & 2097152 /* Alias */)) {
      return void 0;
    }
    const links = getSymbolLinks(symbol);
    if (links.typeOnlyDeclaration === void 0) {
      links.typeOnlyDeclaration = false;
      const resolved = resolveSymbol(symbol);
      markSymbolOfAliasDeclarationIfTypeOnly(
        (_a = symbol.declarations) == null ? void 0 : _a[0],
        getDeclarationOfAliasSymbol(symbol) && getImmediateAliasedSymbol(symbol),
        resolved,
        /*overwriteEmpty*/
        true
      );
    }
    if (include === void 0) {
      return links.typeOnlyDeclaration || void 0;
    }
    if (links.typeOnlyDeclaration) {
      const resolved = links.typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? resolveSymbol(getExportsOfModule(links.typeOnlyDeclaration.symbol.parent).get(links.typeOnlyExportStarName || symbol.escapedName)) : resolveAlias(links.typeOnlyDeclaration.symbol);
      return getSymbolFlags(resolved) & include ? links.typeOnlyDeclaration : void 0;
    }
    return void 0;
  }
  function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
    if (entityName.kind === 80 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
      entityName = entityName.parent;
    }
    if (entityName.kind === 80 /* Identifier */ || entityName.parent.kind === 166 /* QualifiedName */) {
      return resolveEntityName(
        entityName,
        1920 /* Namespace */,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      );
    } else {
      Debug.assert(entityName.parent.kind === 271 /* ImportEqualsDeclaration */);
      return resolveEntityName(
        entityName,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
        /*ignoreErrors*/
        false,
        dontResolveAlias
      );
    }
  }
  function getFullyQualifiedName(symbol, containingLocation) {
    return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(
      symbol,
      containingLocation,
      /*meaning*/
      void 0,
      32 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */
    );
  }
  function getContainingQualifiedNameNode(node) {
    while (isQualifiedName(node.parent)) {
      node = node.parent;
    }
    return node;
  }
  function tryGetQualifiedNameAsValue(node) {
    let left = getFirstIdentifier(node);
    let symbol = resolveName(
      left,
      left,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (!symbol) {
      return void 0;
    }
    while (isQualifiedName(left.parent)) {
      const type = getTypeOfSymbol(symbol);
      symbol = getPropertyOfType(type, left.parent.right.escapedText);
      if (!symbol) {
        return void 0;
      }
      left = left.parent;
    }
    return symbol;
  }
  function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
    if (nodeIsMissing(name)) {
      return void 0;
    }
    const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
    let symbol;
    if (name.kind === 80 /* Identifier */) {
      const message = meaning === namespaceMeaning || nodeIsSynthesized(name) ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name));
      const symbolFromJSPrototype = isInJSFile(name) && !nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : void 0;
      symbol = getMergedSymbol(resolveName(
        location || name,
        name,
        meaning,
        ignoreErrors || symbolFromJSPrototype ? void 0 : message,
        /*isUse*/
        true,
        /*excludeGlobals*/
        false
      ));
      if (!symbol) {
        return getMergedSymbol(symbolFromJSPrototype);
      }
    } else if (name.kind === 166 /* QualifiedName */ || name.kind === 211 /* PropertyAccessExpression */) {
      const left = name.kind === 166 /* QualifiedName */ ? name.left : name.expression;
      const right = name.kind === 166 /* QualifiedName */ ? name.right : name.name;
      let namespace = resolveEntityName(
        left,
        namespaceMeaning,
        ignoreErrors,
        /*dontResolveAlias*/
        false,
        location
      );
      if (!namespace || nodeIsMissing(right)) {
        return void 0;
      } else if (namespace === unknownSymbol) {
        return namespace;
      }
      if (namespace.valueDeclaration && isInJSFile(namespace.valueDeclaration) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && isCommonJsRequire(namespace.valueDeclaration.initializer)) {
        const moduleName = namespace.valueDeclaration.initializer.arguments[0];
        const moduleSym = resolveExternalModuleName(moduleName, moduleName);
        if (moduleSym) {
          const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
          if (resolvedModuleSymbol) {
            namespace = resolvedModuleSymbol;
          }
        }
      }
      symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
      if (!symbol && namespace.flags & 2097152 /* Alias */) {
        symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(resolveAlias(namespace)), right.escapedText, meaning));
      }
      if (!symbol) {
        if (!ignoreErrors) {
          const namespaceName = getFullyQualifiedName(namespace);
          const declarationName = declarationNameToString(right);
          const suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace);
          if (suggestionForNonexistentModule) {
            error(right, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule));
            return void 0;
          }
          const containingQualifiedName = isQualifiedName(name) && getContainingQualifiedNameNode(name);
          const canSuggestTypeof = globalObjectType && meaning & 788968 /* Type */ && containingQualifiedName && !isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName);
          if (canSuggestTypeof) {
            error(
              containingQualifiedName,
              Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0,
              entityNameToString(containingQualifiedName)
            );
            return void 0;
          }
          if (meaning & 1920 /* Namespace */ && isQualifiedName(name.parent)) {
            const exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */));
            if (exportedTypeSymbol) {
              error(
                name.parent.right,
                Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,
                symbolToString(exportedTypeSymbol),
                unescapeLeadingUnderscores(name.parent.right.escapedText)
              );
              return void 0;
            }
          }
          error(right, Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
        }
        return void 0;
      }
    } else {
      Debug.assertNever(name, "Unknown entity name kind.");
    }
    if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 277 /* ExportAssignment */)) {
      markSymbolOfAliasDeclarationIfTypeOnly(
        getAliasDeclarationFromName(name),
        symbol,
        /*finalTarget*/
        void 0,
        /*overwriteEmpty*/
        true
      );
    }
    return symbol.flags & meaning || dontResolveAlias ? symbol : resolveAlias(symbol);
  }
  function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
    if (isJSDocTypeReference(name.parent)) {
      const secondaryLocation = getAssignmentDeclarationLocation(name.parent);
      if (secondaryLocation) {
        return resolveName(
          secondaryLocation,
          name,
          meaning,
          /*nameNotFoundMessage*/
          void 0,
          /*isUse*/
          true
        );
      }
    }
  }
  function getAssignmentDeclarationLocation(node) {
    const typeAlias = findAncestor(node, (node2) => !(isJSDocNode(node2) || node2.flags & 16777216 /* JSDoc */) ? "quit" : isJSDocTypeAlias(node2));
    if (typeAlias) {
      return;
    }
    const host2 = getJSDocHost(node);
    if (host2 && isExpressionStatement(host2) && isPrototypePropertyAssignment(host2.expression)) {
      const symbol = getSymbolOfDeclaration(host2.expression.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    if (host2 && isFunctionExpression(host2) && isPrototypePropertyAssignment(host2.parent) && isExpressionStatement(host2.parent.parent)) {
      const symbol = getSymbolOfDeclaration(host2.parent.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    if (host2 && (isObjectLiteralMethod(host2) || isPropertyAssignment(host2)) && isBinaryExpression(host2.parent.parent) && getAssignmentDeclarationKind(host2.parent.parent) === 6 /* Prototype */) {
      const symbol = getSymbolOfDeclaration(host2.parent.parent.left);
      if (symbol) {
        return getDeclarationOfJSPrototypeContainer(symbol);
      }
    }
    const sig = getEffectiveJSDocHost(node);
    if (sig && isFunctionLike(sig)) {
      const symbol = getSymbolOfDeclaration(sig);
      return symbol && symbol.valueDeclaration;
    }
  }
  function getDeclarationOfJSPrototypeContainer(symbol) {
    const decl = symbol.parent.valueDeclaration;
    if (!decl) {
      return void 0;
    }
    const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : void 0;
    return initializer || decl;
  }
  function getExpandoSymbol(symbol) {
    const decl = symbol.valueDeclaration;
    if (!decl || !isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || getExpandoInitializer(
      decl,
      /*isPrototypeAssignment*/
      false
    )) {
      return void 0;
    }
    const init = isVariableDeclaration(decl) ? getDeclaredExpandoInitializer(decl) : getAssignedExpandoInitializer(decl);
    if (init) {
      const initSymbol = getSymbolOfNode(init);
      if (initSymbol) {
        return mergeJSSymbols(initSymbol, symbol);
      }
    }
  }
  function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
    const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */;
    const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
    return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage, ignoreErrors);
  }
  function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, ignoreErrors = false, isForAugmentation = false) {
    return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0;
  }
  function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
    if (errorNode && startsWith(moduleReference, "@types/")) {
      const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
      const withoutAtTypePrefix = removePrefix(moduleReference, "@types/");
      error(errorNode, diag2, withoutAtTypePrefix, moduleReference);
    }
    const ambientModule = tryFindAmbientModule(
      moduleReference,
      /*withAugmentations*/
      true
    );
    if (ambientModule) {
      return ambientModule;
    }
    const currentSourceFile = getSourceFileOfNode(location);
    const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _a.name) || ((_b = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _b.argument.literal) || (isVariableDeclaration(location) && location.initializer && isRequireCall(
      location.initializer,
      /*requireStringLiteralLikeArgument*/
      true
    ) ? location.initializer.arguments[0] : void 0) || ((_c = findAncestor(location, isImportCall)) == null ? void 0 : _c.arguments[0]) || ((_d = findAncestor(location, or(isImportDeclaration, isJSDocImportTag, isExportDeclaration))) == null ? void 0 : _d.moduleSpecifier) || ((_e = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _e.moduleReference.expression);
    const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : host.getDefaultResolutionModeForFile(currentSourceFile);
    const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
    const resolvedModule = (_f = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _f.resolvedModule;
    const resolutionDiagnostic = errorNode && resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile);
    const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName);
    if (sourceFile) {
      if (resolutionDiagnostic) {
        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
      }
      if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) {
        const importOrExport = ((_g = findAncestor(location, isImportDeclaration)) == null ? void 0 : _g.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
        if (errorNode && importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) {
          error(
            errorNode,
            Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead,
            getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))
          );
        }
      } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) {
        const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
        if (errorNode && !((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) {
          const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference));
          error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension);
        }
      } else if (compilerOptions.rewriteRelativeImportExtensions && !(location.flags & 33554432 /* Ambient */) && !isDeclarationFileName(moduleReference) && !isLiteralImportTypeNode(location) && !isPartOfTypeOnlyImportOrExportDeclaration(location)) {
        const shouldRewrite = shouldRewriteModuleSpecifier(moduleReference, compilerOptions);
        if (!resolvedModule.resolvedUsingTsExtension && shouldRewrite) {
          error(
            errorNode,
            Diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolves_to_0,
            getRelativePathFromFile(getNormalizedAbsolutePath(currentSourceFile.fileName, host.getCurrentDirectory()), resolvedModule.resolvedFileName, hostGetCanonicalFileName(host))
          );
        } else if (resolvedModule.resolvedUsingTsExtension && !shouldRewrite && sourceFileMayBeEmitted(sourceFile, host)) {
          error(
            errorNode,
            Diagnostics.This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_during_emit_because_it_is_not_a_relative_path,
            getAnyExtensionFromPath(moduleReference)
          );
        } else if (resolvedModule.resolvedUsingTsExtension && shouldRewrite) {
          const redirect = host.getResolvedProjectReferenceToRedirect(sourceFile.path);
          if (redirect) {
            const ignoreCase = !host.useCaseSensitiveFileNames();
            const ownRootDir = host.getCommonSourceDirectory();
            const otherRootDir = getCommonSourceDirectoryOfConfig(redirect.commandLine, ignoreCase);
            const rootDirPath = getRelativePathFromDirectory(ownRootDir, otherRootDir, ignoreCase);
            const outDirPath = getRelativePathFromDirectory(compilerOptions.outDir || ownRootDir, redirect.commandLine.options.outDir || otherRootDir, ignoreCase);
            if (rootDirPath !== outDirPath) {
              error(
                errorNode,
                Diagnostics.This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_between_the_projects_output_files_is_not_the_same_as_the_relative_path_between_its_input_files
              );
            }
          }
        }
      }
      if (sourceFile.symbol) {
        if (errorNode && resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
          errorOnImplicitAnyModule(
            /*isError*/
            false,
            errorNode,
            currentSourceFile,
            mode,
            resolvedModule,
            moduleReference
          );
        }
        if (errorNode && (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */)) {
          const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration);
          const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l) || isJSDocImportTag(l));
          if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !hasResolutionModeOverride(overrideHost)) {
            if (findAncestor(location, isImportEqualsDeclaration)) {
              error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference);
            } else {
              let diagnosticDetails;
              const ext = tryGetExtensionFromPath2(currentSourceFile.fileName);
              if (ext === ".ts" /* Ts */ || ext === ".js" /* Js */ || ext === ".tsx" /* Tsx */ || ext === ".jsx" /* Jsx */) {
                diagnosticDetails = createModeMismatchDetails(currentSourceFile);
              }
              const message = (overrideHost == null ? void 0 : overrideHost.kind) === 272 /* ImportDeclaration */ && ((_i = overrideHost.importClause) == null ? void 0 : _i.isTypeOnly) ? Diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : (overrideHost == null ? void 0 : overrideHost.kind) === 205 /* ImportType */ ? Diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead;
              diagnostics.add(createDiagnosticForNodeFromMessageChain(
                getSourceFileOfNode(errorNode),
                errorNode,
                chainDiagnosticMessages(diagnosticDetails, message, moduleReference)
              ));
            }
          }
        }
        return getMergedSymbol(sourceFile.symbol);
      }
      if (errorNode && moduleNotFoundError && !isSideEffectImport(errorNode)) {
        error(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
      }
      return void 0;
    }
    if (patternAmbientModules) {
      const pattern = findBestPatternMatch(patternAmbientModules, (_) => _.pattern, moduleReference);
      if (pattern) {
        const augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
        if (augmentation) {
          return getMergedSymbol(augmentation);
        }
        return getMergedSymbol(pattern.symbol);
      }
    }
    if (!errorNode) {
      return void 0;
    }
    if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === void 0 || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
      if (isForAugmentation) {
        const diag2 = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
        error(errorNode, diag2, moduleReference, resolvedModule.resolvedFileName);
      } else {
        errorOnImplicitAnyModule(
          /*isError*/
          noImplicitAny && !!moduleNotFoundError,
          errorNode,
          currentSourceFile,
          mode,
          resolvedModule,
          moduleReference
        );
      }
      return void 0;
    }
    if (moduleNotFoundError) {
      if (resolvedModule) {
        const redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
        if (redirect) {
          error(errorNode, Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
          return void 0;
        }
      }
      if (resolutionDiagnostic) {
        error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
      } else {
        const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference);
        const resolutionIsNode16OrNext = moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */;
        if (!getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, ".json" /* Json */) && moduleResolutionKind !== 1 /* Classic */ && hasJsonModuleEmitEnabled(compilerOptions)) {
          error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
        } else if (mode === 99 /* ESNext */ && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) {
          const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path));
          const suggestedExt = (_j = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))) == null ? void 0 : _j[1];
          if (suggestedExt) {
            error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt);
          } else {
            error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_ECMAScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path);
          }
        } else {
          if ((_k = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _k.alternateResult) {
            const errorInfo = createModuleNotFoundChain(currentSourceFile, host, moduleReference, mode, moduleReference);
            errorOrSuggestion(
              /*isError*/
              true,
              errorNode,
              chainDiagnosticMessages(errorInfo, moduleNotFoundError, moduleReference)
            );
          } else {
            error(errorNode, moduleNotFoundError, moduleReference);
          }
        }
      }
    }
    return void 0;
    function getSuggestedImportSource(tsExtension) {
      const importSourceWithoutExtension = removeExtension(moduleReference, tsExtension);
      if (emitModuleKindIsNonNodeESM(moduleKind) || mode === 99 /* ESNext */) {
        const preferTs = isDeclarationFileName(moduleReference) && shouldAllowImportingTsExtension(compilerOptions);
        const ext = tsExtension === ".mts" /* Mts */ || tsExtension === ".d.mts" /* Dmts */ ? preferTs ? ".mts" : ".mjs" : tsExtension === ".cts" /* Cts */ || tsExtension === ".d.mts" /* Dmts */ ? preferTs ? ".cts" : ".cjs" : preferTs ? ".ts" : ".js";
        return importSourceWithoutExtension + ext;
      }
      return importSourceWithoutExtension;
    }
  }
  function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) {
    if (isSideEffectImport(errorNode)) {
      return;
    }
    let errorInfo;
    if (!isExternalModuleNameRelative(moduleReference) && packageId) {
      errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name);
    }
    errorOrSuggestion(
      isError,
      errorNode,
      chainDiagnosticMessages(
        errorInfo,
        Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type,
        moduleReference,
        resolvedFileName
      )
    );
  }
  function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
    if (moduleSymbol == null ? void 0 : moduleSymbol.exports) {
      const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
      const exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
      return getMergedSymbol(exported) || moduleSymbol;
    }
    return void 0;
  }
  function getCommonJsExportEquals(exported, moduleSymbol) {
    if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
      return exported;
    }
    const links = getSymbolLinks(exported);
    if (links.cjsExportMerged) {
      return links.cjsExportMerged;
    }
    const merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
    merged.flags = merged.flags | 512 /* ValueModule */;
    if (merged.exports === void 0) {
      merged.exports = createSymbolTable();
    }
    moduleSymbol.exports.forEach((s, name) => {
      if (name === "export=" /* ExportEquals */) return;
      merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
    });
    if (merged === exported) {
      getSymbolLinks(merged).resolvedExports = void 0;
      getSymbolLinks(merged).resolvedMembers = void 0;
    }
    getSymbolLinks(merged).cjsExportMerged = merged;
    return links.cjsExportMerged = merged;
  }
  function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
    var _a;
    const symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
    if (!dontResolveAlias && symbol) {
      if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !getDeclarationOfKind(symbol, 307 /* SourceFile */)) {
        const compilerOptionName = moduleKind >= 5 /* ES2015 */ ? "allowSyntheticDefaultImports" : "esModuleInterop";
        error(referencingLocation, Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName);
        return symbol;
      }
      const referenceParent = referencingLocation.parent;
      if (isImportDeclaration(referenceParent) && getNamespaceDeclarationNode(referenceParent) || isImportCall(referenceParent)) {
        const reference = isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier;
        const type = getTypeOfSymbol(symbol);
        const defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference);
        if (defaultOnlyType) {
          return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent);
        }
        const targetFile = (_a = moduleSymbol == null ? void 0 : moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
        const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getEmitSyntaxForModuleSpecifierExpression(reference), host.getImpliedNodeFormatForEmit(targetFile));
        if (getESModuleInterop(compilerOptions) || isEsmCjsRef) {
          let sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
          if (!sigs || !sigs.length) {
            sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
          }
          if (sigs && sigs.length || getPropertyOfType(
            type,
            "default" /* Default */,
            /*skipObjectFunctionPropertyAugment*/
            true
          ) || isEsmCjsRef) {
            const moduleType = type.flags & 3670016 /* StructuredType */ ? getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference) : createDefaultPropertyWrapperForModule(symbol, symbol.parent);
            return cloneTypeAsModuleType(symbol, moduleType, referenceParent);
          }
        }
      }
    }
    return symbol;
  }
  function cloneTypeAsModuleType(symbol, moduleType, referenceParent) {
    const result = createSymbol(symbol.flags, symbol.escapedName);
    result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
    result.parent = symbol.parent;
    result.links.target = symbol;
    result.links.originatingImport = referenceParent;
    if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
    if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
    if (symbol.members) result.members = new Map(symbol.members);
    if (symbol.exports) result.exports = new Map(symbol.exports);
    const resolvedModuleType = resolveStructuredTypeMembers(moduleType);
    result.links.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.indexInfos);
    return result;
  }
  function hasExportAssignmentSymbol(moduleSymbol) {
    return moduleSymbol.exports.get("export=" /* ExportEquals */) !== void 0;
  }
  function getExportsOfModuleAsArray(moduleSymbol) {
    return symbolsToArray(getExportsOfModule(moduleSymbol));
  }
  function getExportsAndPropertiesOfModule(moduleSymbol) {
    const exports2 = getExportsOfModuleAsArray(moduleSymbol);
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals !== moduleSymbol) {
      const type = getTypeOfSymbol(exportEquals);
      if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
        addRange(exports2, getPropertiesOfType(type));
      }
    }
    return exports2;
  }
  function forEachExportAndPropertyOfModule(moduleSymbol, cb) {
    const exports2 = getExportsOfModule(moduleSymbol);
    exports2.forEach((symbol, key) => {
      if (!isReservedMemberName(key)) {
        cb(symbol, key);
      }
    });
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals !== moduleSymbol) {
      const type = getTypeOfSymbol(exportEquals);
      if (shouldTreatPropertiesOfExternalModuleAsExports(type)) {
        forEachPropertyOfType(type, (symbol, escapedName) => {
          cb(symbol, escapedName);
        });
      }
    }
  }
  function tryGetMemberInModuleExports(memberName, moduleSymbol) {
    const symbolTable = getExportsOfModule(moduleSymbol);
    if (symbolTable) {
      return symbolTable.get(memberName);
    }
  }
  function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
    const symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
    if (symbol) {
      return symbol;
    }
    const exportEquals = resolveExternalModuleSymbol(moduleSymbol);
    if (exportEquals === moduleSymbol) {
      return void 0;
    }
    const type = getTypeOfSymbol(exportEquals);
    return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : void 0;
  }
  function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) {
    return !(resolvedExternalModuleType.flags & 402784252 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path
    isArrayType(resolvedExternalModuleType) || isTupleType(resolvedExternalModuleType));
  }
  function getExportsOfSymbol(symbol) {
    return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols;
  }
  function getExportsOfModule(moduleSymbol) {
    const links = getSymbolLinks(moduleSymbol);
    if (!links.resolvedExports) {
      const { exports: exports2, typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol);
      links.resolvedExports = exports2;
      links.typeOnlyExportStarMap = typeOnlyExportStarMap;
    }
    return links.resolvedExports;
  }
  function extendExportSymbols(target, source, lookupTable, exportNode) {
    if (!source) return;
    source.forEach((sourceSymbol, id) => {
      if (id === "default" /* Default */) return;
      const targetSymbol = target.get(id);
      if (!targetSymbol) {
        target.set(id, sourceSymbol);
        if (lookupTable && exportNode) {
          lookupTable.set(id, {
            specifierText: getTextOfNode(exportNode.moduleSpecifier)
          });
        }
      } else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
        const collisionTracker = lookupTable.get(id);
        if (!collisionTracker.exportsWithDuplicate) {
          collisionTracker.exportsWithDuplicate = [exportNode];
        } else {
          collisionTracker.exportsWithDuplicate.push(exportNode);
        }
      }
    });
  }
  function getExportsOfModuleWorker(moduleSymbol) {
    const visitedSymbols = [];
    let typeOnlyExportStarMap;
    const nonTypeOnlyNames = /* @__PURE__ */ new Set();
    moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
    const exports2 = visit(moduleSymbol) || emptySymbols;
    if (typeOnlyExportStarMap) {
      nonTypeOnlyNames.forEach((name) => typeOnlyExportStarMap.delete(name));
    }
    return {
      exports: exports2,
      typeOnlyExportStarMap
    };
    function visit(symbol, exportStar, isTypeOnly) {
      if (!isTypeOnly && (symbol == null ? void 0 : symbol.exports)) {
        symbol.exports.forEach((_, name) => nonTypeOnlyNames.add(name));
      }
      if (!(symbol && symbol.exports && pushIfUnique(visitedSymbols, symbol))) {
        return;
      }
      const symbols = new Map(symbol.exports);
      const exportStars = symbol.exports.get("__export" /* ExportStar */);
      if (exportStars) {
        const nestedSymbols = createSymbolTable();
        const lookupTable = /* @__PURE__ */ new Map();
        if (exportStars.declarations) {
          for (const node of exportStars.declarations) {
            const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
            const exportedSymbols = visit(resolvedModule, node, isTypeOnly || node.isTypeOnly);
            extendExportSymbols(
              nestedSymbols,
              exportedSymbols,
              lookupTable,
              node
            );
          }
        }
        lookupTable.forEach(({ exportsWithDuplicate }, id) => {
          if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
            return;
          }
          for (const node of exportsWithDuplicate) {
            diagnostics.add(createDiagnosticForNode(
              node,
              Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity,
              lookupTable.get(id).specifierText,
              unescapeLeadingUnderscores(id)
            ));
          }
        });
        extendExportSymbols(symbols, nestedSymbols);
      }
      if (exportStar == null ? void 0 : exportStar.isTypeOnly) {
        typeOnlyExportStarMap ?? (typeOnlyExportStarMap = /* @__PURE__ */ new Map());
        symbols.forEach(
          (_, escapedName) => typeOnlyExportStarMap.set(
            escapedName,
            exportStar
          )
        );
      }
      return symbols;
    }
  }
  function getMergedSymbol(symbol) {
    let merged;
    return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
  }
  function getSymbolOfDeclaration(node) {
    return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
  }
  function getSymbolOfNode(node) {
    return canHaveSymbol(node) ? getSymbolOfDeclaration(node) : void 0;
  }
  function getParentOfSymbol(symbol) {
    return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
  }
  function getFunctionExpressionParentSymbolOrSymbol(symbol) {
    var _a, _b;
    return ((_a = symbol.valueDeclaration) == null ? void 0 : _a.kind) === 219 /* ArrowFunction */ || ((_b = symbol.valueDeclaration) == null ? void 0 : _b.kind) === 218 /* FunctionExpression */ ? getSymbolOfNode(symbol.valueDeclaration.parent) || symbol : symbol;
  }
  function getAlternativeContainingModules(symbol, enclosingDeclaration) {
    const containingFile = getSourceFileOfNode(enclosingDeclaration);
    const id = getNodeId(containingFile);
    const links = getSymbolLinks(symbol);
    let results;
    if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
      return results;
    }
    if (containingFile && containingFile.imports) {
      for (const importRef of containingFile.imports) {
        if (nodeIsSynthesized(importRef)) continue;
        const resolvedModule = resolveExternalModuleName(
          enclosingDeclaration,
          importRef,
          /*ignoreErrors*/
          true
        );
        if (!resolvedModule) continue;
        const ref = getAliasForSymbolInContainer(resolvedModule, symbol);
        if (!ref) continue;
        results = append(results, resolvedModule);
      }
      if (length(results)) {
        (links.extendedContainersByFile || (links.extendedContainersByFile = /* @__PURE__ */ new Map())).set(id, results);
        return results;
      }
    }
    if (links.extendedContainers) {
      return links.extendedContainers;
    }
    const otherFiles = host.getSourceFiles();
    for (const file of otherFiles) {
      if (!isExternalModule(file)) continue;
      const sym = getSymbolOfDeclaration(file);
      const ref = getAliasForSymbolInContainer(sym, symbol);
      if (!ref) continue;
      results = append(results, sym);
    }
    return links.extendedContainers = results || emptyArray;
  }
  function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
    const container = getParentOfSymbol(symbol);
    if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
      return getWithAlternativeContainers(container);
    }
    const candidates = mapDefined(symbol.declarations, (d) => {
      if (!isAmbientModule(d) && d.parent) {
        if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
          return getSymbolOfDeclaration(d.parent);
        }
        if (isModuleBlock(d.parent) && d.parent.parent && resolveExternalModuleSymbol(getSymbolOfDeclaration(d.parent.parent)) === symbol) {
          return getSymbolOfDeclaration(d.parent.parent);
        }
      }
      if (isClassExpression(d) && isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 64 /* EqualsToken */ && isAccessExpression(d.parent.left) && isEntityNameExpression(d.parent.left.expression)) {
        if (isModuleExportsAccessExpression(d.parent.left) || isExportsIdentifier(d.parent.left.expression)) {
          return getSymbolOfDeclaration(getSourceFileOfNode(d));
        }
        checkExpressionCached(d.parent.left.expression);
        return getNodeLinks(d.parent.left.expression).resolvedSymbol;
      }
    });
    if (!length(candidates)) {
      return void 0;
    }
    const containers = mapDefined(candidates, (candidate) => getAliasForSymbolInContainer(candidate, symbol) ? candidate : void 0);
    let bestContainers = [];
    let alternativeContainers = [];
    for (const container2 of containers) {
      const [bestMatch, ...rest] = getWithAlternativeContainers(container2);
      bestContainers = append(bestContainers, bestMatch);
      alternativeContainers = addRange(alternativeContainers, rest);
    }
    return concatenate(bestContainers, alternativeContainers);
    function getWithAlternativeContainers(container2) {
      const additionalContainers = mapDefined(container2.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
      const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
      const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container2, meaning);
      if (enclosingDeclaration && container2.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain(
        container2,
        enclosingDeclaration,
        1920 /* Namespace */,
        /*useOnlyExternalAliasing*/
        false
      )) {
        return append(concatenate(concatenate([container2], additionalContainers), reexportContainers), objectLiteralContainer);
      }
      const firstVariableMatch = !(container2.flags & getQualifiedLeftMeaning(meaning)) && container2.flags & 788968 /* Type */ && getDeclaredTypeOfSymbol(container2).flags & 524288 /* Object */ && meaning === 111551 /* Value */ ? forEachSymbolTableInScope(enclosingDeclaration, (t) => {
        return forEachEntry(t, (s) => {
          if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container2)) {
            return s;
          }
        });
      }) : void 0;
      let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container2] : [...additionalContainers, container2];
      res = append(res, objectLiteralContainer);
      res = addRange(res, reexportContainers);
      return res;
    }
    function fileSymbolIfFileSymbolExportEqualsContainer(d) {
      return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
    }
  }
  function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
    const firstDecl = !!length(symbol.declarations) && first(symbol.declarations);
    if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && isVariableDeclaration(firstDecl.parent)) {
      if (isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
        return getSymbolOfDeclaration(firstDecl.parent);
      }
    }
  }
  function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
    const fileSymbol = getExternalModuleContainer(d);
    const exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
    return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : void 0;
  }
  function getAliasForSymbolInContainer(container, symbol) {
    if (container === getParentOfSymbol(symbol)) {
      return symbol;
    }
    const exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
    if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
      return container;
    }
    const exports2 = getExportsOfSymbol(container);
    const quick = exports2.get(symbol.escapedName);
    if (quick && getSymbolIfSameReference(quick, symbol)) {
      return quick;
    }
    return forEachEntry(exports2, (exported) => {
      if (getSymbolIfSameReference(exported, symbol)) {
        return exported;
      }
    });
  }
  function getSymbolIfSameReference(s1, s2) {
    if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
      return s1;
    }
  }
  function getExportSymbolOfValueSymbolIfExported(symbol) {
    return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 && symbol.exportSymbol || symbol);
  }
  function symbolIsValue(symbol, includeTypeOnlyMembers) {
    return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */);
  }
  function createType(flags) {
    var _a;
    const result = new Type7(checker, flags);
    typeCount++;
    result.id = typeCount;
    (_a = tracing) == null ? void 0 : _a.recordType(result);
    return result;
  }
  function createTypeWithSymbol(flags, symbol) {
    const result = createType(flags);
    result.symbol = symbol;
    return result;
  }
  function createOriginType(flags) {
    return new Type7(checker, flags);
  }
  function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */, debugIntrinsicName) {
    checkIntrinsicName(intrinsicName, debugIntrinsicName);
    const type = createType(kind);
    type.intrinsicName = intrinsicName;
    type.debugIntrinsicName = debugIntrinsicName;
    type.objectFlags = objectFlags | 524288 /* CouldContainTypeVariablesComputed */ | 2097152 /* IsGenericTypeComputed */ | 33554432 /* IsUnknownLikeUnionComputed */ | 16777216 /* IsNeverIntersectionComputed */;
    return type;
  }
  function checkIntrinsicName(name, debug) {
    const key = `${name},${debug ?? ""}`;
    if (seenIntrinsicNames.has(key)) {
      Debug.fail(`Duplicate intrinsic type name ${name}${debug ? ` (${debug})` : ""}; you may need to pass a name to createIntrinsicType.`);
    }
    seenIntrinsicNames.add(key);
  }
  function createObjectType(objectFlags, symbol) {
    const type = createTypeWithSymbol(524288 /* Object */, symbol);
    type.objectFlags = objectFlags;
    type.members = void 0;
    type.properties = void 0;
    type.callSignatures = void 0;
    type.constructSignatures = void 0;
    type.indexInfos = void 0;
    return type;
  }
  function createTypeofType() {
    return getUnionType(arrayFrom(typeofNEFacts.keys(), getStringLiteralType));
  }
  function createTypeParameter(symbol) {
    return createTypeWithSymbol(262144 /* TypeParameter */, symbol);
  }
  function isReservedMemberName(name) {
    return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) !== 95 /* _ */ && name.charCodeAt(2) !== 64 /* at */ && name.charCodeAt(2) !== 35 /* hash */;
  }
  function getNamedMembers(members) {
    let result;
    members.forEach((symbol, id) => {
      if (isNamedMember(symbol, id)) {
        (result || (result = [])).push(symbol);
      }
    });
    return result || emptyArray;
  }
  function isNamedMember(member, escapedName) {
    return !isReservedMemberName(escapedName) && symbolIsValue(member);
  }
  function getNamedOrIndexSignatureMembers(members) {
    const result = getNamedMembers(members);
    const index = getIndexSymbolFromSymbolTable(members);
    return index ? concatenate(result, [index]) : result;
  }
  function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos) {
    const resolved = type;
    resolved.members = members;
    resolved.properties = emptyArray;
    resolved.callSignatures = callSignatures;
    resolved.constructSignatures = constructSignatures;
    resolved.indexInfos = indexInfos;
    if (members !== emptySymbols) resolved.properties = getNamedMembers(members);
    return resolved;
  }
  function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) {
    return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos);
  }
  function getResolvedTypeWithoutAbstractConstructSignatures(type) {
    if (type.constructSignatures.length === 0) return type;
    if (type.objectTypeWithoutAbstractConstructSignatures) return type.objectTypeWithoutAbstractConstructSignatures;
    const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & 4 /* Abstract */));
    if (type.constructSignatures === constructSignatures) return type;
    const typeCopy = createAnonymousType(
      type.symbol,
      type.members,
      type.callSignatures,
      some(constructSignatures) ? constructSignatures : emptyArray,
      type.indexInfos
    );
    type.objectTypeWithoutAbstractConstructSignatures = typeCopy;
    typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy;
    return typeCopy;
  }
  function forEachSymbolTableInScope(enclosingDeclaration, callback) {
    let result;
    for (let location = enclosingDeclaration; location; location = location.parent) {
      if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
        if (result = callback(
          location.locals,
          /*ignoreQualification*/
          void 0,
          /*isLocalNameLookup*/
          true,
          location
        )) {
          return result;
        }
      }
      switch (location.kind) {
        case 307 /* SourceFile */:
          if (!isExternalOrCommonJsModule(location)) {
            break;
          }
        // falls through
        case 267 /* ModuleDeclaration */:
          const sym = getSymbolOfDeclaration(location);
          if (result = callback(
            (sym == null ? void 0 : sym.exports) || emptySymbols,
            /*ignoreQualification*/
            void 0,
            /*isLocalNameLookup*/
            true,
            location
          )) {
            return result;
          }
          break;
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */:
        case 264 /* InterfaceDeclaration */:
          let table;
          (getSymbolOfDeclaration(location).members || emptySymbols).forEach((memberSymbol, key) => {
            if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
              (table || (table = createSymbolTable())).set(key, memberSymbol);
            }
          });
          if (table && (result = callback(
            table,
            /*ignoreQualification*/
            void 0,
            /*isLocalNameLookup*/
            false,
            location
          ))) {
            return result;
          }
          break;
      }
    }
    return callback(
      globals,
      /*ignoreQualification*/
      void 0,
      /*isLocalNameLookup*/
      true
    );
  }
  function getQualifiedLeftMeaning(rightMeaning) {
    return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
  }
  function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap = /* @__PURE__ */ new Map()) {
    if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
      return void 0;
    }
    const links = getSymbolLinks(symbol);
    const cache = links.accessibleChainCache || (links.accessibleChainCache = /* @__PURE__ */ new Map());
    const firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, (_, __, ___, node) => node);
    const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation ? getNodeId(firstRelevantLocation) : 0}|${meaning}`;
    if (cache.has(key)) {
      return cache.get(key);
    }
    const id = getSymbolId(symbol);
    let visitedSymbolTables = visitedSymbolTablesMap.get(id);
    if (!visitedSymbolTables) {
      visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
    }
    const result = forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
    cache.set(key, result);
    return result;
    function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
      if (!pushIfUnique(visitedSymbolTables, symbols)) {
        return void 0;
      }
      const result2 = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup);
      visitedSymbolTables.pop();
      return result2;
    }
    function canQualifySymbol(symbolFromSymbolTable, meaning2) {
      return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning2) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
      !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning2), useOnlyExternalAliasing, visitedSymbolTablesMap);
    }
    function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
      return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
      // and if symbolFromSymbolTable or alias resolution matches the symbol,
      // check the symbol can be qualified, it is only then this symbol is accessible
      !some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
    }
    function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) {
      if (isAccessible(
        symbols.get(symbol.escapedName),
        /*resolvedAliasSymbol*/
        void 0,
        ignoreQualification
      )) {
        return [symbol];
      }
      const result2 = forEachEntry(symbols, (symbolFromSymbolTable) => {
        if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */))) {
          const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
          const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
          if (candidate) {
            return candidate;
          }
        }
        if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
          if (isAccessible(
            getMergedSymbol(symbolFromSymbolTable.exportSymbol),
            /*resolvedAliasSymbol*/
            void 0,
            ignoreQualification
          )) {
            return [symbol];
          }
        }
      });
      return result2 || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : void 0);
    }
    function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
      if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
        return [symbolFromSymbolTable];
      }
      const candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
      const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(
        candidateTable,
        /*ignoreQualification*/
        true
      );
      if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
        return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
      }
    }
  }
  function needsQualification(symbol, enclosingDeclaration, meaning) {
    let qualify = false;
    forEachSymbolTableInScope(enclosingDeclaration, (symbolTable) => {
      let symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
      if (!symbolFromSymbolTable) {
        return false;
      }
      if (symbolFromSymbolTable === symbol) {
        return true;
      }
      const shouldResolveAlias = symbolFromSymbolTable.flags & 2097152 /* Alias */ && !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */);
      symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
      const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags;
      if (flags & meaning) {
        qualify = true;
        return true;
      }
      return false;
    });
    return qualify;
  }
  function isPropertyOrMethodDeclarationSymbol(symbol) {
    if (symbol.declarations && symbol.declarations.length) {
      for (const declaration of symbol.declarations) {
        switch (declaration.kind) {
          case 172 /* PropertyDeclaration */:
          case 174 /* MethodDeclaration */:
          case 177 /* GetAccessor */:
          case 178 /* SetAccessor */:
            continue;
          default:
            return false;
        }
      }
      return true;
    }
    return false;
  }
  function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      788968 /* Type */,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      true
    );
    return access.accessibility === 0 /* Accessible */;
  }
  function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      111551 /* Value */,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      true
    );
    return access.accessibility === 0 /* Accessible */;
  }
  function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
    const access = isSymbolAccessibleWorker(
      typeSymbol,
      enclosingDeclaration,
      flags,
      /*shouldComputeAliasesToMakeVisible*/
      false,
      /*allowModules*/
      false
    );
    return access.accessibility === 0 /* Accessible */;
  }
  function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
    if (!length(symbols)) return;
    let hadAccessibleChain;
    let earlyModuleBail = false;
    for (const symbol of symbols) {
      const accessibleSymbolChain = getAccessibleSymbolChain(
        symbol,
        enclosingDeclaration,
        meaning,
        /*useOnlyExternalAliasing*/
        false
      );
      if (accessibleSymbolChain) {
        hadAccessibleChain = symbol;
        const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
        if (hasAccessibleDeclarations) {
          return hasAccessibleDeclarations;
        }
      }
      if (allowModules) {
        if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
          if (shouldComputeAliasesToMakeVisible) {
            earlyModuleBail = true;
            continue;
          }
          return {
            accessibility: 0 /* Accessible */
          };
        }
      }
      const containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
      const parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
      if (parentResult) {
        return parentResult;
      }
    }
    if (earlyModuleBail) {
      return {
        accessibility: 0 /* Accessible */
      };
    }
    if (hadAccessibleChain) {
      return {
        accessibility: 1 /* NotAccessible */,
        errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
        errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : void 0
      };
    }
  }
  function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
    return isSymbolAccessibleWorker(
      symbol,
      enclosingDeclaration,
      meaning,
      shouldComputeAliasesToMakeVisible,
      /*allowModules*/
      true
    );
  }
  function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
    if (symbol && enclosingDeclaration) {
      const result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
      if (result) {
        return result;
      }
      const symbolExternalModule = forEach(symbol.declarations, getExternalModuleContainer);
      if (symbolExternalModule) {
        const enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
        if (symbolExternalModule !== enclosingExternalModule) {
          return {
            accessibility: 2 /* CannotBeNamed */,
            errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
            errorModuleName: symbolToString(symbolExternalModule),
            errorNode: isInJSFile(enclosingDeclaration) ? enclosingDeclaration : void 0
          };
        }
      }
      return {
        accessibility: 1 /* NotAccessible */,
        errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning)
      };
    }
    return { accessibility: 0 /* Accessible */ };
  }
  function getExternalModuleContainer(declaration) {
    const node = findAncestor(declaration, hasExternalModuleSymbol);
    return node && getSymbolOfDeclaration(node);
  }
  function hasExternalModuleSymbol(declaration) {
    return isAmbientModule(declaration) || declaration.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(declaration);
  }
  function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
    return isModuleWithStringLiteralName(declaration) || declaration.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(declaration);
  }
  function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
    let aliasesToMakeVisible;
    if (!every(filter(symbol.declarations, (d) => d.kind !== 80 /* Identifier */), getIsDeclarationVisible)) {
      return void 0;
    }
    return { accessibility: 0 /* Accessible */, aliasesToMakeVisible };
    function getIsDeclarationVisible(declaration) {
      var _a, _b;
      if (!isDeclarationVisible(declaration)) {
        const anyImportSyntax = getAnyImportSyntax(declaration);
        if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 32 /* Export */) && // import clause without export
        isDeclarationVisible(anyImportSyntax.parent)) {
          return addVisibleAlias(declaration, anyImportSyntax);
        } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 32 /* Export */) && // unexported variable statement
        isDeclarationVisible(declaration.parent.parent.parent)) {
          return addVisibleAlias(declaration, declaration.parent.parent);
        } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 32 /* Export */) && isDeclarationVisible(declaration.parent)) {
          return addVisibleAlias(declaration, declaration);
        } else if (isBindingElement(declaration)) {
          if (symbol.flags & 2097152 /* Alias */ && isInJSFile(declaration) && ((_a = declaration.parent) == null ? void 0 : _a.parent) && isVariableDeclaration(declaration.parent.parent) && ((_b = declaration.parent.parent.parent) == null ? void 0 : _b.parent) && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, 32 /* Export */) && declaration.parent.parent.parent.parent.parent && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
            return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
          } else if (symbol.flags & 2 /* BlockScopedVariable */) {
            const variableStatement = findAncestor(declaration, isVariableStatement);
            if (hasSyntacticModifier(variableStatement, 32 /* Export */)) {
              return true;
            }
            if (!isDeclarationVisible(variableStatement.parent)) {
              return false;
            }
            return addVisibleAlias(declaration, variableStatement);
          }
        }
        return false;
      }
      return true;
    }
    function addVisibleAlias(declaration, aliasingStatement) {
      if (shouldComputeAliasToMakeVisible) {
        getNodeLinks(declaration).isVisible = true;
        aliasesToMakeVisible = appendIfUnique(aliasesToMakeVisible, aliasingStatement);
      }
      return true;
    }
  }
  function getMeaningOfEntityNameReference(entityName) {
    let meaning;
    if (entityName.parent.kind === 186 /* TypeQuery */ || entityName.parent.kind === 233 /* ExpressionWithTypeArguments */ && !isPartOfTypeNode(entityName.parent) || entityName.parent.kind === 167 /* ComputedPropertyName */ || entityName.parent.kind === 182 /* TypePredicate */ && entityName.parent.parameterName === entityName) {
      meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
    } else if (entityName.kind === 166 /* QualifiedName */ || entityName.kind === 211 /* PropertyAccessExpression */ || entityName.parent.kind === 271 /* ImportEqualsDeclaration */ || entityName.parent.kind === 166 /* QualifiedName */ && entityName.parent.left === entityName || entityName.parent.kind === 211 /* PropertyAccessExpression */ && entityName.parent.expression === entityName || entityName.parent.kind === 212 /* ElementAccessExpression */ && entityName.parent.expression === entityName) {
      meaning = 1920 /* Namespace */;
    } else {
      meaning = 788968 /* Type */;
    }
    return meaning;
  }
  function isEntityNameVisible(entityName, enclosingDeclaration, shouldComputeAliasToMakeVisible = true) {
    const meaning = getMeaningOfEntityNameReference(entityName);
    const firstIdentifier = getFirstIdentifier(entityName);
    const symbol = resolveName(
      enclosingDeclaration,
      firstIdentifier.escapedText,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
    if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
      return { accessibility: 0 /* Accessible */ };
    }
    if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible(
      getSymbolOfDeclaration(getThisContainer(
        firstIdentifier,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      )),
      firstIdentifier,
      meaning,
      /*shouldComputeAliasesToMakeVisible*/
      false
    ).accessibility === 0 /* Accessible */) {
      return { accessibility: 0 /* Accessible */ };
    }
    if (!symbol) {
      return {
        accessibility: 3 /* NotResolved */,
        errorSymbolName: getTextOfNode(firstIdentifier),
        errorNode: firstIdentifier
      };
    }
    return hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || {
      accessibility: 1 /* NotAccessible */,
      errorSymbolName: getTextOfNode(firstIdentifier),
      errorNode: firstIdentifier
    };
  }
  function symbolToString(symbol, enclosingDeclaration, meaning, flags = 4 /* AllowAnyNodeKind */, writer) {
    let nodeFlags = 70221824 /* IgnoreErrors */;
    let internalNodeFlags = 0 /* None */;
    if (flags & 2 /* UseOnlyExternalAliasing */) {
      nodeFlags |= 128 /* UseOnlyExternalAliasing */;
    }
    if (flags & 1 /* WriteTypeParametersOrArguments */) {
      nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
    }
    if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
      nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
    }
    if (flags & 32 /* DoNotIncludeSymbolChain */) {
      internalNodeFlags |= 4 /* DoNotIncludeSymbolChain */;
    }
    if (flags & 16 /* WriteComputedProps */) {
      internalNodeFlags |= 1 /* WriteComputedProps */;
    }
    const builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName;
    return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker);
    function symbolToStringWorker(writer2) {
      const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags, internalNodeFlags);
      const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 307 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        4 /* Unspecified */,
        entity,
        /*sourceFile*/
        sourceFile,
        writer2
      );
      return writer2;
    }
  }
  function signatureToString(signature, enclosingDeclaration, flags = 0 /* None */, kind, writer) {
    return writer ? signatureToStringWorker(writer).getText() : usingSingleLineStringWriter(signatureToStringWorker);
    function signatureToStringWorker(writer2) {
      let sigOutput;
      if (flags & 262144 /* WriteArrowStyleSignature */) {
        sigOutput = kind === 1 /* Construct */ ? 185 /* ConstructorType */ : 184 /* FunctionType */;
      } else {
        sigOutput = kind === 1 /* Construct */ ? 180 /* ConstructSignature */ : 179 /* CallSignature */;
      }
      const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
      const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        4 /* Unspecified */,
        sig,
        /*sourceFile*/
        sourceFile,
        getTrailingSemicolonDeferringWriter(writer2)
      );
      return writer2;
    }
  }
  function typeToString(type, enclosingDeclaration, flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer = createTextWriter("")) {
    const noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
    const typeNode = nodeBuilder.typeToTypeNode(
      type,
      enclosingDeclaration,
      toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0 /* None */),
      /*internalFlags*/
      void 0
    );
    if (typeNode === void 0) return Debug.fail("should always get typenode");
    const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults();
    const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
    printer.writeNode(
      4 /* Unspecified */,
      typeNode,
      /*sourceFile*/
      sourceFile,
      writer
    );
    const result = writer.getText();
    const maxLength = noTruncation ? noTruncationMaximumTruncationLength * 2 : defaultMaximumTruncationLength * 2;
    if (maxLength && result && result.length >= maxLength) {
      return result.substr(0, maxLength - "...".length) + "...";
    }
    return result;
  }
  function getTypeNamesForErrorDisplay(left, right) {
    let leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
    let rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
    if (leftStr === rightStr) {
      leftStr = getTypeNameForErrorDisplay(left);
      rightStr = getTypeNameForErrorDisplay(right);
    }
    return [leftStr, rightStr];
  }
  function getTypeNameForErrorDisplay(type) {
    return typeToString(
      type,
      /*enclosingDeclaration*/
      void 0,
      64 /* UseFullyQualifiedType */
    );
  }
  function symbolValueDeclarationIsContextSensitive(symbol) {
    return symbol && !!symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
  }
  function toNodeBuilderFlags(flags = 0 /* None */) {
    return flags & 848330095 /* NodeBuilderFlagsMask */;
  }
  function isClassInstanceSide(type) {
    return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & 524288 /* Object */) && !!(getObjectFlags(type) & 16777216 /* IsClassInstanceClone */));
  }
  function getTypeFromTypeNodeWithoutContext(node) {
    return getTypeFromTypeNode(node);
  }
  function createNodeBuilder() {
    const syntacticBuilderResolver = {
      evaluateEntityNameExpression,
      isExpandoFunctionDeclaration,
      hasLateBindableName,
      shouldRemoveDeclaration(context, node) {
        return !(context.internalFlags & 8 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */);
      },
      createRecoveryBoundary(context) {
        return createRecoveryBoundary(context);
      },
      isDefinitelyReferenceToGlobalSymbolObject,
      getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration,
      requiresAddingImplicitUndefined(declaration, symbol, enclosingDeclaration) {
        var _a;
        switch (declaration.kind) {
          case 172 /* PropertyDeclaration */:
          case 171 /* PropertySignature */:
          case 348 /* JSDocPropertyTag */:
            symbol ?? (symbol = getSymbolOfDeclaration(declaration));
            const type = getTypeOfSymbol(symbol);
            return !!(symbol.flags & 4 /* Property */ && symbol.flags & 16777216 /* Optional */ && isOptionalDeclaration(declaration) && ((_a = symbol.links) == null ? void 0 : _a.mappedType) && containsNonMissingUndefinedType(type));
          case 169 /* Parameter */:
          case 341 /* JSDocParameterTag */:
            return requiresAddingImplicitUndefined(declaration, enclosingDeclaration);
          default:
            Debug.assertNever(declaration);
        }
      },
      isOptionalParameter,
      isUndefinedIdentifierExpression(node) {
        Debug.assert(isExpressionNode(node));
        return getSymbolAtLocation(node) === undefinedSymbol;
      },
      isEntityNameVisible(context, entityName, shouldComputeAliasToMakeVisible) {
        return isEntityNameVisible(entityName, context.enclosingDeclaration, shouldComputeAliasToMakeVisible);
      },
      serializeExistingTypeNode(context, typeNode, addUndefined) {
        return serializeExistingTypeNode(context, typeNode, !!addUndefined);
      },
      serializeReturnTypeForSignature(syntacticContext, signatureDeclaration) {
        const context = syntacticContext;
        const signature = getSignatureFromDeclaration(signatureDeclaration);
        const returnType = context.enclosingSymbolTypes.get(getSymbolId(getSymbolOfDeclaration(signatureDeclaration))) ?? instantiateType(getReturnTypeOfSignature(signature), context.mapper);
        return serializeInferredReturnTypeForSignature(context, signature, returnType);
      },
      serializeTypeOfExpression(syntacticContext, expr) {
        const context = syntacticContext;
        const type = instantiateType(getWidenedType(getRegularTypeOfExpression(expr)), context.mapper);
        return typeToTypeNodeHelper(type, context);
      },
      serializeTypeOfDeclaration(syntacticContext, declaration, symbol) {
        var _a;
        const context = syntacticContext;
        symbol ?? (symbol = getSymbolOfDeclaration(declaration));
        let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol));
        if (type === void 0) {
          type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? instantiateType(getWidenedLiteralType(getTypeOfSymbol(symbol)), context.mapper) : errorType;
        }
        const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration);
        if (addUndefinedForParameter) {
          type = getOptionalType(type);
        }
        return serializeInferredTypeForDeclaration(symbol, context, type);
      },
      serializeNameOfParameter(context, parameter) {
        return parameterToParameterDeclarationName(getSymbolOfDeclaration(parameter), parameter, context);
      },
      serializeEntityName(syntacticContext, node) {
        const context = syntacticContext;
        const symbol = getSymbolAtLocation(
          node,
          /*ignoreErrors*/
          true
        );
        if (!symbol) return void 0;
        if (!isValueSymbolAccessible(symbol, context.enclosingDeclaration)) return void 0;
        return symbolToExpression(symbol, context, 111551 /* Value */ | 1048576 /* ExportValue */);
      },
      serializeTypeName(context, node, isTypeOf, typeArguments) {
        return serializeTypeName(context, node, isTypeOf, typeArguments);
      },
      getJsDocPropertyOverride(syntacticContext, jsDocTypeLiteral, jsDocProperty) {
        const context = syntacticContext;
        const name = isIdentifier(jsDocProperty.name) ? jsDocProperty.name : jsDocProperty.name.right;
        const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, jsDocTypeLiteral), name.escapedText);
        const overrideTypeNode = typeViaParent && jsDocProperty.typeExpression && getTypeFromTypeNode2(context, jsDocProperty.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0;
        return overrideTypeNode;
      },
      enterNewScope(context, node) {
        if (isFunctionLike(node) || isJSDocSignature(node)) {
          const signature = getSignatureFromDeclaration(node);
          const expandedParams = getExpandedParameters(
            signature,
            /*skipUnionExpanding*/
            true
          )[0];
          return enterNewScope(context, node, expandedParams, signature.typeParameters);
        } else {
          const typeParameters = isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))];
          return enterNewScope(
            context,
            node,
            /*expandedParams*/
            void 0,
            typeParameters
          );
        }
      },
      markNodeReuse(context, range, location) {
        return setTextRange2(context, range, location);
      },
      trackExistingEntityName(context, node) {
        return trackExistingEntityName(node, context);
      },
      trackComputedName(context, accessExpression) {
        trackComputedName(accessExpression, context.enclosingDeclaration, context);
      },
      getModuleSpecifierOverride(syntacticContext, parent, lit) {
        const context = syntacticContext;
        if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) {
          let name = lit.text;
          const nodeSymbol = getNodeLinks(parent).resolvedSymbol;
          const meaning = parent.isTypeOf ? 111551 /* Value */ : 788968 /* Type */;
          const parentSymbol = nodeSymbol && isSymbolAccessible(
            nodeSymbol,
            context.enclosingDeclaration,
            meaning,
            /*shouldComputeAliasesToMakeVisible*/
            false
          ).accessibility === 0 /* Accessible */ && lookupSymbolChain(
            nodeSymbol,
            context,
            meaning,
            /*yieldModuleSymbol*/
            true
          )[0];
          if (parentSymbol && isExternalModuleSymbol(parentSymbol)) {
            name = getSpecifierForModuleSymbol(parentSymbol, context);
          } else {
            const targetFile = getExternalModuleFileFromDeclaration(parent);
            if (targetFile) {
              name = getSpecifierForModuleSymbol(targetFile.symbol, context);
            }
          }
          if (name.includes("/node_modules/")) {
            context.encounteredError = true;
            if (context.tracker.reportLikelyUnsafeImportRequiredError) {
              context.tracker.reportLikelyUnsafeImportRequiredError(name);
            }
          }
          return name;
        }
      },
      canReuseTypeNode(context, typeNode) {
        return canReuseTypeNode(context, typeNode);
      },
      canReuseTypeNodeAnnotation(syntacticContext, node, existing, symbol, requiresAddingUndefined) {
        var _a;
        const context = syntacticContext;
        if (context.enclosingDeclaration === void 0) return false;
        symbol ?? (symbol = getSymbolOfDeclaration(node));
        let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol));
        if (type === void 0) {
          if (symbol.flags & 98304 /* Accessor */) {
            type = node.kind === 178 /* SetAccessor */ ? getWriteTypeOfSymbol(symbol) : getTypeOfAccessors(symbol);
          } else if (isValueSignatureDeclaration(node)) {
            type = getReturnTypeOfSignature(getSignatureFromDeclaration(node));
          } else {
            type = getTypeOfSymbol(symbol);
          }
        }
        let annotationType = getTypeFromTypeNodeWithoutContext(existing);
        if (isErrorType(annotationType)) {
          return true;
        }
        if (requiresAddingUndefined && annotationType) {
          annotationType = addOptionality(annotationType, !isParameter(node));
        }
        return !!annotationType && typeNodeIsEquivalentToType(node, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type);
      }
    };
    return {
      syntacticBuilderResolver,
      typeToTypeNode: (type, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeToTypeNodeHelper(type, context)),
      typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)),
      serializeTypeForExpression: (expr, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfExpression(expr, context)),
      serializeTypeForDeclaration: (declaration, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, symbol, context)),
      serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeReturnTypeForSignature(signature, getSymbolOfDeclaration(signature), context)),
      indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper(
        indexInfo,
        context,
        /*typeNode*/
        void 0
      )),
      signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)),
      symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToName(
        symbol,
        context,
        meaning,
        /*expectsIdentifier*/
        false
      )),
      symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToExpression(symbol, context, meaning)),
      symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)),
      symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToParameterDeclaration(symbol, context)),
      typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParameterToDeclaration(parameter, context)),
      symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)),
      symbolToNode: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToNode(symbol, context, meaning))
    };
    function getTypeFromTypeNode2(context, node, noMappedTypes) {
      const type = getTypeFromTypeNodeWithoutContext(node);
      if (!context.mapper) return type;
      const mappedType = instantiateType(type, context.mapper);
      return noMappedTypes && mappedType !== type ? void 0 : mappedType;
    }
    function setTextRange2(context, range, location) {
      if (!nodeIsSynthesized(range) || !(range.flags & 16 /* Synthesized */) || !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(range))) {
        range = factory.cloneNode(range);
      }
      if (range === location) return range;
      if (!location) {
        return range;
      }
      let original = range.original;
      while (original && original !== location) {
        original = original.original;
      }
      if (!original) {
        setOriginalNode(range, location);
      }
      if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(getOriginalNode(location))) {
        return setTextRange(range, location);
      }
      return range;
    }
    function symbolToNode(symbol, context, meaning) {
      if (context.internalFlags & 1 /* WriteComputedProps */) {
        if (symbol.valueDeclaration) {
          const name = getNameOfDeclaration(symbol.valueDeclaration);
          if (name && isComputedPropertyName(name)) return name;
        }
        const nameType = getSymbolLinks(symbol).nameType;
        if (nameType && nameType.flags & (1024 /* EnumLiteral */ | 8192 /* UniqueESSymbol */)) {
          context.enclosingDeclaration = nameType.symbol.valueDeclaration;
          return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning));
        }
      }
      return symbolToExpression(symbol, context, meaning);
    }
    function withContext(enclosingDeclaration, flags, internalFlags, tracker, cb) {
      const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : (internalFlags || 0 /* None */) & 4 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0;
      const context = {
        enclosingDeclaration,
        enclosingFile: enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration),
        flags: flags || 0 /* None */,
        internalFlags: internalFlags || 0 /* None */,
        tracker: void 0,
        encounteredError: false,
        suppressReportInferenceFallback: false,
        reportedDiagnostic: false,
        visitedTypes: void 0,
        symbolDepth: void 0,
        inferTypeParameters: void 0,
        approximateLength: 0,
        trackedSymbols: void 0,
        bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)),
        truncating: false,
        usedSymbolNames: void 0,
        remappedSymbolNames: void 0,
        remappedSymbolReferences: void 0,
        reverseMappedStack: void 0,
        mustCreateTypeParameterSymbolList: true,
        typeParameterSymbolList: void 0,
        mustCreateTypeParametersNamesLookups: true,
        typeParameterNames: void 0,
        typeParameterNamesByText: void 0,
        typeParameterNamesByTextNextNameCount: void 0,
        enclosingSymbolTypes: /* @__PURE__ */ new Map(),
        mapper: void 0
      };
      context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost);
      const resultingNode = cb(context);
      if (context.truncating && context.flags & 1 /* NoTruncation */) {
        context.tracker.reportTruncationError();
      }
      return context.encounteredError ? void 0 : resultingNode;
    }
    function addSymbolTypeToContext(context, symbol, type) {
      const id = getSymbolId(symbol);
      const oldType = context.enclosingSymbolTypes.get(id);
      context.enclosingSymbolTypes.set(id, type);
      return restore;
      function restore() {
        if (oldType) {
          context.enclosingSymbolTypes.set(id, oldType);
        } else {
          context.enclosingSymbolTypes.delete(id);
        }
      }
    }
    function saveRestoreFlags(context) {
      const flags = context.flags;
      const internalFlags = context.internalFlags;
      return restore;
      function restore() {
        context.flags = flags;
        context.internalFlags = internalFlags;
      }
    }
    function checkTruncationLength(context) {
      if (context.truncating) return context.truncating;
      return context.truncating = context.approximateLength > (context.flags & 1 /* NoTruncation */ ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength);
    }
    function typeToTypeNodeHelper(type, context) {
      const restoreFlags = saveRestoreFlags(context);
      const typeNode = typeToTypeNodeWorker(type, context);
      restoreFlags();
      return typeNode;
    }
    function typeToTypeNodeWorker(type, context) {
      var _a, _b;
      if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
        cancellationToken.throwIfCancellationRequested();
      }
      const inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
      context.flags &= ~8388608 /* InTypeAlias */;
      if (!type) {
        if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
          context.encounteredError = true;
          return void 0;
        }
        context.approximateLength += 3;
        return factory.createKeywordTypeNode(133 /* AnyKeyword */);
      }
      if (!(context.flags & 536870912 /* NoTypeReduction */)) {
        type = getReducedType(type);
      }
      if (type.flags & 1 /* Any */) {
        if (type.aliasSymbol) {
          return factory.createTypeReferenceNode(symbolToEntityNameNode(type.aliasSymbol), mapToTypeNodes(type.aliasTypeArguments, context));
        }
        if (type === unresolvedType) {
          return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "unresolved");
        }
        context.approximateLength += 3;
        return factory.createKeywordTypeNode(type === intrinsicMarkerType ? 141 /* IntrinsicKeyword */ : 133 /* AnyKeyword */);
      }
      if (type.flags & 2 /* Unknown */) {
        return factory.createKeywordTypeNode(159 /* UnknownKeyword */);
      }
      if (type.flags & 4 /* String */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(154 /* StringKeyword */);
      }
      if (type.flags & 8 /* Number */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(150 /* NumberKeyword */);
      }
      if (type.flags & 64 /* BigInt */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(163 /* BigIntKeyword */);
      }
      if (type.flags & 16 /* Boolean */ && !type.aliasSymbol) {
        context.approximateLength += 7;
        return factory.createKeywordTypeNode(136 /* BooleanKeyword */);
      }
      if (type.flags & 1056 /* EnumLike */) {
        if (type.symbol.flags & 8 /* EnumMember */) {
          const parentSymbol = getParentOfSymbol(type.symbol);
          const parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
          if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
            return parentName;
          }
          const memberName = symbolName(type.symbol);
          if (isIdentifierText(memberName, 1 /* ES5 */)) {
            return appendReferenceToType(
              parentName,
              factory.createTypeReferenceNode(
                memberName,
                /*typeArguments*/
                void 0
              )
            );
          }
          if (isImportTypeNode(parentName)) {
            parentName.isTypeOf = true;
            return factory.createIndexedAccessTypeNode(parentName, factory.createLiteralTypeNode(factory.createStringLiteral(memberName)));
          } else if (isTypeReferenceNode(parentName)) {
            return factory.createIndexedAccessTypeNode(factory.createTypeQueryNode(parentName.typeName), factory.createLiteralTypeNode(factory.createStringLiteral(memberName)));
          } else {
            return Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
          }
        }
        return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
      }
      if (type.flags & 128 /* StringLiteral */) {
        context.approximateLength += type.value.length + 2;
        return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
      }
      if (type.flags & 256 /* NumberLiteral */) {
        const value = type.value;
        context.approximateLength += ("" + value).length;
        return factory.createLiteralTypeNode(value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-value)) : factory.createNumericLiteral(value));
      }
      if (type.flags & 2048 /* BigIntLiteral */) {
        context.approximateLength += pseudoBigIntToString(type.value).length + 1;
        return factory.createLiteralTypeNode(factory.createBigIntLiteral(type.value));
      }
      if (type.flags & 512 /* BooleanLiteral */) {
        context.approximateLength += type.intrinsicName.length;
        return factory.createLiteralTypeNode(type.intrinsicName === "true" ? factory.createTrue() : factory.createFalse());
      }
      if (type.flags & 8192 /* UniqueESSymbol */) {
        if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
          if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
            context.approximateLength += 6;
            return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
          }
          if (context.tracker.reportInaccessibleUniqueSymbolError) {
            context.tracker.reportInaccessibleUniqueSymbolError();
          }
        }
        context.approximateLength += 13;
        return factory.createTypeOperatorNode(158 /* UniqueKeyword */, factory.createKeywordTypeNode(155 /* SymbolKeyword */));
      }
      if (type.flags & 16384 /* Void */) {
        context.approximateLength += 4;
        return factory.createKeywordTypeNode(116 /* VoidKeyword */);
      }
      if (type.flags & 32768 /* Undefined */) {
        context.approximateLength += 9;
        return factory.createKeywordTypeNode(157 /* UndefinedKeyword */);
      }
      if (type.flags & 65536 /* Null */) {
        context.approximateLength += 4;
        return factory.createLiteralTypeNode(factory.createNull());
      }
      if (type.flags & 131072 /* Never */) {
        context.approximateLength += 5;
        return factory.createKeywordTypeNode(146 /* NeverKeyword */);
      }
      if (type.flags & 4096 /* ESSymbol */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(155 /* SymbolKeyword */);
      }
      if (type.flags & 67108864 /* NonPrimitive */) {
        context.approximateLength += 6;
        return factory.createKeywordTypeNode(151 /* ObjectKeyword */);
      }
      if (isThisTypeParameter(type)) {
        if (context.flags & 4194304 /* InObjectTypeLiteral */) {
          if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
            context.encounteredError = true;
          }
          (_b = (_a = context.tracker).reportInaccessibleThisError) == null ? void 0 : _b.call(_a);
        }
        context.approximateLength += 4;
        return factory.createThisTypeNode();
      }
      if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
        const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
        if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes);
        if (length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) {
          return factory.createArrayTypeNode(typeArgumentNodes[0]);
        }
        return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
      }
      const objectFlags = getObjectFlags(type);
      if (objectFlags & 4 /* Reference */) {
        Debug.assert(!!(type.flags & 524288 /* Object */));
        return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
      }
      if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
        if (type.flags & 262144 /* TypeParameter */ && contains(context.inferTypeParameters, type)) {
          context.approximateLength += symbolName(type.symbol).length + 6;
          let constraintNode;
          const constraint = getConstraintOfTypeParameter(type);
          if (constraint) {
            const inferredConstraint = getInferredTypeParameterConstraint(
              type,
              /*omitTypeReferences*/
              true
            );
            if (!(inferredConstraint && isTypeIdenticalTo(constraint, inferredConstraint))) {
              context.approximateLength += 9;
              constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
            }
          }
          return factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, constraintNode));
        }
        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type.flags & 262144 /* TypeParameter */) {
          const name2 = typeParameterToName(type, context);
          context.approximateLength += idText(name2).length;
          return factory.createTypeReferenceNode(
            factory.createIdentifier(idText(name2)),
            /*typeArguments*/
            void 0
          );
        }
        if (type.symbol) {
          return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
        }
        const name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? (type === markerSubTypeForCheck ? "sub-" : "super-") + symbolName(varianceTypeParameter.symbol) : "?";
        return factory.createTypeReferenceNode(
          factory.createIdentifier(name),
          /*typeArguments*/
          void 0
        );
      }
      if (type.flags & 1048576 /* Union */ && type.origin) {
        type = type.origin;
      }
      if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
        const types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
        if (length(types) === 1) {
          return typeToTypeNodeHelper(types[0], context);
        }
        const typeNodes = mapToTypeNodes(
          types,
          context,
          /*isBareList*/
          true
        );
        if (typeNodes && typeNodes.length > 0) {
          return type.flags & 1048576 /* Union */ ? factory.createUnionTypeNode(typeNodes) : factory.createIntersectionTypeNode(typeNodes);
        } else {
          if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
            context.encounteredError = true;
          }
          return void 0;
        }
      }
      if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
        Debug.assert(!!(type.flags & 524288 /* Object */));
        return createAnonymousTypeNode(type);
      }
      if (type.flags & 4194304 /* Index */) {
        const indexedType = type.type;
        context.approximateLength += 6;
        const indexTypeNode = typeToTypeNodeHelper(indexedType, context);
        return factory.createTypeOperatorNode(143 /* KeyOfKeyword */, indexTypeNode);
      }
      if (type.flags & 134217728 /* TemplateLiteral */) {
        const texts = type.texts;
        const types = type.types;
        const templateHead = factory.createTemplateHead(texts[0]);
        const templateSpans = factory.createNodeArray(
          map(types, (t, i) => factory.createTemplateLiteralTypeSpan(
            typeToTypeNodeHelper(t, context),
            (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1])
          ))
        );
        context.approximateLength += 2;
        return factory.createTemplateLiteralType(templateHead, templateSpans);
      }
      if (type.flags & 268435456 /* StringMapping */) {
        const typeNode = typeToTypeNodeHelper(type.type, context);
        return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]);
      }
      if (type.flags & 8388608 /* IndexedAccess */) {
        const objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
        const indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
        context.approximateLength += 2;
        return factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
      }
      if (type.flags & 16777216 /* Conditional */) {
        return visitAndTransformType(type, (type2) => conditionalTypeToTypeNode(type2));
      }
      if (type.flags & 33554432 /* Substitution */) {
        const typeNode = typeToTypeNodeHelper(type.baseType, context);
        const noInferSymbol = isNoInferType(type) && getGlobalTypeSymbol(
          "NoInfer",
          /*reportErrors*/
          false
        );
        return noInferSymbol ? symbolToTypeNode(noInferSymbol, context, 788968 /* Type */, [typeNode]) : typeNode;
      }
      return Debug.fail("Should be unreachable.");
      function conditionalTypeToTypeNode(type2) {
        const checkTypeNode = typeToTypeNodeHelper(type2.checkType, context);
        context.approximateLength += 15;
        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type2.root.isDistributive && !(type2.checkType.flags & 262144 /* TypeParameter */)) {
          const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T"));
          const name = typeParameterToName(newParam, context);
          const newTypeVariable = factory.createTypeReferenceNode(name);
          context.approximateLength += 37;
          const newMapper = prependTypeMapping(type2.root.checkType, newParam, type2.mapper);
          const saveInferTypeParameters2 = context.inferTypeParameters;
          context.inferTypeParameters = type2.root.inferTypeParameters;
          const extendsTypeNode2 = typeToTypeNodeHelper(instantiateType(type2.root.extendsType, newMapper), context);
          context.inferTypeParameters = saveInferTypeParameters2;
          const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.trueType), newMapper));
          const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.falseType), newMapper));
          return factory.createConditionalTypeNode(
            checkTypeNode,
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName)
            )),
            factory.createConditionalTypeNode(
              factory.createTypeReferenceNode(factory.cloneNode(name)),
              typeToTypeNodeHelper(type2.checkType, context),
              factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2),
              factory.createKeywordTypeNode(146 /* NeverKeyword */)
            ),
            factory.createKeywordTypeNode(146 /* NeverKeyword */)
          );
        }
        const saveInferTypeParameters = context.inferTypeParameters;
        context.inferTypeParameters = type2.root.inferTypeParameters;
        const extendsTypeNode = typeToTypeNodeHelper(type2.extendsType, context);
        context.inferTypeParameters = saveInferTypeParameters;
        const trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type2));
        const falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type2));
        return factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
      }
      function typeToTypeNodeOrCircularityElision(type2) {
        var _a2, _b2, _c;
        if (type2.flags & 1048576 /* Union */) {
          if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(getTypeId(type2))) {
            if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
              context.encounteredError = true;
              (_c = (_b2 = context.tracker) == null ? void 0 : _b2.reportCyclicStructureError) == null ? void 0 : _c.call(_b2);
            }
            return createElidedInformationPlaceholder(context);
          }
          return visitAndTransformType(type2, (type3) => typeToTypeNodeHelper(type3, context));
        }
        return typeToTypeNodeHelper(type2, context);
      }
      function isMappedTypeHomomorphic(type2) {
        return !!getHomomorphicTypeVariable(type2);
      }
      function isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) {
        return !!type2.target && isMappedTypeHomomorphic(type2.target) && !isMappedTypeHomomorphic(type2);
      }
      function createMappedTypeNodeFromType(type2) {
        var _a2;
        Debug.assert(!!(type2.flags & 524288 /* Object */));
        const readonlyToken = type2.declaration.readonlyToken ? factory.createToken(type2.declaration.readonlyToken.kind) : void 0;
        const questionToken = type2.declaration.questionToken ? factory.createToken(type2.declaration.questionToken.kind) : void 0;
        let appropriateConstraintTypeNode;
        let newTypeVariable;
        const needsModifierPreservingWrapper = !isMappedTypeWithKeyofConstraintDeclaration(type2) && !(getModifiersTypeFromMappedType(type2).flags & 2 /* Unknown */) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && !(getConstraintTypeFromMappedType(type2).flags & 262144 /* TypeParameter */ && ((_a2 = getConstraintOfTypeParameter(getConstraintTypeFromMappedType(type2))) == null ? void 0 : _a2.flags) & 4194304 /* Index */);
        if (isMappedTypeWithKeyofConstraintDeclaration(type2)) {
          if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
            const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T"));
            const name = typeParameterToName(newParam, context);
            newTypeVariable = factory.createTypeReferenceNode(name);
          }
          appropriateConstraintTypeNode = factory.createTypeOperatorNode(143 /* KeyOfKeyword */, newTypeVariable || typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context));
        } else if (needsModifierPreservingWrapper) {
          const newParam = createTypeParameter(createSymbol(262144 /* TypeParameter */, "T"));
          const name = typeParameterToName(newParam, context);
          newTypeVariable = factory.createTypeReferenceNode(name);
          appropriateConstraintTypeNode = newTypeVariable;
        } else {
          appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context);
        }
        const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type2), context, appropriateConstraintTypeNode);
        const nameTypeNode = type2.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type2), context) : void 0;
        const templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type2), !!(getMappedTypeModifiers(type2) & 4 /* IncludeOptional */)), context);
        const mappedTypeNode = factory.createMappedTypeNode(
          readonlyToken,
          typeParameterNode,
          nameTypeNode,
          questionToken,
          templateTypeNode,
          /*members*/
          void 0
        );
        context.approximateLength += 10;
        const result = setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
        if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
          const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode2(context, type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper);
          return factory.createConditionalTypeNode(
            typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context),
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName),
              originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context)
            )),
            result,
            factory.createKeywordTypeNode(146 /* NeverKeyword */)
          );
        } else if (needsModifierPreservingWrapper) {
          return factory.createConditionalTypeNode(
            typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context),
            factory.createInferTypeNode(factory.createTypeParameterDeclaration(
              /*modifiers*/
              void 0,
              factory.cloneNode(newTypeVariable.typeName),
              factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context))
            )),
            result,
            factory.createKeywordTypeNode(146 /* NeverKeyword */)
          );
        }
        return result;
      }
      function createAnonymousTypeNode(type2) {
        var _a2, _b2;
        const typeId = type2.id;
        const symbol = type2.symbol;
        if (symbol) {
          const isInstantiationExpressionType = !!(getObjectFlags(type2) & 8388608 /* InstantiationExpressionType */);
          if (isInstantiationExpressionType) {
            const instantiationExpressionType = type2;
            const existing = instantiationExpressionType.node;
            if (isTypeQueryNode(existing) && getTypeFromTypeNode2(context, existing) === type2) {
              const typeNode = syntacticNodeBuilder.tryReuseExistingTypeNode(context, existing);
              if (typeNode) {
                return typeNode;
              }
            }
            if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(typeId)) {
              return createElidedInformationPlaceholder(context);
            }
            return visitAndTransformType(type2, createTypeNodeFromObjectType);
          }
          const isInstanceType = isClassInstanceSide(type2) ? 788968 /* Type */ : 111551 /* Value */;
          if (isJSConstructor(symbol.valueDeclaration)) {
            return symbolToTypeNode(symbol, context, isInstanceType);
          } else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(
            symbol,
            context.enclosingDeclaration,
            isInstanceType,
            /*shouldComputeAliasesToMakeVisible*/
            false
          ).accessibility !== 0 /* Accessible */)) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) {
            return symbolToTypeNode(symbol, context, isInstanceType);
          } else if ((_b2 = context.visitedTypes) == null ? void 0 : _b2.has(typeId)) {
            const typeAlias = getTypeAliasForTypeLiteral(type2);
            if (typeAlias) {
              return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
            } else {
              return createElidedInformationPlaceholder(context);
            }
          } else {
            return visitAndTransformType(type2, createTypeNodeFromObjectType);
          }
        } else {
          return createTypeNodeFromObjectType(type2);
        }
        function shouldWriteTypeOfFunctionSymbol() {
          var _a3;
          const isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
          some(symbol.declarations, (declaration) => isStatic(declaration));
          const isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol
          forEach(symbol.declarations, (declaration) => declaration.parent.kind === 307 /* SourceFile */ || declaration.parent.kind === 268 /* ModuleBlock */));
          if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
            return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId))) && // it is type of the symbol uses itself recursively
            (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration));
          }
        }
      }
      function visitAndTransformType(type2, transform) {
        var _a2, _b2, _c;
        const typeId = type2.id;
        const isConstructorObject = getObjectFlags(type2) & 16 /* Anonymous */ && type2.symbol && type2.symbol.flags & 32 /* Class */;
        const id = getObjectFlags(type2) & 4 /* Reference */ && type2.node ? "N" + getNodeId(type2.node) : type2.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0;
        if (!context.visitedTypes) {
          context.visitedTypes = /* @__PURE__ */ new Set();
        }
        if (id && !context.symbolDepth) {
          context.symbolDepth = /* @__PURE__ */ new Map();
        }
        const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration);
        const key = `${getTypeId(type2)}|${context.flags}|${context.internalFlags}`;
        if (links) {
          links.serializedTypes || (links.serializedTypes = /* @__PURE__ */ new Map());
        }
        const cachedResult = (_a2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a2.get(key);
        if (cachedResult) {
          (_b2 = cachedResult.trackedSymbols) == null ? void 0 : _b2.forEach(
            ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(
              symbol,
              enclosingDeclaration,
              meaning
            )
          );
          if (cachedResult.truncating) {
            context.truncating = true;
          }
          context.approximateLength += cachedResult.addedLength;
          return deepCloneOrReuseNode(cachedResult.node);
        }
        let depth;
        if (id) {
          depth = context.symbolDepth.get(id) || 0;
          if (depth > 10) {
            return createElidedInformationPlaceholder(context);
          }
          context.symbolDepth.set(id, depth + 1);
        }
        context.visitedTypes.add(typeId);
        const prevTrackedSymbols = context.trackedSymbols;
        context.trackedSymbols = void 0;
        const startLength = context.approximateLength;
        const result = transform(type2);
        const addedLength = context.approximateLength - startLength;
        if (!context.reportedDiagnostic && !context.encounteredError) {
          (_c = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _c.set(key, {
            node: result,
            truncating: context.truncating,
            addedLength,
            trackedSymbols: context.trackedSymbols
          });
        }
        context.visitedTypes.delete(typeId);
        if (id) {
          context.symbolDepth.set(id, depth);
        }
        context.trackedSymbols = prevTrackedSymbols;
        return result;
        function deepCloneOrReuseNode(node) {
          if (!nodeIsSynthesized(node) && getParseTreeNode(node) === node) {
            return node;
          }
          return setTextRange2(context, factory.cloneNode(visitEachChild(
            node,
            deepCloneOrReuseNode,
            /*context*/
            void 0,
            deepCloneOrReuseNodes,
            deepCloneOrReuseNode
          )), node);
        }
        function deepCloneOrReuseNodes(nodes, visitor, test, start, count) {
          if (nodes && nodes.length === 0) {
            return setTextRange(factory.createNodeArray(
              /*elements*/
              void 0,
              nodes.hasTrailingComma
            ), nodes);
          }
          return visitNodes2(nodes, visitor, test, start, count);
        }
      }
      function createTypeNodeFromObjectType(type2) {
        if (isGenericMappedType(type2) || type2.containsError) {
          return createMappedTypeNodeFromType(type2);
        }
        const resolved = resolveStructuredTypeMembers(type2);
        if (!resolved.properties.length && !resolved.indexInfos.length) {
          if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
            context.approximateLength += 2;
            return setEmitFlags(factory.createTypeLiteralNode(
              /*members*/
              void 0
            ), 1 /* SingleLine */);
          }
          if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
            const signature = resolved.callSignatures[0];
            const signatureNode = signatureToSignatureDeclarationHelper(signature, 184 /* FunctionType */, context);
            return signatureNode;
          }
          if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
            const signature = resolved.constructSignatures[0];
            const signatureNode = signatureToSignatureDeclarationHelper(signature, 185 /* ConstructorType */, context);
            return signatureNode;
          }
        }
        const abstractSignatures = filter(resolved.constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */));
        if (some(abstractSignatures)) {
          const types = map(abstractSignatures, (s) => getOrCreateTypeFromSignature(s));
          const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + // exclude `prototype` when writing a class expression as a type literal, as per
          // the logic in `createTypeNodesFromResolvedType`.
          (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ? countWhere(resolved.properties, (p) => !(p.flags & 4194304 /* Prototype */)) : length(resolved.properties));
          if (typeElementCount) {
            types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved));
          }
          return typeToTypeNodeHelper(getIntersectionType(types), context);
        }
        const restoreFlags = saveRestoreFlags(context);
        context.flags |= 4194304 /* InObjectTypeLiteral */;
        const members = createTypeNodesFromResolvedType(resolved);
        restoreFlags();
        const typeLiteralNode = factory.createTypeLiteralNode(members);
        context.approximateLength += 2;
        setEmitFlags(typeLiteralNode, context.flags & 1024 /* MultilineObjectLiterals */ ? 0 : 1 /* SingleLine */);
        return typeLiteralNode;
      }
      function typeReferenceToTypeNode(type2) {
        let typeArguments = getTypeArguments(type2);
        if (type2.target === globalArrayType || type2.target === globalReadonlyArrayType) {
          if (context.flags & 2 /* WriteArrayAsGenericType */) {
            const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
            return factory.createTypeReferenceNode(type2.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
          }
          const elementType = typeToTypeNodeHelper(typeArguments[0], context);
          const arrayType = factory.createArrayTypeNode(elementType);
          return type2.target === globalArrayType ? arrayType : factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, arrayType);
        } else if (type2.target.objectFlags & 8 /* Tuple */) {
          typeArguments = sameMap(typeArguments, (t, i) => removeMissingType(t, !!(type2.target.elementFlags[i] & 2 /* Optional */)));
          if (typeArguments.length > 0) {
            const arity = getTypeReferenceArity(type2);
            const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
            if (tupleConstituentNodes) {
              const { labeledElementDeclarations } = type2.target;
              for (let i = 0; i < tupleConstituentNodes.length; i++) {
                const flags = type2.target.elementFlags[i];
                const labeledElementDeclaration = labeledElementDeclarations == null ? void 0 : labeledElementDeclarations[i];
                if (labeledElementDeclaration) {
                  tupleConstituentNodes[i] = factory.createNamedTupleMember(
                    flags & 12 /* Variable */ ? factory.createToken(26 /* DotDotDotToken */) : void 0,
                    factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))),
                    flags & 2 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                    flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]
                  );
                } else {
                  tupleConstituentNodes[i] = flags & 12 /* Variable */ ? factory.createRestTypeNode(flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & 2 /* Optional */ ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i];
                }
              }
              const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
              return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
            }
          }
          if (context.encounteredError || context.flags & 524288 /* AllowEmptyTuple */) {
            const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode([]), 1 /* SingleLine */);
            return type2.target.readonly ? factory.createTypeOperatorNode(148 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
          }
          context.encounteredError = true;
          return void 0;
        } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type2.symbol.valueDeclaration && isClassLike(type2.symbol.valueDeclaration) && !isValueSymbolAccessible(type2.symbol, context.enclosingDeclaration)) {
          return createAnonymousTypeNode(type2);
        } else {
          const outerTypeParameters = type2.target.outerTypeParameters;
          let i = 0;
          let resultType;
          if (outerTypeParameters) {
            const length2 = outerTypeParameters.length;
            while (i < length2) {
              const start = i;
              const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
              do {
                i++;
              } while (i < length2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
              if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) {
                const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
                const restoreFlags2 = saveRestoreFlags(context);
                context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
                const ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
                restoreFlags2();
                resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
              }
            }
          }
          let typeArgumentNodes;
          if (typeArguments.length > 0) {
            let typeParameterCount = 0;
            if (type2.target.typeParameters) {
              typeParameterCount = Math.min(type2.target.typeParameters.length, typeArguments.length);
              if (isReferenceToType(type2, getGlobalIterableType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalIterableIteratorType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalAsyncIterableType(
                /*reportErrors*/
                false
              )) || isReferenceToType(type2, getGlobalAsyncIterableIteratorType(
                /*reportErrors*/
                false
              ))) {
                if (!type2.node || !isTypeReferenceNode(type2.node) || !type2.node.typeArguments || type2.node.typeArguments.length < typeParameterCount) {
                  while (typeParameterCount > 0) {
                    const typeArgument = typeArguments[typeParameterCount - 1];
                    const typeParameter = type2.target.typeParameters[typeParameterCount - 1];
                    const defaultType = getDefaultFromTypeParameter(typeParameter);
                    if (!defaultType || !isTypeIdenticalTo(typeArgument, defaultType)) {
                      break;
                    }
                    typeParameterCount--;
                  }
                }
              }
            }
            typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
          }
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
          const finalRef = symbolToTypeNode(type2.symbol, context, 788968 /* Type */, typeArgumentNodes);
          restoreFlags();
          return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
        }
      }
      function appendReferenceToType(root, ref) {
        if (isImportTypeNode(root)) {
          let typeArguments = root.typeArguments;
          let qualifier = root.qualifier;
          if (qualifier) {
            if (isIdentifier(qualifier)) {
              if (typeArguments !== getIdentifierTypeArguments(qualifier)) {
                qualifier = setIdentifierTypeArguments(factory.cloneNode(qualifier), typeArguments);
              }
            } else {
              if (typeArguments !== getIdentifierTypeArguments(qualifier.right)) {
                qualifier = factory.updateQualifiedName(qualifier, qualifier.left, setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments));
              }
            }
          }
          typeArguments = ref.typeArguments;
          const ids = getAccessStack(ref);
          for (const id of ids) {
            qualifier = qualifier ? factory.createQualifiedName(qualifier, id) : id;
          }
          return factory.updateImportTypeNode(
            root,
            root.argument,
            root.attributes,
            qualifier,
            typeArguments,
            root.isTypeOf
          );
        } else {
          let typeArguments = root.typeArguments;
          let typeName = root.typeName;
          if (isIdentifier(typeName)) {
            if (typeArguments !== getIdentifierTypeArguments(typeName)) {
              typeName = setIdentifierTypeArguments(factory.cloneNode(typeName), typeArguments);
            }
          } else {
            if (typeArguments !== getIdentifierTypeArguments(typeName.right)) {
              typeName = factory.updateQualifiedName(typeName, typeName.left, setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments));
            }
          }
          typeArguments = ref.typeArguments;
          const ids = getAccessStack(ref);
          for (const id of ids) {
            typeName = factory.createQualifiedName(typeName, id);
          }
          return factory.updateTypeReferenceNode(
            root,
            typeName,
            typeArguments
          );
        }
      }
      function getAccessStack(ref) {
        let state = ref.typeName;
        const ids = [];
        while (!isIdentifier(state)) {
          ids.unshift(state.right);
          state = state.left;
        }
        ids.unshift(state);
        return ids;
      }
      function createTypeNodesFromResolvedType(resolvedType) {
        if (checkTruncationLength(context)) {
          if (context.flags & 1 /* NoTruncation */) {
            return [addSyntheticTrailingComment(factory.createNotEmittedTypeElement(), 3 /* MultiLineCommentTrivia */, "elided")];
          }
          return [factory.createPropertySignature(
            /*modifiers*/
            void 0,
            "...",
            /*questionToken*/
            void 0,
            /*type*/
            void 0
          )];
        }
        const typeElements = [];
        for (const signature of resolvedType.callSignatures) {
          typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */, context));
        }
        for (const signature of resolvedType.constructSignatures) {
          if (signature.flags & 4 /* Abstract */) continue;
          typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */, context));
        }
        for (const info of resolvedType.indexInfos) {
          typeElements.push(indexInfoToIndexSignatureDeclarationHelper(info, context, resolvedType.objectFlags & 1024 /* ReverseMapped */ ? createElidedInformationPlaceholder(context) : void 0));
        }
        const properties = resolvedType.properties;
        if (!properties) {
          return typeElements;
        }
        let i = 0;
        for (const propertySymbol of properties) {
          i++;
          if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
            if (propertySymbol.flags & 4194304 /* Prototype */) {
              continue;
            }
            if (getDeclarationModifierFlagsFromSymbol(propertySymbol) & (2 /* Private */ | 4 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
              context.tracker.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(propertySymbol.escapedName));
            }
          }
          if (checkTruncationLength(context) && i + 2 < properties.length - 1) {
            if (context.flags & 1 /* NoTruncation */) {
              const typeElement = typeElements.pop();
              typeElements.push(addSyntheticTrailingComment(typeElement, 3 /* MultiLineCommentTrivia */, `... ${properties.length - i} more elided ...`));
            } else {
              typeElements.push(factory.createPropertySignature(
                /*modifiers*/
                void 0,
                `... ${properties.length - i} more ...`,
                /*questionToken*/
                void 0,
                /*type*/
                void 0
              ));
            }
            addPropertyToElementList(properties[properties.length - 1], context, typeElements);
            break;
          }
          addPropertyToElementList(propertySymbol, context, typeElements);
        }
        return typeElements.length ? typeElements : void 0;
      }
    }
    function createElidedInformationPlaceholder(context) {
      context.approximateLength += 3;
      if (!(context.flags & 1 /* NoTruncation */)) {
        return factory.createTypeReferenceNode(
          factory.createIdentifier("..."),
          /*typeArguments*/
          void 0
        );
      }
      return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided");
    }
    function shouldUsePlaceholderForProperty(propertySymbol, context) {
      var _a;
      const depth = 3;
      return !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) && (contains(context.reverseMappedStack, propertySymbol) || ((_a = context.reverseMappedStack) == null ? void 0 : _a[0]) && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & 16 /* Anonymous */) || isDeeplyNestedReverseMappedTypeProperty());
      function isDeeplyNestedReverseMappedTypeProperty() {
        var _a2;
        if ((((_a2 = context.reverseMappedStack) == null ? void 0 : _a2.length) ?? 0) < depth) {
          return false;
        }
        for (let i = 0; i < depth; i++) {
          const prop = context.reverseMappedStack[context.reverseMappedStack.length - 1 - i];
          if (prop.links.mappedType.symbol !== propertySymbol.links.mappedType.symbol) {
            return false;
          }
        }
        return true;
      }
    }
    function addPropertyToElementList(propertySymbol, context, typeElements) {
      var _a;
      const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
      const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getNonMissingTypeOfSymbol(propertySymbol);
      const saveEnclosingDeclaration = context.enclosingDeclaration;
      context.enclosingDeclaration = void 0;
      if (context.tracker.canTrackSymbol && isLateBoundName(propertySymbol.escapedName)) {
        if (propertySymbol.declarations) {
          const decl = first(propertySymbol.declarations);
          if (hasLateBindableName(decl)) {
            if (isBinaryExpression(decl)) {
              const name = getNameOfDeclaration(decl);
              if (name && isElementAccessExpression(name) && isPropertyAccessEntityNameExpression(name.argumentExpression)) {
                trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
              }
            } else {
              trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
            }
          }
        } else {
          context.tracker.reportNonSerializableProperty(symbolToString(propertySymbol));
        }
      }
      context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) == null ? void 0 : _a[0]) || saveEnclosingDeclaration;
      const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
      context.enclosingDeclaration = saveEnclosingDeclaration;
      context.approximateLength += symbolName(propertySymbol).length + 1;
      if (propertySymbol.flags & 98304 /* Accessor */) {
        const writeType = getWriteTypeOfSymbol(propertySymbol);
        if (propertyType !== writeType && !isErrorType(propertyType) && !isErrorType(writeType)) {
          const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */);
          const getterSignature = getSignatureFromDeclaration(getterDeclaration);
          typeElements.push(
            setCommentRange2(
              context,
              signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { name: propertyName }),
              getterDeclaration
            )
          );
          const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */);
          const setterSignature = getSignatureFromDeclaration(setterDeclaration);
          typeElements.push(
            setCommentRange2(
              context,
              signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { name: propertyName }),
              setterDeclaration
            )
          );
          return;
        }
      }
      const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0;
      if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
        const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & 32768 /* Undefined */)), 0 /* Call */);
        for (const signature of signatures) {
          const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
          typeElements.push(preserveCommentsOn(methodDeclaration, signature.declaration || propertySymbol.valueDeclaration));
        }
        if (signatures.length || !optionalToken) {
          return;
        }
      }
      let propertyTypeNode;
      if (shouldUsePlaceholderForProperty(propertySymbol, context)) {
        propertyTypeNode = createElidedInformationPlaceholder(context);
      } else {
        if (propertyIsReverseMapped) {
          context.reverseMappedStack || (context.reverseMappedStack = []);
          context.reverseMappedStack.push(propertySymbol);
        }
        propertyTypeNode = propertyType ? serializeTypeForDeclaration(
          context,
          /*declaration*/
          void 0,
          propertyType,
          propertySymbol
        ) : factory.createKeywordTypeNode(133 /* AnyKeyword */);
        if (propertyIsReverseMapped) {
          context.reverseMappedStack.pop();
        }
      }
      const modifiers = isReadonlySymbol(propertySymbol) ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0;
      if (modifiers) {
        context.approximateLength += 9;
      }
      const propertySignature = factory.createPropertySignature(
        modifiers,
        propertyName,
        optionalToken,
        propertyTypeNode
      );
      typeElements.push(preserveCommentsOn(propertySignature, propertySymbol.valueDeclaration));
      function preserveCommentsOn(node, range) {
        var _a2;
        const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d) => d.kind === 348 /* JSDocPropertyTag */);
        if (jsdocPropertyTag) {
          const commentText = getTextOfJSDocComment(jsdocPropertyTag.comment);
          if (commentText) {
            setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
          }
        } else if (range) {
          setCommentRange2(context, node, range);
        }
        return node;
      }
    }
    function setCommentRange2(context, node, range) {
      if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(range)) {
        return setCommentRange(node, range);
      }
      return node;
    }
    function mapToTypeNodes(types, context, isBareList) {
      if (some(types)) {
        if (checkTruncationLength(context)) {
          if (!isBareList) {
            return [
              context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided") : factory.createTypeReferenceNode(
                "...",
                /*typeArguments*/
                void 0
              )
            ];
          } else if (types.length > 2) {
            return [
              typeToTypeNodeHelper(types[0], context),
              context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - 2} more elided ...`) : factory.createTypeReferenceNode(
                `... ${types.length - 2} more ...`,
                /*typeArguments*/
                void 0
              ),
              typeToTypeNodeHelper(types[types.length - 1], context)
            ];
          }
        }
        const mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
        const seenNames = mayHaveNameCollisions ? createMultiMap() : void 0;
        const result = [];
        let i = 0;
        for (const type of types) {
          i++;
          if (checkTruncationLength(context) && i + 2 < types.length - 1) {
            result.push(
              context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - i} more elided ...`) : factory.createTypeReferenceNode(
                `... ${types.length - i} more ...`,
                /*typeArguments*/
                void 0
              )
            );
            const typeNode2 = typeToTypeNodeHelper(types[types.length - 1], context);
            if (typeNode2) {
              result.push(typeNode2);
            }
            break;
          }
          context.approximateLength += 2;
          const typeNode = typeToTypeNodeHelper(type, context);
          if (typeNode) {
            result.push(typeNode);
            if (seenNames && isIdentifierTypeReference(typeNode)) {
              seenNames.add(typeNode.typeName.escapedText, [type, result.length - 1]);
            }
          }
        }
        if (seenNames) {
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= 64 /* UseFullyQualifiedType */;
          seenNames.forEach((types2) => {
            if (!arrayIsHomogeneous(types2, ([a], [b]) => typesAreSameReference(a, b))) {
              for (const [type, resultIndex] of types2) {
                result[resultIndex] = typeToTypeNodeHelper(type, context);
              }
            }
          });
          restoreFlags();
        }
        return result;
      }
    }
    function typesAreSameReference(a, b) {
      return a === b || !!a.symbol && a.symbol === b.symbol || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
    }
    function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) {
      const name = getNameFromIndexInfo(indexInfo) || "x";
      const indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context);
      const indexingParameter = factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        indexerTypeNode,
        /*initializer*/
        void 0
      );
      if (!typeNode) {
        typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
      }
      if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
        context.encounteredError = true;
      }
      context.approximateLength += name.length + 4;
      return factory.createIndexSignature(
        indexInfo.isReadonly ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0,
        [indexingParameter],
        typeNode
      );
    }
    function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
      var _a;
      let typeParameters;
      let typeArguments;
      const expandedParams = getExpandedParameters(
        signature,
        /*skipUnionExpanding*/
        true
      )[0];
      const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters, signature.parameters, signature.mapper);
      context.approximateLength += 3;
      if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
        typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context));
      } else {
        typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context));
      }
      const restoreFlags = saveRestoreFlags(context);
      context.flags &= ~256 /* SuppressAnyReturnType */;
      const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */));
      const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context);
      if (thisParameter) {
        parameters.unshift(thisParameter);
      }
      restoreFlags();
      const returnTypeNode = serializeReturnTypeForSignature(context, signature);
      let modifiers = options == null ? void 0 : options.modifiers;
      if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */) {
        const flags = modifiersToFlags(modifiers);
        modifiers = factory.createModifiersFromModifierFlags(flags | 64 /* Abstract */);
      }
      const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration(
        modifiers,
        /*asteriskToken*/
        void 0,
        (options == null ? void 0 : options.name) ?? factory.createIdentifier(""),
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === 176 /* Constructor */ ? factory.createConstructorDeclaration(
        modifiers,
        parameters,
        /*body*/
        void 0
      ) : kind === 177 /* GetAccessor */ ? factory.createGetAccessorDeclaration(
        modifiers,
        (options == null ? void 0 : options.name) ?? factory.createIdentifier(""),
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === 178 /* SetAccessor */ ? factory.createSetAccessorDeclaration(
        modifiers,
        (options == null ? void 0 : options.name) ?? factory.createIdentifier(""),
        parameters,
        /*body*/
        void 0
      ) : kind === 181 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 317 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 184 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 185 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 262 /* FunctionDeclaration */ ? factory.createFunctionDeclaration(
        modifiers,
        /*asteriskToken*/
        void 0,
        (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""),
        typeParameters,
        parameters,
        returnTypeNode,
        /*body*/
        void 0
      ) : kind === 218 /* FunctionExpression */ ? factory.createFunctionExpression(
        modifiers,
        /*asteriskToken*/
        void 0,
        (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""),
        typeParameters,
        parameters,
        returnTypeNode,
        factory.createBlock([])
      ) : kind === 219 /* ArrowFunction */ ? factory.createArrowFunction(
        modifiers,
        typeParameters,
        parameters,
        returnTypeNode,
        /*equalsGreaterThanToken*/
        void 0,
        factory.createBlock([])
      ) : Debug.assertNever(kind);
      if (typeArguments) {
        node.typeArguments = factory.createNodeArray(typeArguments);
      }
      if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 323 /* JSDocSignature */ && signature.declaration.parent.kind === 339 /* JSDocOverloadTag */) {
        const comment = getTextOfNode(
          signature.declaration.parent.parent,
          /*includeTrivia*/
          true
        ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n");
        addSyntheticLeadingComment(
          node,
          3 /* MultiLineCommentTrivia */,
          comment,
          /*hasTrailingNewLine*/
          true
        );
      }
      cleanup == null ? void 0 : cleanup();
      return node;
    }
    function createRecoveryBoundary(context) {
      if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
        cancellationToken.throwIfCancellationRequested();
      }
      let trackedSymbols;
      let unreportedErrors;
      let hadError = false;
      const oldTracker = context.tracker;
      const oldTrackedSymbols = context.trackedSymbols;
      context.trackedSymbols = void 0;
      const oldEncounteredError = context.encounteredError;
      context.tracker = new SymbolTrackerImpl(context, {
        ...oldTracker.inner,
        reportCyclicStructureError() {
          markError(() => oldTracker.reportCyclicStructureError());
        },
        reportInaccessibleThisError() {
          markError(() => oldTracker.reportInaccessibleThisError());
        },
        reportInaccessibleUniqueSymbolError() {
          markError(() => oldTracker.reportInaccessibleUniqueSymbolError());
        },
        reportLikelyUnsafeImportRequiredError(specifier) {
          markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier));
        },
        reportNonSerializableProperty(name) {
          markError(() => oldTracker.reportNonSerializableProperty(name));
        },
        reportPrivateInBaseOfClassExpression(propertyName) {
          markError(() => oldTracker.reportPrivateInBaseOfClassExpression(propertyName));
        },
        trackSymbol(sym, decl, meaning) {
          (trackedSymbols ?? (trackedSymbols = [])).push([sym, decl, meaning]);
          return false;
        },
        moduleResolverHost: context.tracker.moduleResolverHost
      }, context.tracker.moduleResolverHost);
      return {
        startRecoveryScope,
        finalizeBoundary,
        markError,
        hadError: () => hadError
      };
      function markError(unreportedError) {
        hadError = true;
        if (unreportedError) {
          (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError);
        }
      }
      function startRecoveryScope() {
        const trackedSymbolsTop = (trackedSymbols == null ? void 0 : trackedSymbols.length) ?? 0;
        const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0;
        return () => {
          hadError = false;
          if (trackedSymbols) {
            trackedSymbols.length = trackedSymbolsTop;
          }
          if (unreportedErrors) {
            unreportedErrors.length = unreportedErrorsTop;
          }
        };
      }
      function finalizeBoundary() {
        context.tracker = oldTracker;
        context.trackedSymbols = oldTrackedSymbols;
        context.encounteredError = oldEncounteredError;
        unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn());
        if (hadError) {
          return false;
        }
        trackedSymbols == null ? void 0 : trackedSymbols.forEach(
          ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(
            symbol,
            enclosingDeclaration,
            meaning
          )
        );
        return true;
      }
    }
    function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) {
      const cleanupContext = cloneNodeBuilderContext(context);
      let cleanupParams;
      let cleanupTypeParams;
      const oldEnclosingDecl = context.enclosingDeclaration;
      const oldMapper = context.mapper;
      if (mapper) {
        context.mapper = mapper;
      }
      if (context.enclosingDeclaration && declaration) {
        let pushFakeScope2 = function(kind, addAll) {
          Debug.assert(context.enclosingDeclaration);
          let existingFakeScope;
          if (getNodeLinks(context.enclosingDeclaration).fakeScopeForSignatureDeclaration === kind) {
            existingFakeScope = context.enclosingDeclaration;
          } else if (context.enclosingDeclaration.parent && getNodeLinks(context.enclosingDeclaration.parent).fakeScopeForSignatureDeclaration === kind) {
            existingFakeScope = context.enclosingDeclaration.parent;
          }
          Debug.assertOptionalNode(existingFakeScope, isBlock);
          const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable();
          let newLocals;
          let oldLocals;
          addAll((name, symbol) => {
            if (existingFakeScope) {
              const oldSymbol = locals.get(name);
              if (!oldSymbol) {
                newLocals = append(newLocals, name);
              } else {
                oldLocals = append(oldLocals, { name, oldSymbol });
              }
            }
            locals.set(name, symbol);
          });
          if (!existingFakeScope) {
            const fakeScope = factory.createBlock(emptyArray);
            getNodeLinks(fakeScope).fakeScopeForSignatureDeclaration = kind;
            fakeScope.locals = locals;
            setParent(fakeScope, context.enclosingDeclaration);
            context.enclosingDeclaration = fakeScope;
          } else {
            return function undo() {
              forEach(newLocals, (s) => locals.delete(s));
              forEach(oldLocals, (s) => locals.set(s.name, s.oldSymbol));
            };
          }
        };
        var pushFakeScope = pushFakeScope2;
        cleanupParams = !some(expandedParams) ? void 0 : pushFakeScope2(
          "params",
          (add) => {
            if (!expandedParams) return;
            for (let pIndex = 0; pIndex < expandedParams.length; pIndex++) {
              const param = expandedParams[pIndex];
              const originalParam = originalParameters == null ? void 0 : originalParameters[pIndex];
              if (originalParameters && originalParam !== param) {
                add(param.escapedName, unknownSymbol);
                if (originalParam) {
                  add(originalParam.escapedName, unknownSymbol);
                }
              } else if (!forEach(param.declarations, (d) => {
                if (isParameter(d) && isBindingPattern(d.name)) {
                  bindPattern(d.name);
                  return true;
                }
                return void 0;
                function bindPattern(p) {
                  forEach(p.elements, (e) => {
                    switch (e.kind) {
                      case 232 /* OmittedExpression */:
                        return;
                      case 208 /* BindingElement */:
                        return bindElement(e);
                      default:
                        return Debug.assertNever(e);
                    }
                  });
                }
                function bindElement(e) {
                  if (isBindingPattern(e.name)) {
                    return bindPattern(e.name);
                  }
                  const symbol = getSymbolOfDeclaration(e);
                  add(symbol.escapedName, symbol);
                }
              })) {
                add(param.escapedName, param);
              }
            }
          }
        );
        if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && some(typeParameters)) {
          cleanupTypeParams = pushFakeScope2(
            "typeParams",
            (add) => {
              for (const typeParam of typeParameters ?? emptyArray) {
                const typeParamName = typeParameterToName(typeParam, context).escapedText;
                add(typeParamName, typeParam.symbol);
              }
            }
          );
        }
      }
      return () => {
        cleanupParams == null ? void 0 : cleanupParams();
        cleanupTypeParams == null ? void 0 : cleanupTypeParams();
        cleanupContext();
        context.enclosingDeclaration = oldEnclosingDecl;
        context.mapper = oldMapper;
      };
    }
    function tryGetThisParameterDeclaration(signature, context) {
      if (signature.thisParameter) {
        return symbolToParameterDeclaration(signature.thisParameter, context);
      }
      if (signature.declaration && isInJSFile(signature.declaration)) {
        const thisTag = getJSDocThisTag(signature.declaration);
        if (thisTag && thisTag.typeExpression) {
          return factory.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            "this",
            /*questionToken*/
            void 0,
            typeToTypeNodeHelper(getTypeFromTypeNode2(context, thisTag.typeExpression), context)
          );
        }
      }
    }
    function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
      const restoreFlags = saveRestoreFlags(context);
      context.flags &= ~512 /* WriteTypeParametersInQualifiedName */;
      const modifiers = factory.createModifiersFromModifierFlags(getTypeParameterModifiers(type));
      const name = typeParameterToName(type, context);
      const defaultParameter = getDefaultFromTypeParameter(type);
      const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
      restoreFlags();
      return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode);
    }
    function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) {
      return typeNode && getTypeFromTypeNode2(context, typeNode) === type && syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode) || typeToTypeNodeHelper(type, context);
    }
    function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) {
      const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context);
      return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
    }
    function typePredicateToTypePredicateNodeHelper(typePredicate, context) {
      const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0;
      const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode();
      const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
      return factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
    }
    function getEffectiveParameterDeclaration(parameterSymbol) {
      const parameterDeclaration = getDeclarationOfKind(parameterSymbol, 169 /* Parameter */);
      if (parameterDeclaration) {
        return parameterDeclaration;
      }
      if (!isTransientSymbol(parameterSymbol)) {
        return getDeclarationOfKind(parameterSymbol, 341 /* JSDocParameterTag */);
      }
    }
    function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
      const parameterDeclaration = getEffectiveParameterDeclaration(parameterSymbol);
      const parameterType = getTypeOfSymbol(parameterSymbol);
      const parameterTypeNode = serializeTypeForDeclaration(context, parameterDeclaration, parameterType, parameterSymbol);
      const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0;
      const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
      const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0;
      const name = parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context);
      const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
      const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0;
      const parameterNode = factory.createParameterDeclaration(
        modifiers,
        dotDotDotToken,
        name,
        questionToken,
        parameterTypeNode,
        /*initializer*/
        void 0
      );
      context.approximateLength += symbolName(parameterSymbol).length + 3;
      return parameterNode;
    }
    function parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context) {
      return parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 166 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol);
      function cloneBindingName(node) {
        return elideInitializerAndSetEmitFlags(node);
        function elideInitializerAndSetEmitFlags(node2) {
          if (context.tracker.canTrackSymbol && isComputedPropertyName(node2) && isLateBindableName(node2)) {
            trackComputedName(node2.expression, context.enclosingDeclaration, context);
          }
          let visited = visitEachChild(
            node2,
            elideInitializerAndSetEmitFlags,
            /*context*/
            void 0,
            /*nodesVisitor*/
            void 0,
            elideInitializerAndSetEmitFlags
          );
          if (isBindingElement(visited)) {
            visited = factory.updateBindingElement(
              visited,
              visited.dotDotDotToken,
              visited.propertyName,
              visited.name,
              /*initializer*/
              void 0
            );
          }
          if (!nodeIsSynthesized(visited)) {
            visited = factory.cloneNode(visited);
          }
          return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
        }
      }
    }
    function trackComputedName(accessExpression, enclosingDeclaration, context) {
      if (!context.tracker.canTrackSymbol) return;
      const firstIdentifier = getFirstIdentifier(accessExpression);
      const name = resolveName(
        firstIdentifier,
        firstIdentifier.escapedText,
        111551 /* Value */ | 1048576 /* ExportValue */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (name) {
        context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
      }
    }
    function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
      context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning);
      return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
    }
    function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
      let chain;
      const isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
      if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.internalFlags & 4 /* DoNotIncludeSymbolChain */)) {
        chain = Debug.checkDefined(getSymbolChain(
          symbol,
          meaning,
          /*endOfChain*/
          true
        ));
        Debug.assert(chain && chain.length > 0);
      } else {
        chain = [symbol];
      }
      return chain;
      function getSymbolChain(symbol2, meaning2, endOfChain) {
        let accessibleSymbolChain = getAccessibleSymbolChain(symbol2, context.enclosingDeclaration, meaning2, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
        let parentSpecifiers;
        if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning2 : getQualifiedLeftMeaning(meaning2))) {
          const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol2, context.enclosingDeclaration, meaning2);
          if (length(parents)) {
            parentSpecifiers = parents.map(
              (symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0
            );
            const indices = parents.map((_, i) => i);
            indices.sort(sortByBestName);
            const sortedParents = indices.map((i) => parents[i]);
            for (const parent of sortedParents) {
              const parentChain = getSymbolChain(
                parent,
                getQualifiedLeftMeaning(meaning2),
                /*endOfChain*/
                false
              );
              if (parentChain) {
                if (parent.exports && parent.exports.get("export=" /* ExportEquals */) && getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol2)) {
                  accessibleSymbolChain = parentChain;
                  break;
                }
                accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol2) || symbol2]);
                break;
              }
            }
          }
        }
        if (accessibleSymbolChain) {
          return accessibleSymbolChain;
        }
        if (
          // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
          endOfChain || // If a parent symbol is an anonymous type, don't write it.
          !(symbol2.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))
        ) {
          if (!endOfChain && !yieldModuleSymbol && !!forEach(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
            return;
          }
          return [symbol2];
        }
        function sortByBestName(a, b) {
          const specifierA = parentSpecifiers[a];
          const specifierB = parentSpecifiers[b];
          if (specifierA && specifierB) {
            const isBRelative = pathIsRelative(specifierB);
            if (pathIsRelative(specifierA) === isBRelative) {
              return countPathComponents(specifierA) - countPathComponents(specifierB);
            }
            if (isBRelative) {
              return -1;
            }
            return 1;
          }
          return 0;
        }
      }
    }
    function typeParametersToTypeParameterDeclarations(symbol, context) {
      let typeParameterNodes;
      const targetSymbol = getTargetSymbol(symbol);
      if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
        typeParameterNodes = factory.createNodeArray(map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), (tp) => typeParameterToDeclaration(tp, context)));
      }
      return typeParameterNodes;
    }
    function lookupTypeParameterNodes(chain, index, context) {
      var _a;
      Debug.assert(chain && 0 <= index && index < chain.length);
      const symbol = chain[index];
      const symbolId = getSymbolId(symbol);
      if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) {
        return void 0;
      }
      if (context.mustCreateTypeParameterSymbolList) {
        context.mustCreateTypeParameterSymbolList = false;
        context.typeParameterSymbolList = new Set(context.typeParameterSymbolList);
      }
      context.typeParameterSymbolList.add(symbolId);
      let typeParameterNodes;
      if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) {
        const parentSymbol = symbol;
        const nextSymbol = chain[index + 1];
        if (getCheckFlags(nextSymbol) & 1 /* Instantiated */) {
          const params = getTypeParametersOfClassOrInterface(
            parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol
          );
          typeParameterNodes = mapToTypeNodes(map(params, (t) => getMappedType(t, nextSymbol.links.mapper)), context);
        } else {
          typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
        }
      }
      return typeParameterNodes;
    }
    function getTopmostIndexedAccessType(top) {
      if (isIndexedAccessTypeNode(top.objectType)) {
        return getTopmostIndexedAccessType(top.objectType);
      }
      return top;
    }
    function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) {
      let file = getDeclarationOfKind(symbol, 307 /* SourceFile */);
      if (!file) {
        const equivalentFileSymbol = firstDefined(symbol.declarations, (d) => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol));
        if (equivalentFileSymbol) {
          file = getDeclarationOfKind(equivalentFileSymbol, 307 /* SourceFile */);
        }
      }
      if (file && file.moduleName !== void 0) {
        return file.moduleName;
      }
      if (!file) {
        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
          return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
        }
      }
      if (!context.enclosingFile || !context.tracker.moduleResolverHost) {
        if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
          return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
        }
        return getSourceFileOfNode(getNonAugmentationDeclaration(symbol)).fileName;
      }
      const enclosingDeclaration = getOriginalNode(context.enclosingDeclaration);
      const originalModuleSpecifier = canHaveModuleSpecifier(enclosingDeclaration) ? tryGetModuleSpecifierFromDeclaration(enclosingDeclaration) : void 0;
      const contextFile = context.enclosingFile;
      const resolutionMode = overrideImportMode || originalModuleSpecifier && host.getModeForUsageLocation(contextFile, originalModuleSpecifier) || contextFile && host.getDefaultResolutionModeForFile(contextFile);
      const cacheKey = createModeAwareCacheKey(contextFile.path, resolutionMode);
      const links = getSymbolLinks(symbol);
      let specifier = links.specifierCache && links.specifierCache.get(cacheKey);
      if (!specifier) {
        const isBundle2 = !!compilerOptions.outFile;
        const { moduleResolverHost } = context.tracker;
        const specifierCompilerOptions = isBundle2 ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() } : compilerOptions;
        specifier = first(getModuleSpecifiers(
          symbol,
          checker,
          specifierCompilerOptions,
          contextFile,
          moduleResolverHost,
          {
            importModuleSpecifierPreference: isBundle2 ? "non-relative" : "project-relative",
            importModuleSpecifierEnding: isBundle2 ? "minimal" : resolutionMode === 99 /* ESNext */ ? "js" : void 0
          },
          { overrideImportMode }
        ));
        links.specifierCache ?? (links.specifierCache = /* @__PURE__ */ new Map());
        links.specifierCache.set(cacheKey, specifier);
      }
      return specifier;
    }
    function symbolToEntityNameNode(symbol) {
      const identifier = factory.createIdentifier(unescapeLeadingUnderscores(symbol.escapedName));
      return symbol.parent ? factory.createQualifiedName(symbolToEntityNameNode(symbol.parent), identifier) : identifier;
    }
    function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
      const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */));
      const isTypeOf = meaning === 111551 /* Value */;
      if (some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
        const nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : void 0;
        const typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
        const contextFile = getSourceFileOfNode(getOriginalNode(context.enclosingDeclaration));
        const targetFile = getSourceFileOfModule(chain[0]);
        let specifier;
        let attributes;
        if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) {
          if ((targetFile == null ? void 0 : targetFile.impliedNodeFormat) === 99 /* ESNext */ && targetFile.impliedNodeFormat !== (contextFile == null ? void 0 : contextFile.impliedNodeFormat)) {
            specifier = getSpecifierForModuleSymbol(chain[0], context, 99 /* ESNext */);
            attributes = factory.createImportAttributes(
              factory.createNodeArray([
                factory.createImportAttribute(
                  factory.createStringLiteral("resolution-mode"),
                  factory.createStringLiteral("import")
                )
              ])
            );
          }
        }
        if (!specifier) {
          specifier = getSpecifierForModuleSymbol(chain[0], context);
        }
        if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && getEmitModuleResolutionKind(compilerOptions) !== 1 /* Classic */ && specifier.includes("/node_modules/")) {
          const oldSpecifier = specifier;
          if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) {
            const swappedMode = (contextFile == null ? void 0 : contextFile.impliedNodeFormat) === 99 /* ESNext */ ? 1 /* CommonJS */ : 99 /* ESNext */;
            specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode);
            if (specifier.includes("/node_modules/")) {
              specifier = oldSpecifier;
            } else {
              attributes = factory.createImportAttributes(
                factory.createNodeArray([
                  factory.createImportAttribute(
                    factory.createStringLiteral("resolution-mode"),
                    factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require")
                  )
                ])
              );
            }
          }
          if (!attributes) {
            context.encounteredError = true;
            if (context.tracker.reportLikelyUnsafeImportRequiredError) {
              context.tracker.reportLikelyUnsafeImportRequiredError(oldSpecifier);
            }
          }
        }
        const lit = factory.createLiteralTypeNode(factory.createStringLiteral(specifier));
        context.approximateLength += specifier.length + 10;
        if (!nonRootParts || isEntityName(nonRootParts)) {
          if (nonRootParts) {
            const lastId = isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
            setIdentifierTypeArguments(
              lastId,
              /*typeArguments*/
              void 0
            );
          }
          return factory.createImportTypeNode(lit, attributes, nonRootParts, typeParameterNodes, isTypeOf);
        } else {
          const splitNode = getTopmostIndexedAccessType(nonRootParts);
          const qualifier = splitNode.objectType.typeName;
          return factory.createIndexedAccessTypeNode(factory.createImportTypeNode(lit, attributes, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
        }
      }
      const entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
      if (isIndexedAccessTypeNode(entityName)) {
        return entityName;
      }
      if (isTypeOf) {
        return factory.createTypeQueryNode(entityName);
      } else {
        const lastId = isIdentifier(entityName) ? entityName : entityName.right;
        const lastTypeArgs = getIdentifierTypeArguments(lastId);
        setIdentifierTypeArguments(
          lastId,
          /*typeArguments*/
          void 0
        );
        return factory.createTypeReferenceNode(entityName, lastTypeArgs);
      }
      function createAccessFromSymbolChain(chain2, index, stopper) {
        const typeParameterNodes = index === chain2.length - 1 ? overrideTypeArguments : lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        const parent = chain2[index - 1];
        let symbolName2;
        if (index === 0) {
          context.flags |= 16777216 /* InInitialEntityName */;
          symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
          context.approximateLength += (symbolName2 ? symbolName2.length : 0) + 1;
          context.flags ^= 16777216 /* InInitialEntityName */;
        } else {
          if (parent && getExportsOfSymbol(parent)) {
            const exports2 = getExportsOfSymbol(parent);
            forEachEntry(exports2, (ex, name) => {
              if (getSymbolIfSameReference(ex, symbol2) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
                symbolName2 = unescapeLeadingUnderscores(name);
                return true;
              }
            });
          }
        }
        if (symbolName2 === void 0) {
          const name = firstDefined(symbol2.declarations, getNameOfDeclaration);
          if (name && isComputedPropertyName(name) && isEntityName(name.expression)) {
            const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
            if (isEntityName(LHS)) {
              return factory.createIndexedAccessTypeNode(factory.createParenthesizedType(factory.createTypeQueryNode(LHS)), factory.createTypeQueryNode(name.expression));
            }
            return LHS;
          }
          symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        }
        context.approximateLength += symbolName2.length + 1;
        if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol2.escapedName) && getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol2.escapedName), symbol2)) {
          const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
          if (isIndexedAccessTypeNode(LHS)) {
            return factory.createIndexedAccessTypeNode(LHS, factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2)));
          } else {
            return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2)));
          }
        }
        const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
        if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
        identifier.symbol = symbol2;
        if (index > stopper) {
          const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper);
          if (!isEntityName(LHS)) {
            return Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
          }
          return factory.createQualifiedName(LHS, identifier);
        }
        return identifier;
      }
    }
    function typeParameterShadowsOtherTypeParameterInScope(escapedName, context, type) {
      const result = resolveName(
        context.enclosingDeclaration,
        escapedName,
        788968 /* Type */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
      if (result && result.flags & 262144 /* TypeParameter */) {
        return result !== type.symbol;
      }
      return false;
    }
    function typeParameterToName(type, context) {
      var _a, _b, _c, _d;
      if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
        const cached = context.typeParameterNames.get(getTypeId(type));
        if (cached) {
          return cached;
        }
      }
      let result = symbolToName(
        type.symbol,
        context,
        788968 /* Type */,
        /*expectsIdentifier*/
        true
      );
      if (!(result.kind & 80 /* Identifier */)) {
        return factory.createIdentifier("(Missing type parameter)");
      }
      const decl = (_b = (_a = type.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0];
      if (decl && isTypeParameterDeclaration(decl)) {
        result = setTextRange2(context, result, decl.name);
      }
      if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
        const rawtext = result.escapedText;
        let i = ((_c = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _c.get(rawtext)) || 0;
        let text = rawtext;
        while (((_d = context.typeParameterNamesByText) == null ? void 0 : _d.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) {
          i++;
          text = `${rawtext}_${i}`;
        }
        if (text !== rawtext) {
          const typeArguments = getIdentifierTypeArguments(result);
          result = factory.createIdentifier(text);
          setIdentifierTypeArguments(result, typeArguments);
        }
        if (context.mustCreateTypeParametersNamesLookups) {
          context.mustCreateTypeParametersNamesLookups = false;
          context.typeParameterNames = new Map(context.typeParameterNames);
          context.typeParameterNamesByTextNextNameCount = new Map(context.typeParameterNamesByTextNextNameCount);
          context.typeParameterNamesByText = new Set(context.typeParameterNamesByText);
        }
        context.typeParameterNamesByTextNextNameCount.set(rawtext, i);
        context.typeParameterNames.set(getTypeId(type), result);
        context.typeParameterNamesByText.add(text);
      }
      return result;
    }
    function symbolToName(symbol, context, meaning, expectsIdentifier) {
      const chain = lookupSymbolChain(symbol, context, meaning);
      if (expectsIdentifier && chain.length !== 1 && !context.encounteredError && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) {
        context.encounteredError = true;
      }
      return createEntityNameFromSymbolChain(chain, chain.length - 1);
      function createEntityNameFromSymbolChain(chain2, index) {
        const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        if (index === 0) {
          context.flags |= 16777216 /* InInitialEntityName */;
        }
        const symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        if (index === 0) {
          context.flags ^= 16777216 /* InInitialEntityName */;
        }
        const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
        if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
        identifier.symbol = symbol2;
        return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier;
      }
    }
    function symbolToExpression(symbol, context, meaning) {
      const chain = lookupSymbolChain(symbol, context, meaning);
      return createExpressionFromSymbolChain(chain, chain.length - 1);
      function createExpressionFromSymbolChain(chain2, index) {
        const typeParameterNodes = lookupTypeParameterNodes(chain2, index, context);
        const symbol2 = chain2[index];
        if (index === 0) {
          context.flags |= 16777216 /* InInitialEntityName */;
        }
        let symbolName2 = getNameOfSymbolAsWritten(symbol2, context);
        if (index === 0) {
          context.flags ^= 16777216 /* InInitialEntityName */;
        }
        let firstChar = symbolName2.charCodeAt(0);
        if (isSingleOrDoubleQuote(firstChar) && some(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
          return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context));
        }
        if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) {
          const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
          if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
          identifier.symbol = symbol2;
          return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier;
        } else {
          if (firstChar === 91 /* openBracket */) {
            symbolName2 = symbolName2.substring(1, symbolName2.length - 1);
            firstChar = symbolName2.charCodeAt(0);
          }
          let expression;
          if (isSingleOrDoubleQuote(firstChar) && !(symbol2.flags & 8 /* EnumMember */)) {
            expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, (s) => s.substring(1)), firstChar === 39 /* singleQuote */);
          } else if ("" + +symbolName2 === symbolName2) {
            expression = factory.createNumericLiteral(+symbolName2);
          }
          if (!expression) {
            const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */);
            if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes));
            identifier.symbol = symbol2;
            expression = identifier;
          }
          return factory.createElementAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), expression);
        }
      }
    }
    function isStringNamed(d) {
      const name = getNameOfDeclaration(d);
      if (!name) {
        return false;
      }
      if (isComputedPropertyName(name)) {
        const type = checkExpression(name.expression);
        return !!(type.flags & 402653316 /* StringLike */);
      }
      if (isElementAccessExpression(name)) {
        const type = checkExpression(name.argumentExpression);
        return !!(type.flags & 402653316 /* StringLike */);
      }
      return isStringLiteral(name);
    }
    function isSingleQuotedStringNamed(d) {
      const name = getNameOfDeclaration(d);
      return !!(name && isStringLiteral(name) && (name.singleQuote || !nodeIsSynthesized(name) && startsWith(getTextOfNode(
        name,
        /*includeTrivia*/
        false
      ), "'")));
    }
    function getPropertyNameNodeForSymbol(symbol, context) {
      const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed);
      const singleQuote = !!length(symbol.declarations) && every(symbol.declarations, isSingleQuotedStringNamed);
      const isMethod = !!(symbol.flags & 8192 /* Method */);
      const fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod);
      if (fromNameType) {
        return fromNameType;
      }
      const rawName = unescapeLeadingUnderscores(symbol.escapedName);
      return createPropertyNameNodeForIdentifierOrLiteral(rawName, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod);
    }
    function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote, stringNamed, isMethod) {
      const nameType = getSymbolLinks(symbol).nameType;
      if (nameType) {
        if (nameType.flags & 384 /* StringOrNumberLiteral */) {
          const name = "" + nameType.value;
          if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && (stringNamed || !isNumericLiteralName(name))) {
            return factory.createStringLiteral(name, !!singleQuote);
          }
          if (isNumericLiteralName(name) && startsWith(name, "-")) {
            return factory.createComputedPropertyName(factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-name)));
          }
          return createPropertyNameNodeForIdentifierOrLiteral(name, getEmitScriptTarget(compilerOptions), singleQuote, stringNamed, isMethod);
        }
        if (nameType.flags & 8192 /* UniqueESSymbol */) {
          return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
        }
      }
    }
    function cloneNodeBuilderContext(context) {
      const oldMustCreateTypeParameterSymbolList = context.mustCreateTypeParameterSymbolList;
      const oldMustCreateTypeParametersNamesLookups = context.mustCreateTypeParametersNamesLookups;
      context.mustCreateTypeParameterSymbolList = true;
      context.mustCreateTypeParametersNamesLookups = true;
      const oldTypeParameterNames = context.typeParameterNames;
      const oldTypeParameterNamesByText = context.typeParameterNamesByText;
      const oldTypeParameterNamesByTextNextNameCount = context.typeParameterNamesByTextNextNameCount;
      const oldTypeParameterSymbolList = context.typeParameterSymbolList;
      return () => {
        context.typeParameterNames = oldTypeParameterNames;
        context.typeParameterNamesByText = oldTypeParameterNamesByText;
        context.typeParameterNamesByTextNextNameCount = oldTypeParameterNamesByTextNextNameCount;
        context.typeParameterSymbolList = oldTypeParameterSymbolList;
        context.mustCreateTypeParameterSymbolList = oldMustCreateTypeParameterSymbolList;
        context.mustCreateTypeParametersNamesLookups = oldMustCreateTypeParametersNamesLookups;
      };
    }
    function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
      return symbol.declarations && find(symbol.declarations, (s) => !!getNonlocalEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration)));
    }
    function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
      if (!(getObjectFlags(type) & 4 /* Reference */)) return true;
      if (!isTypeReferenceNode(existing)) return true;
      void getTypeFromTypeReference(existing);
      const symbol = getNodeLinks(existing).resolvedSymbol;
      const existingTarget = symbol && getDeclaredTypeOfSymbol(symbol);
      if (!existingTarget || existingTarget !== type.target) return true;
      return length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
    }
    function getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration) {
      while (getNodeLinks(enclosingDeclaration).fakeScopeForSignatureDeclaration) {
        enclosingDeclaration = enclosingDeclaration.parent;
      }
      return enclosingDeclaration;
    }
    function serializeInferredTypeForDeclaration(symbol, context, type) {
      if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile))) {
        context.flags |= 1048576 /* AllowUniqueESSymbolType */;
      }
      const result = typeToTypeNodeHelper(type, context);
      return result;
    }
    function serializeTypeForDeclaration(context, declaration, type, symbol) {
      var _a;
      let result;
      const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration);
      const decl = declaration ?? symbol.valueDeclaration ?? getDeclarationWithTypeAnnotation(symbol) ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]);
      if (decl) {
        if (isAccessor(decl)) {
          result = syntacticNodeBuilder.serializeTypeOfAccessor(decl, symbol, context);
        } else if (hasInferredType(decl) && !nodeIsSynthesized(decl) && !(getObjectFlags(type) & 196608 /* RequiresWidening */)) {
          const restore = addSymbolTypeToContext(context, symbol, type);
          result = syntacticNodeBuilder.serializeTypeOfDeclaration(decl, symbol, context);
          restore();
        }
      }
      if (!result) {
        if (addUndefinedForParameter) {
          type = getOptionalType(type);
        }
        result = serializeInferredTypeForDeclaration(symbol, context, type);
      }
      return result ?? factory.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) {
      if (typeFromTypeNode === type) {
        return true;
      }
      if (!annotatedDeclaration) {
        return false;
      }
      if ((isPropertySignature(annotatedDeclaration) || isPropertyDeclaration(annotatedDeclaration)) && annotatedDeclaration.questionToken) {
        return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode;
      }
      if (isParameter(annotatedDeclaration) && hasEffectiveQuestionToken(annotatedDeclaration)) {
        return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode;
      }
      return false;
    }
    function serializeReturnTypeForSignature(context, signature) {
      const suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
      const restoreFlags = saveRestoreFlags(context);
      if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */;
      let returnTypeNode;
      const returnType = getReturnTypeOfSignature(signature);
      if (!(suppressAny && isTypeAny(returnType))) {
        if (signature.declaration && !nodeIsSynthesized(signature.declaration)) {
          const declarationSymbol = getSymbolOfDeclaration(signature.declaration);
          const restore = addSymbolTypeToContext(context, declarationSymbol, returnType);
          returnTypeNode = syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, declarationSymbol, context);
          restore();
        }
        if (!returnTypeNode) {
          returnTypeNode = serializeInferredReturnTypeForSignature(context, signature, returnType);
        }
      }
      if (!returnTypeNode && !suppressAny) {
        returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */);
      }
      restoreFlags();
      return returnTypeNode;
    }
    function serializeInferredReturnTypeForSignature(context, signature, returnType) {
      const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback;
      context.suppressReportInferenceFallback = true;
      const typePredicate = getTypePredicateOfSignature(signature);
      const returnTypeNode = typePredicate ? typePredicateToTypePredicateNodeHelper(context.mapper ? instantiateTypePredicate(typePredicate, context.mapper) : typePredicate, context) : typeToTypeNodeHelper(returnType, context);
      context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback;
      return returnTypeNode;
    }
    function trackExistingEntityName(node, context, enclosingDeclaration = context.enclosingDeclaration) {
      let introducesError = false;
      const leftmost = getFirstIdentifier(node);
      if (isInJSFile(node) && (isExportsIdentifier(leftmost) || isModuleExportsAccessExpression(leftmost.parent) || isQualifiedName(leftmost.parent) && isModuleIdentifier(leftmost.parent.left) && isExportsIdentifier(leftmost.parent.right))) {
        introducesError = true;
        return { introducesError, node };
      }
      const meaning = getMeaningOfEntityNameReference(node);
      let sym;
      if (isThisIdentifier(leftmost)) {
        sym = getSymbolOfDeclaration(getThisContainer(
          leftmost,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        ));
        if (isSymbolAccessible(
          sym,
          leftmost,
          meaning,
          /*shouldComputeAliasesToMakeVisible*/
          false
        ).accessibility !== 0 /* Accessible */) {
          introducesError = true;
          context.tracker.reportInaccessibleThisError();
        }
        return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
      }
      sym = resolveEntityName(
        leftmost,
        meaning,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true
      );
      if (context.enclosingDeclaration && !(sym && sym.flags & 262144 /* TypeParameter */)) {
        sym = getExportSymbolOfValueSymbolIfExported(sym);
        const symAtLocation = resolveEntityName(
          leftmost,
          meaning,
          /*ignoreErrors*/
          true,
          /*dontResolveAlias*/
          true,
          context.enclosingDeclaration
        );
        if (
          // Check for unusable parameters symbols
          symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node
          symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it should point to the same reference
          symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym)
        ) {
          if (symAtLocation !== unknownSymbol) {
            context.tracker.reportInferenceFallback(node);
          }
          introducesError = true;
          return { introducesError, node, sym };
        } else {
          sym = symAtLocation;
        }
      }
      if (sym) {
        if (sym.flags & 1 /* FunctionScopedVariable */ && sym.valueDeclaration) {
          if (isPartOfParameterDeclaration(sym.valueDeclaration) || isJSDocParameterTag(sym.valueDeclaration)) {
            return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
          }
        }
        if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the current context if they are are resolvable
        !isDeclarationName(node) && isSymbolAccessible(
          sym,
          enclosingDeclaration,
          meaning,
          /*shouldComputeAliasesToMakeVisible*/
          false
        ).accessibility !== 0 /* Accessible */) {
          context.tracker.reportInferenceFallback(node);
          introducesError = true;
        } else {
          context.tracker.trackSymbol(sym, enclosingDeclaration, meaning);
        }
        return { introducesError, node: attachSymbolToLeftmostIdentifier(node) };
      }
      return { introducesError, node };
      function attachSymbolToLeftmostIdentifier(node2) {
        if (node2 === leftmost) {
          const type = getDeclaredTypeOfSymbol(sym);
          const name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(type, context) : factory.cloneNode(node2);
          name.symbol = sym;
          return setTextRange2(context, setEmitFlags(name, 16777216 /* NoAsciiEscaping */), node2);
        }
        const updated = visitEachChild(
          node2,
          (c) => attachSymbolToLeftmostIdentifier(c),
          /*context*/
          void 0
        );
        if (updated !== node2) {
          setTextRange2(context, updated, node2);
        }
        return updated;
      }
    }
    function serializeTypeName(context, node, isTypeOf, typeArguments) {
      const meaning = isTypeOf ? 111551 /* Value */ : 788968 /* Type */;
      const symbol = resolveEntityName(
        node,
        meaning,
        /*ignoreErrors*/
        true
      );
      if (!symbol) return void 0;
      const resolvedSymbol = symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol;
      if (isSymbolAccessible(
        symbol,
        context.enclosingDeclaration,
        meaning,
        /*shouldComputeAliasesToMakeVisible*/
        false
      ).accessibility !== 0 /* Accessible */) return void 0;
      return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments);
    }
    function canReuseTypeNode(context, existing) {
      const type = getTypeFromTypeNode2(
        context,
        existing,
        /*noMappedTypes*/
        true
      );
      if (!type) {
        return false;
      }
      if (isInJSFile(existing)) {
        if (isLiteralImportTypeNode(existing)) {
          void getTypeFromImportTypeNode(existing);
          const nodeSymbol = getNodeLinks(existing).resolvedSymbol;
          return !nodeSymbol || !// The import type resolved using jsdoc fallback logic
          (!existing.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic
          !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))));
        }
      }
      if (isTypeReferenceNode(existing)) {
        if (isConstTypeReference(existing)) return false;
        const symbol = getNodeLinks(existing).resolvedSymbol;
        if (!symbol) return false;
        if (symbol.flags & 262144 /* TypeParameter */) {
          const declaredType = getDeclaredTypeOfSymbol(symbol);
          return !(context.mapper && getMappedType(declaredType, context.mapper) !== declaredType);
        }
        if (isInJSDoc(existing)) {
          return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && !!(symbol.flags & 788968 /* Type */);
        }
      }
      if (isTypeOperatorNode(existing) && existing.operator === 158 /* UniqueKeyword */ && existing.type.kind === 155 /* SymbolKeyword */) {
        const effectiveEnclosingContext = context.enclosingDeclaration && getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration);
        return !!findAncestor(existing, (n) => n === effectiveEnclosingContext);
      }
      return true;
    }
    function serializeExistingTypeNode(context, typeNode, addUndefined) {
      const type = getTypeFromTypeNode2(context, typeNode);
      if (addUndefined && !someType(type, (t) => !!(t.flags & 32768 /* Undefined */)) && canReuseTypeNode(context, typeNode)) {
        const clone = syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode);
        if (clone) {
          return factory.createUnionTypeNode([clone, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
        }
      }
      return typeToTypeNodeHelper(type, context);
    }
    function symbolTableToDeclarationStatements(symbolTable, context) {
      var _a;
      const serializePropertySymbolForClass = makeSerializePropertySymbol(
        factory.createPropertyDeclaration,
        174 /* MethodDeclaration */,
        /*useAccessors*/
        true
      );
      const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(
        (mods, name, question, type) => factory.createPropertySignature(mods, name, question, type),
        173 /* MethodSignature */,
        /*useAccessors*/
        false
      );
      const enclosingDeclaration = context.enclosingDeclaration;
      let results = [];
      const visitedSymbols = /* @__PURE__ */ new Set();
      const deferredPrivatesStack = [];
      const oldcontext = context;
      context = {
        ...oldcontext,
        usedSymbolNames: new Set(oldcontext.usedSymbolNames),
        remappedSymbolNames: /* @__PURE__ */ new Map(),
        remappedSymbolReferences: new Map((_a = oldcontext.remappedSymbolReferences) == null ? void 0 : _a.entries()),
        tracker: void 0
      };
      const tracker = {
        ...oldcontext.tracker.inner,
        trackSymbol: (sym, decl, meaning) => {
          var _a2, _b;
          if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) return false;
          const accessibleResult = isSymbolAccessible(
            sym,
            decl,
            meaning,
            /*shouldComputeAliasesToMakeVisible*/
            false
          );
          if (accessibleResult.accessibility === 0 /* Accessible */) {
            const chain = lookupSymbolChainWorker(sym, context, meaning);
            if (!(sym.flags & 4 /* Property */)) {
              const root = chain[0];
              const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration);
              if (some(root.declarations, (d) => getSourceFileOfNode(d) === contextFile)) {
                includePrivateSymbol(root);
              }
            }
          } else if ((_b = oldcontext.tracker.inner) == null ? void 0 : _b.trackSymbol) {
            return oldcontext.tracker.inner.trackSymbol(sym, decl, meaning);
          }
          return false;
        }
      };
      context.tracker = new SymbolTrackerImpl(context, tracker, oldcontext.tracker.moduleResolverHost);
      forEachEntry(symbolTable, (symbol, name) => {
        const baseName = unescapeLeadingUnderscores(name);
        void getInternalSymbolName(symbol, baseName);
      });
      let addingDeclare = !context.bundled;
      const exportEquals = symbolTable.get("export=" /* ExportEquals */);
      if (exportEquals && symbolTable.size > 1 && exportEquals.flags & (2097152 /* Alias */ | 1536 /* Module */)) {
        symbolTable = createSymbolTable();
        symbolTable.set("export=" /* ExportEquals */, exportEquals);
      }
      visitSymbolTable(symbolTable);
      return mergeRedundantStatements(results);
      function isIdentifierAndNotUndefined(node) {
        return !!node && node.kind === 80 /* Identifier */;
      }
      function getNamesOfDeclaration(statement) {
        if (isVariableStatement(statement)) {
          return filter(map(statement.declarationList.declarations, getNameOfDeclaration), isIdentifierAndNotUndefined);
        }
        return filter([getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
      }
      function flattenExportAssignedNamespace(statements) {
        const exportAssignment = find(statements, isExportAssignment);
        const nsIndex = findIndex(statements, isModuleDeclaration);
        let ns = nsIndex !== -1 ? statements[nsIndex] : void 0;
        if (ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && ns.body && isModuleBlock(ns.body)) {
          const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & 32 /* Export */));
          const name = ns.name;
          let body = ns.body;
          if (length(excessExports)) {
            ns = factory.updateModuleDeclaration(
              ns,
              ns.modifiers,
              ns.name,
              body = factory.updateModuleBlock(
                body,
                factory.createNodeArray([
                  ...ns.body.statements,
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier(
                      /*isTypeOnly*/
                      false,
                      /*propertyName*/
                      void 0,
                      id
                    ))),
                    /*moduleSpecifier*/
                    void 0
                  )
                ])
              )
            );
            statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)];
          }
          if (!find(statements, (s) => s !== ns && nodeHasName(s, name))) {
            results = [];
            const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, 32 /* Export */) || isExportAssignment(s) || isExportDeclaration(s));
            forEach(body.statements, (s) => {
              addResult(s, mixinExportFlag ? 32 /* Export */ : 0 /* None */);
            });
            statements = [...filter(statements, (s) => s !== ns && s !== exportAssignment), ...results];
          }
        }
        return statements;
      }
      function mergeExportDeclarations(statements) {
        const exports2 = filter(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause));
        if (length(exports2) > 1) {
          const nonExports = filter(statements, (d) => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause);
          statements = [
            ...nonExports,
            factory.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory.createNamedExports(flatMap(exports2, (e) => cast(e.exportClause, isNamedExports).elements)),
              /*moduleSpecifier*/
              void 0
            )
          ];
        }
        const reexports = filter(statements, (d) => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause));
        if (length(reexports) > 1) {
          const groups = group(reexports, (decl) => isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">");
          if (groups.length !== reexports.length) {
            for (const group2 of groups) {
              if (group2.length > 1) {
                statements = [
                  ...filter(statements, (s) => !group2.includes(s)),
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports(flatMap(group2, (e) => cast(e.exportClause, isNamedExports).elements)),
                    group2[0].moduleSpecifier
                  )
                ];
              }
            }
          }
        }
        return statements;
      }
      function inlineExportModifiers(statements) {
        const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause));
        if (index >= 0) {
          const exportDecl = statements[index];
          const replacements = mapDefined(exportDecl.exportClause.elements, (e) => {
            if (!e.propertyName && e.name.kind !== 11 /* StringLiteral */) {
              const name = e.name;
              const indices = indicesOf(statements);
              const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], name));
              if (length(associatedIndices) && every(associatedIndices, (i) => canHaveExportModifier(statements[i]))) {
                for (const index2 of associatedIndices) {
                  statements[index2] = addExportModifier(statements[index2]);
                }
                return void 0;
              }
            }
            return e;
          });
          if (!length(replacements)) {
            orderedRemoveItemAt(statements, index);
          } else {
            statements[index] = factory.updateExportDeclaration(
              exportDecl,
              exportDecl.modifiers,
              exportDecl.isTypeOnly,
              factory.updateNamedExports(
                exportDecl.exportClause,
                replacements
              ),
              exportDecl.moduleSpecifier,
              exportDecl.attributes
            );
          }
        }
        return statements;
      }
      function mergeRedundantStatements(statements) {
        statements = flattenExportAssignedNamespace(statements);
        statements = mergeExportDeclarations(statements);
        statements = inlineExportModifiers(statements);
        if (enclosingDeclaration && (isSourceFile(enclosingDeclaration) && isExternalOrCommonJsModule(enclosingDeclaration) || isModuleDeclaration(enclosingDeclaration)) && (!some(statements, isExternalModuleIndicator) || !hasScopeMarker(statements) && some(statements, needsScopeMarker))) {
          statements.push(createEmptyExports(factory));
        }
        return statements;
      }
      function addExportModifier(node) {
        const flags = (getEffectiveModifierFlags(node) | 32 /* Export */) & ~128 /* Ambient */;
        return factory.replaceModifiers(node, flags);
      }
      function removeExportModifier(node) {
        const flags = getEffectiveModifierFlags(node) & ~32 /* Export */;
        return factory.replaceModifiers(node, flags);
      }
      function visitSymbolTable(symbolTable2, suppressNewPrivateContext, propertyAsAlias) {
        if (!suppressNewPrivateContext) {
          deferredPrivatesStack.push(/* @__PURE__ */ new Map());
        }
        symbolTable2.forEach((symbol) => {
          serializeSymbol(
            symbol,
            /*isPrivate*/
            false,
            !!propertyAsAlias
          );
        });
        if (!suppressNewPrivateContext) {
          deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach((symbol) => {
            serializeSymbol(
              symbol,
              /*isPrivate*/
              true,
              !!propertyAsAlias
            );
          });
          deferredPrivatesStack.pop();
        }
      }
      function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
        void getPropertiesOfType(getTypeOfSymbol(symbol));
        const visitedSym = getMergedSymbol(symbol);
        if (visitedSymbols.has(getSymbolId(visitedSym))) {
          return;
        }
        visitedSymbols.add(getSymbolId(visitedSym));
        const skipMembershipCheck = !isPrivate;
        if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) {
          const scopeCleanup = cloneNodeBuilderContext(context);
          context.tracker.pushErrorFallbackNode(find(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile));
          serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
          context.tracker.popErrorFallbackNode();
          scopeCleanup();
        }
      }
      function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) {
        var _a2, _b, _c, _d, _e, _f;
        const symbolName2 = unescapeLeadingUnderscores(escapedSymbolName);
        const isDefault = escapedSymbolName === "default" /* Default */;
        if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && isStringANonContextualKeyword(symbolName2) && !isDefault) {
          context.encounteredError = true;
          return;
        }
        let needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */ || symbol.flags & 16 /* Function */ && length(getPropertiesOfType(getTypeOfSymbol(symbol)))) && !(symbol.flags & 2097152 /* Alias */);
        let needsExportDeclaration = !needsPostExportDefault && !isPrivate && isStringANonContextualKeyword(symbolName2) && !isDefault;
        if (needsPostExportDefault || needsExportDeclaration) {
          isPrivate = true;
        }
        const modifierFlags = (!isPrivate ? 32 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 2048 /* Default */ : 0);
        const isConstMergedWithNS = symbol.flags & 1536 /* Module */ && symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && escapedSymbolName !== "export=" /* ExportEquals */;
        const isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
        if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
          serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
        }
        if (symbol.flags & 524288 /* TypeAlias */) {
          serializeTypeAlias(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && escapedSymbolName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) {
          if (propertyAsAlias) {
            const createdExport = serializeMaybeAliasAssignment(symbol);
            if (createdExport) {
              needsExportDeclaration = false;
              needsPostExportDefault = false;
            }
          } else {
            const type = getTypeOfSymbol(symbol);
            const localName = getInternalSymbolName(symbol, symbolName2);
            if (type.symbol && type.symbol !== symbol && type.symbol.flags & 16 /* Function */ && some(type.symbol.declarations, isFunctionExpressionOrArrowFunction) && (((_a2 = type.symbol.members) == null ? void 0 : _a2.size) || ((_b = type.symbol.exports) == null ? void 0 : _b.size))) {
              if (!context.remappedSymbolReferences) {
                context.remappedSymbolReferences = /* @__PURE__ */ new Map();
              }
              context.remappedSymbolReferences.set(getSymbolId(type.symbol), symbol);
              serializeSymbolWorker(type.symbol, isPrivate, propertyAsAlias, escapedSymbolName);
              context.remappedSymbolReferences.delete(getSymbolId(type.symbol));
            } else if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
              serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
            } else {
              const flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? ((_c = symbol.parent) == null ? void 0 : _c.valueDeclaration) && isSourceFile((_d = symbol.parent) == null ? void 0 : _d.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */;
              const name = needsPostExportDefault || !(symbol.flags & 4 /* Property */) ? localName : getUnusedName(localName, symbol);
              let textRange = symbol.declarations && find(symbol.declarations, (d) => isVariableDeclaration(d));
              if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
                textRange = textRange.parent.parent;
              }
              const propertyAccessRequire = (_e = symbol.declarations) == null ? void 0 : _e.find(isPropertyAccessExpression);
              if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && ((_f = type.symbol) == null ? void 0 : _f.valueDeclaration) && isSourceFile(type.symbol.valueDeclaration)) {
                const alias = localName === propertyAccessRequire.parent.right.escapedText ? void 0 : propertyAccessRequire.parent.right;
                addResult(
                  factory.createExportDeclaration(
                    /*modifiers*/
                    void 0,
                    /*isTypeOnly*/
                    false,
                    factory.createNamedExports([factory.createExportSpecifier(
                      /*isTypeOnly*/
                      false,
                      alias,
                      localName
                    )])
                  ),
                  0 /* None */
                );
                context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */);
              } else {
                const statement = setTextRange2(
                  context,
                  factory.createVariableStatement(
                    /*modifiers*/
                    void 0,
                    factory.createVariableDeclarationList([
                      factory.createVariableDeclaration(
                        name,
                        /*exclamationToken*/
                        void 0,
                        serializeTypeForDeclaration(
                          context,
                          /*declaration*/
                          void 0,
                          type,
                          symbol
                        )
                      )
                    ], flags)
                  ),
                  textRange
                );
                addResult(statement, name !== localName ? modifierFlags & ~32 /* Export */ : modifierFlags);
                if (name !== localName && !isPrivate) {
                  addResult(
                    factory.createExportDeclaration(
                      /*modifiers*/
                      void 0,
                      /*isTypeOnly*/
                      false,
                      factory.createNamedExports([factory.createExportSpecifier(
                        /*isTypeOnly*/
                        false,
                        name,
                        localName
                      )])
                    ),
                    0 /* None */
                  );
                  needsExportDeclaration = false;
                  needsPostExportDefault = false;
                }
              }
            }
          }
        }
        if (symbol.flags & 384 /* Enum */) {
          serializeEnum(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & 32 /* Class */) {
          if (symbol.flags & 4 /* Property */ && symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration.parent) && isClassExpression(symbol.valueDeclaration.parent.right)) {
            serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
          } else {
            serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
          }
        }
        if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol)) || isConstMergedWithNSPrintableAsSignatureMerge) {
          serializeModule(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) {
          serializeInterface(symbol, symbolName2, modifierFlags);
        }
        if (symbol.flags & 2097152 /* Alias */) {
          serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName2), modifierFlags);
        }
        if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
          serializeMaybeAliasAssignment(symbol);
        }
        if (symbol.flags & 8388608 /* ExportStar */) {
          if (symbol.declarations) {
            for (const node of symbol.declarations) {
              const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
              if (!resolvedModule) continue;
              addResult(factory.createExportDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                node.isTypeOnly,
                /*exportClause*/
                void 0,
                factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))
              ), 0 /* None */);
            }
          }
        }
        if (needsPostExportDefault) {
          addResult(factory.createExportAssignment(
            /*modifiers*/
            void 0,
            /*isExportEquals*/
            false,
            factory.createIdentifier(getInternalSymbolName(symbol, symbolName2))
          ), 0 /* None */);
        } else if (needsExportDeclaration) {
          addResult(
            factory.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory.createNamedExports([factory.createExportSpecifier(
                /*isTypeOnly*/
                false,
                getInternalSymbolName(symbol, symbolName2),
                symbolName2
              )])
            ),
            0 /* None */
          );
        }
      }
      function includePrivateSymbol(symbol) {
        if (some(symbol.declarations, isPartOfParameterDeclaration)) return;
        Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
        getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol);
        const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference));
        deferredPrivatesStack[isExternalImportAlias ? 0 : deferredPrivatesStack.length - 1].set(getSymbolId(symbol), symbol);
      }
      function isExportingScope(enclosingDeclaration2) {
        return isSourceFile(enclosingDeclaration2) && (isExternalOrCommonJsModule(enclosingDeclaration2) || isJsonSourceFile(enclosingDeclaration2)) || isAmbientModule(enclosingDeclaration2) && !isGlobalScopeAugmentation(enclosingDeclaration2);
      }
      function addResult(node, additionalModifierFlags) {
        if (canHaveModifiers(node)) {
          let newModifierFlags = 0 /* None */;
          const enclosingDeclaration2 = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration);
          if (additionalModifierFlags & 32 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) {
            newModifierFlags |= 32 /* Export */;
          }
          if (addingDeclare && !(newModifierFlags & 32 /* Export */) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) {
            newModifierFlags |= 128 /* Ambient */;
          }
          if (additionalModifierFlags & 2048 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) {
            newModifierFlags |= 2048 /* Default */;
          }
          if (newModifierFlags) {
            node = factory.replaceModifiers(node, newModifierFlags | getEffectiveModifierFlags(node));
          }
        }
        results.push(node);
      }
      function serializeTypeAlias(symbol, symbolName2, modifierFlags) {
        var _a2;
        const aliasType = getDeclaredTypeOfTypeAlias(symbol);
        const typeParams = getSymbolLinks(symbol).typeParameters;
        const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context));
        const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias);
        const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0);
        const restoreFlags = saveRestoreFlags(context);
        context.flags |= 8388608 /* InTypeAlias */;
        const oldEnclosingDecl = context.enclosingDeclaration;
        context.enclosingDeclaration = jsdocAliasDecl;
        const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && syntacticNodeBuilder.tryReuseExistingTypeNode(context, jsdocAliasDecl.typeExpression.type) || typeToTypeNodeHelper(aliasType, context);
        addResult(
          setSyntheticLeadingComments(
            factory.createTypeAliasDeclaration(
              /*modifiers*/
              void 0,
              getInternalSymbolName(symbol, symbolName2),
              typeParamDecls,
              typeNode
            ),
            !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]
          ),
          modifierFlags
        );
        restoreFlags();
        context.enclosingDeclaration = oldEnclosingDecl;
      }
      function serializeInterface(symbol, symbolName2, modifierFlags) {
        const interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
        const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context));
        const baseTypes = getBaseTypes(interfaceType);
        const baseType = length(baseTypes) ? getIntersectionType(baseTypes) : void 0;
        const members = flatMap(getPropertiesOfType(interfaceType), (p) => serializePropertySymbolForInterface(p, baseType));
        const callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 179 /* CallSignature */);
        const constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 180 /* ConstructSignature */);
        const indexSignatures = serializeIndexSignatures(interfaceType, baseType);
        const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(96 /* ExtendsKeyword */, mapDefined(baseTypes, (b) => trySerializeAsTypeReference(b, 111551 /* Value */)))];
        addResult(
          factory.createInterfaceDeclaration(
            /*modifiers*/
            void 0,
            getInternalSymbolName(symbol, symbolName2),
            typeParamDecls,
            heritageClauses,
            [...indexSignatures, ...constructSignatures, ...callSignatures, ...members]
          ),
          modifierFlags
        );
      }
      function getNamespaceMembersForSerialization(symbol) {
        let exports2 = arrayFrom(getExportsOfSymbol(symbol).values());
        const merged = getMergedSymbol(symbol);
        if (merged !== symbol) {
          const membersSet = new Set(exports2);
          for (const exported of getExportsOfSymbol(merged).values()) {
            if (!(getSymbolFlags(resolveSymbol(exported)) & 111551 /* Value */)) {
              membersSet.add(exported);
            }
          }
          exports2 = arrayFrom(membersSet);
        }
        return filter(exports2, (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */));
      }
      function isTypeOnlyNamespace(symbol) {
        return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */));
      }
      function serializeModule(symbol, symbolName2, modifierFlags) {
        const members = getNamespaceMembersForSerialization(symbol);
        const locationMap = arrayToMultiMap(members, (m) => m.parent && m.parent === symbol ? "real" : "merged");
        const realMembers = locationMap.get("real") || emptyArray;
        const mergedMembers = locationMap.get("merged") || emptyArray;
        if (length(realMembers)) {
          const localName = getInternalSymbolName(symbol, symbolName2);
          serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
        }
        if (length(mergedMembers)) {
          const containingFile = getSourceFileOfNode(context.enclosingDeclaration);
          const localName = getInternalSymbolName(symbol, symbolName2);
          const nsBody = factory.createModuleBlock([factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports(mapDefined(filter(mergedMembers, (n) => n.escapedName !== "export=" /* ExportEquals */), (s) => {
              var _a2, _b;
              const name = unescapeLeadingUnderscores(s.escapedName);
              const localName2 = getInternalSymbolName(s, name);
              const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
              if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d) => getSourceFileOfNode(d) === containingFile))) {
                (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a2, containingFile, symbol, s);
                return void 0;
              }
              const target = aliasDecl && getTargetOfAliasDeclaration(
                aliasDecl,
                /*dontRecursivelyResolve*/
                true
              );
              includePrivateSymbol(target || s);
              const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName2;
              return factory.createExportSpecifier(
                /*isTypeOnly*/
                false,
                name === targetName ? void 0 : targetName,
                name
              );
            }))
          )]);
          addResult(
            factory.createModuleDeclaration(
              /*modifiers*/
              void 0,
              factory.createIdentifier(localName),
              nsBody,
              32 /* Namespace */
            ),
            0 /* None */
          );
        }
      }
      function serializeEnum(symbol, symbolName2, modifierFlags) {
        addResult(
          factory.createEnumDeclaration(
            factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 4096 /* Const */ : 0),
            getInternalSymbolName(symbol, symbolName2),
            map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & 8 /* EnumMember */)), (p) => {
              const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0;
              return factory.createEnumMember(
                unescapeLeadingUnderscores(p.escapedName),
                initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue)
              );
            })
          ),
          modifierFlags
        );
      }
      function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
        const signatures = getSignaturesOfType(type, 0 /* Call */);
        for (const sig of signatures) {
          const decl = signatureToSignatureDeclarationHelper(sig, 262 /* FunctionDeclaration */, context, { name: factory.createIdentifier(localName) });
          addResult(setTextRange2(context, decl, getSignatureTextRangeLocation(sig)), modifierFlags);
        }
        if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
          const props = filter(getPropertiesOfType(type), isNamespaceMember);
          serializeAsNamespaceDeclaration(
            props,
            localName,
            modifierFlags,
            /*suppressNewPrivateContext*/
            true
          );
        }
      }
      function getSignatureTextRangeLocation(signature) {
        if (signature.declaration && signature.declaration.parent) {
          if (isBinaryExpression(signature.declaration.parent) && getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) {
            return signature.declaration.parent;
          }
          if (isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) {
            return signature.declaration.parent.parent;
          }
        }
        return signature.declaration;
      }
      function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
        if (length(props)) {
          const localVsRemoteMap = arrayToMultiMap(props, (p) => !length(p.declarations) || some(p.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote");
          const localProps = localVsRemoteMap.get("local") || emptyArray;
          let fakespace = parseNodeFactory.createModuleDeclaration(
            /*modifiers*/
            void 0,
            factory.createIdentifier(localName),
            factory.createModuleBlock([]),
            32 /* Namespace */
          );
          setParent(fakespace, enclosingDeclaration);
          fakespace.locals = createSymbolTable(props);
          fakespace.symbol = props[0].parent;
          const oldResults = results;
          results = [];
          const oldAddingDeclare = addingDeclare;
          addingDeclare = false;
          const subcontext = { ...context, enclosingDeclaration: fakespace };
          const oldContext = context;
          context = subcontext;
          visitSymbolTable(
            createSymbolTable(localProps),
            suppressNewPrivateContext,
            /*propertyAsAlias*/
            true
          );
          context = oldContext;
          addingDeclare = oldAddingDeclare;
          const declarations = results;
          results = oldResults;
          const defaultReplaced = map(declarations, (d) => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports([factory.createExportSpecifier(
              /*isTypeOnly*/
              false,
              d.expression,
              factory.createIdentifier("default" /* Default */)
            )])
          ) : d);
          const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, 32 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced;
          fakespace = factory.updateModuleDeclaration(
            fakespace,
            fakespace.modifiers,
            fakespace.name,
            factory.createModuleBlock(exportModifierStripped)
          );
          addResult(fakespace, modifierFlags);
        }
      }
      function isNamespaceMember(p) {
        return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) || !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && isStatic(p.valueDeclaration) && isClassLike(p.valueDeclaration.parent));
      }
      function sanitizeJSDocImplements(clauses) {
        const result = mapDefined(clauses, (e) => {
          const oldEnclosing = context.enclosingDeclaration;
          context.enclosingDeclaration = e;
          let expr = e.expression;
          if (isEntityNameExpression(expr)) {
            if (isIdentifier(expr) && idText(expr) === "") {
              return cleanup(
                /*result*/
                void 0
              );
            }
            let introducesError;
            ({ introducesError, node: expr } = trackExistingEntityName(expr, context));
            if (introducesError) {
              return cleanup(
                /*result*/
                void 0
              );
            }
          }
          return cleanup(factory.createExpressionWithTypeArguments(
            expr,
            map(e.typeArguments, (a) => syntacticNodeBuilder.tryReuseExistingTypeNode(context, a) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context))
          ));
          function cleanup(result2) {
            context.enclosingDeclaration = oldEnclosing;
            return result2;
          }
        });
        if (result.length === clauses.length) {
          return result;
        }
        return void 0;
      }
      function serializeAsClass(symbol, localName, modifierFlags) {
        var _a2, _b;
        const originalDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isClassLike);
        const oldEnclosing = context.enclosingDeclaration;
        context.enclosingDeclaration = originalDecl || oldEnclosing;
        const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context));
        const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol));
        const baseTypes = getBaseTypes(classType);
        const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl);
        const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType);
        const staticType = getTypeOfSymbol(symbol);
        const isClass = !!((_b = staticType.symbol) == null ? void 0 : _b.valueDeclaration) && isClassLike(staticType.symbol.valueDeclaration);
        const staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType;
        const heritageClauses = [
          ...!length(baseTypes) ? [] : [factory.createHeritageClause(96 /* ExtendsKeyword */, map(baseTypes, (b) => serializeBaseType(b, staticBaseType, localName)))],
          ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(119 /* ImplementsKeyword */, implementsExpressions)]
        ];
        const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType));
        const publicSymbolProps = filter(symbolProps, (s) => {
          const valueDecl = s.valueDeclaration;
          return !!valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name));
        });
        const hasPrivateIdentifier = some(symbolProps, (s) => {
          const valueDecl = s.valueDeclaration;
          return !!valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name);
        });
        const privateProperties = hasPrivateIdentifier ? [factory.createPropertyDeclaration(
          /*modifiers*/
          void 0,
          factory.createPrivateIdentifier("#private"),
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        )] : emptyArray;
        const publicProperties = flatMap(publicSymbolProps, (p) => serializePropertySymbolForClass(
          p,
          /*isStatic*/
          false,
          baseTypes[0]
        ));
        const staticMembers = flatMap(
          filter(getPropertiesOfType(staticType), (p) => !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p)),
          (p) => serializePropertySymbolForClass(
            p,
            /*isStatic*/
            true,
            staticBaseType
          )
        );
        const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, 1 /* Construct */));
        const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration(
          factory.createModifiersFromModifierFlags(2 /* Private */),
          [],
          /*body*/
          void 0
        )] : serializeSignatures(1 /* Construct */, staticType, staticBaseType, 176 /* Constructor */);
        const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
        context.enclosingDeclaration = oldEnclosing;
        addResult(
          setTextRange2(
            context,
            factory.createClassDeclaration(
              /*modifiers*/
              void 0,
              localName,
              typeParamDecls,
              heritageClauses,
              [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties]
            ),
            symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0]
          ),
          modifierFlags
        );
      }
      function getSomeTargetNameFromDeclarations(declarations) {
        return firstDefined(declarations, (d) => {
          if (isImportSpecifier(d) || isExportSpecifier(d)) {
            return moduleExportNameTextUnescaped(d.propertyName || d.name);
          }
          if (isBinaryExpression(d) || isExportAssignment(d)) {
            const expression = isExportAssignment(d) ? d.expression : d.right;
            if (isPropertyAccessExpression(expression)) {
              return idText(expression.name);
            }
          }
          if (isAliasSymbolDeclaration(d)) {
            const name = getNameOfDeclaration(d);
            if (name && isIdentifier(name)) {
              return idText(name);
            }
          }
          return void 0;
        });
      }
      function serializeAsAlias(symbol, localName, modifierFlags) {
        var _a2, _b, _c, _d, _e;
        const node = getDeclarationOfAliasSymbol(symbol);
        if (!node) return Debug.fail();
        const target = getMergedSymbol(getTargetOfAliasDeclaration(
          node,
          /*dontRecursivelyResolve*/
          true
        ));
        if (!target) {
          return;
        }
        let verbatimTargetName = isShorthandAmbientModuleSymbol(target) && getSomeTargetNameFromDeclarations(symbol.declarations) || unescapeLeadingUnderscores(target.escapedName);
        if (verbatimTargetName === "export=" /* ExportEquals */ && allowSyntheticDefaultImports) {
          verbatimTargetName = "default" /* Default */;
        }
        const targetName = getInternalSymbolName(target, verbatimTargetName);
        includePrivateSymbol(target);
        switch (node.kind) {
          case 208 /* BindingElement */:
            if (((_b = (_a2 = node.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */) {
              const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context);
              const { propertyName } = node;
              addResult(
                factory.createImportDeclaration(
                  /*modifiers*/
                  void 0,
                  factory.createImportClause(
                    /*isTypeOnly*/
                    false,
                    /*name*/
                    void 0,
                    factory.createNamedImports([factory.createImportSpecifier(
                      /*isTypeOnly*/
                      false,
                      propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0,
                      factory.createIdentifier(localName)
                    )])
                  ),
                  factory.createStringLiteral(specifier2),
                  /*attributes*/
                  void 0
                ),
                0 /* None */
              );
              break;
            }
            Debug.failBadSyntaxKind(((_c = node.parent) == null ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization");
            break;
          case 304 /* ShorthandPropertyAssignment */:
            if (((_e = (_d = node.parent) == null ? void 0 : _d.parent) == null ? void 0 : _e.kind) === 226 /* BinaryExpression */) {
              serializeExportSpecifier(
                unescapeLeadingUnderscores(symbol.escapedName),
                targetName
              );
            }
            break;
          case 260 /* VariableDeclaration */:
            if (isPropertyAccessExpression(node.initializer)) {
              const initializer = node.initializer;
              const uniqueName = factory.createUniqueName(localName);
              const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context);
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  uniqueName,
                  factory.createExternalModuleReference(factory.createStringLiteral(specifier2))
                ),
                0 /* None */
              );
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  factory.createIdentifier(localName),
                  factory.createQualifiedName(uniqueName, initializer.name)
                ),
                modifierFlags
              );
              break;
            }
          // else fall through and treat commonjs require just like import=
          case 271 /* ImportEqualsDeclaration */:
            if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, (d) => isSourceFile(d) && isJsonSourceFile(d))) {
              serializeMaybeAliasAssignment(symbol);
              break;
            }
            const isLocalImport = !(target.flags & 512 /* ValueModule */) && !isVariableDeclaration(node);
            addResult(
              factory.createImportEqualsDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                false,
                factory.createIdentifier(localName),
                isLocalImport ? symbolToName(
                  target,
                  context,
                  -1 /* All */,
                  /*expectsIdentifier*/
                  false
                ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))
              ),
              isLocalImport ? modifierFlags : 0 /* None */
            );
            break;
          case 270 /* NamespaceExportDeclaration */:
            addResult(factory.createNamespaceExportDeclaration(idText(node.name)), 0 /* None */);
            break;
          case 273 /* ImportClause */: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier;
            const attributes = isImportDeclaration(node.parent) ? node.parent.attributes : void 0;
            const isTypeOnly = isJSDocImportTag(node.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  factory.createIdentifier(localName),
                  /*namedBindings*/
                  void 0
                ),
                specifier2,
                attributes
              ),
              0 /* None */
            );
            break;
          }
          case 274 /* NamespaceImport */: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier;
            const isTypeOnly = isJSDocImportTag(node.parent.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  /*name*/
                  void 0,
                  factory.createNamespaceImport(factory.createIdentifier(localName))
                ),
                specifier2,
                node.parent.attributes
              ),
              0 /* None */
            );
            break;
          }
          case 280 /* NamespaceExport */:
            addResult(
              factory.createExportDeclaration(
                /*modifiers*/
                void 0,
                /*isTypeOnly*/
                false,
                factory.createNamespaceExport(factory.createIdentifier(localName)),
                factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))
              ),
              0 /* None */
            );
            break;
          case 276 /* ImportSpecifier */: {
            const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context);
            const specifier2 = context.bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier;
            const isTypeOnly = isJSDocImportTag(node.parent.parent.parent);
            addResult(
              factory.createImportDeclaration(
                /*modifiers*/
                void 0,
                factory.createImportClause(
                  isTypeOnly,
                  /*name*/
                  void 0,
                  factory.createNamedImports([
                    factory.createImportSpecifier(
                      /*isTypeOnly*/
                      false,
                      localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0,
                      factory.createIdentifier(localName)
                    )
                  ])
                ),
                specifier2,
                node.parent.parent.parent.attributes
              ),
              0 /* None */
            );
            break;
          }
          case 281 /* ExportSpecifier */:
            const specifier = node.parent.parent.moduleSpecifier;
            if (specifier) {
              const propertyName = node.propertyName;
              if (propertyName && moduleExportNameIsDefault(propertyName)) {
                verbatimTargetName = "default" /* Default */;
              }
            }
            serializeExportSpecifier(
              unescapeLeadingUnderscores(symbol.escapedName),
              specifier ? verbatimTargetName : targetName,
              specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0
            );
            break;
          case 277 /* ExportAssignment */:
            serializeMaybeAliasAssignment(symbol);
            break;
          case 226 /* BinaryExpression */:
          case 211 /* PropertyAccessExpression */:
          case 212 /* ElementAccessExpression */:
            if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
              serializeMaybeAliasAssignment(symbol);
            } else {
              serializeExportSpecifier(localName, targetName);
            }
            break;
          default:
            return Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
        }
      }
      function serializeExportSpecifier(localName, targetName, specifier) {
        addResult(
          factory.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory.createNamedExports([factory.createExportSpecifier(
              /*isTypeOnly*/
              false,
              localName !== targetName ? targetName : void 0,
              localName
            )]),
            specifier
          ),
          0 /* None */
        );
      }
      function serializeMaybeAliasAssignment(symbol) {
        var _a2;
        if (symbol.flags & 4194304 /* Prototype */) {
          return false;
        }
        const name = unescapeLeadingUnderscores(symbol.escapedName);
        const isExportEquals = name === "export=" /* ExportEquals */;
        const isDefault = name === "default" /* Default */;
        const isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
        const aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
        const target = aliasDecl && getTargetOfAliasDeclaration(
          aliasDecl,
          /*dontRecursivelyResolve*/
          true
        );
        if (target && length(target.declarations) && some(target.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(enclosingDeclaration))) {
          const expr = aliasDecl && (isExportAssignment(aliasDecl) || isBinaryExpression(aliasDecl) ? getExportAssignmentExpression(aliasDecl) : getPropertyAssignmentAliasLikeExpression(aliasDecl));
          const first2 = expr && isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : void 0;
          const referenced = first2 && resolveEntityName(
            first2,
            -1 /* All */,
            /*ignoreErrors*/
            true,
            /*dontResolveAlias*/
            true,
            enclosingDeclaration
          );
          if (referenced || target) {
            includePrivateSymbol(referenced || target);
          }
          const prevDisableTrackSymbol = context.tracker.disableTrackSymbol;
          context.tracker.disableTrackSymbol = true;
          if (isExportAssignmentCompatibleSymbolName) {
            results.push(factory.createExportAssignment(
              /*modifiers*/
              void 0,
              isExportEquals,
              symbolToExpression(target, context, -1 /* All */)
            ));
          } else {
            if (first2 === expr && first2) {
              serializeExportSpecifier(name, idText(first2));
            } else if (expr && isClassExpression(expr)) {
              serializeExportSpecifier(name, getInternalSymbolName(target, symbolName(target)));
            } else {
              const varName = getUnusedName(name, symbol);
              addResult(
                factory.createImportEqualsDeclaration(
                  /*modifiers*/
                  void 0,
                  /*isTypeOnly*/
                  false,
                  factory.createIdentifier(varName),
                  symbolToName(
                    target,
                    context,
                    -1 /* All */,
                    /*expectsIdentifier*/
                    false
                  )
                ),
                0 /* None */
              );
              serializeExportSpecifier(name, varName);
            }
          }
          context.tracker.disableTrackSymbol = prevDisableTrackSymbol;
          return true;
        } else {
          const varName = getUnusedName(name, symbol);
          const typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
          if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
            serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 32 /* Export */);
          } else {
            const flags = ((_a2 = context.enclosingDeclaration) == null ? void 0 : _a2.kind) === 267 /* ModuleDeclaration */ && (!(symbol.flags & 98304 /* Accessor */) || symbol.flags & 65536 /* SetAccessor */) ? 1 /* Let */ : 2 /* Const */;
            const statement = factory.createVariableStatement(
              /*modifiers*/
              void 0,
              factory.createVariableDeclarationList([
                factory.createVariableDeclaration(
                  varName,
                  /*exclamationToken*/
                  void 0,
                  serializeTypeForDeclaration(
                    context,
                    /*declaration*/
                    void 0,
                    typeToSerialize,
                    symbol
                  )
                )
              ], flags)
            );
            addResult(
              statement,
              target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 128 /* Ambient */ : name === varName ? 32 /* Export */ : 0 /* None */
            );
          }
          if (isExportAssignmentCompatibleSymbolName) {
            results.push(factory.createExportAssignment(
              /*modifiers*/
              void 0,
              isExportEquals,
              factory.createIdentifier(varName)
            ));
            return true;
          } else if (name !== varName) {
            serializeExportSpecifier(name, varName);
            return true;
          }
          return false;
        }
      }
      function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
        var _a2;
        const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration);
        return getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !some((_a2 = typeToSerialize.symbol) == null ? void 0 : _a2.declarations, isTypeNode) && // If the type comes straight from a type node, we shouldn't try to break it up
        !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
        !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
        !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => {
          if (!isIdentifierText(symbolName(p), languageVersion)) {
            return false;
          }
          if (!(p.flags & 98304 /* Accessor */)) {
            return true;
          }
          return getNonMissingTypeOfSymbol(p) === getWriteTypeOfSymbol(p);
        });
      }
      function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) {
        return function serializePropertySymbol(p, isStatic2, baseType) {
          var _a2, _b, _c, _d, _e, _f;
          const modifierFlags = getDeclarationModifierFlagsFromSymbol(p);
          const isPrivate = !!(modifierFlags & 2 /* Private */);
          if (isStatic2 && p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) {
            return [];
          }
          if (p.flags & 4194304 /* Prototype */ || p.escapedName === "constructor" || baseType && getPropertyOfType(baseType, p.escapedName) && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName))) {
            return [];
          }
          const flag = modifierFlags & ~1024 /* Async */ | (isStatic2 ? 256 /* Static */ : 0);
          const name = getPropertyNameNodeForSymbol(p, context);
          const firstPropertyLikeDecl = (_a2 = p.declarations) == null ? void 0 : _a2.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression));
          if (p.flags & 98304 /* Accessor */ && useAccessors) {
            const result = [];
            if (p.flags & 65536 /* SetAccessor */) {
              const setter = p.declarations && forEach(p.declarations, (d) => {
                if (d.kind === 178 /* SetAccessor */) {
                  return d;
                }
                if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) {
                  return forEach(d.arguments[2].properties, (propDecl) => {
                    const id = getNameOfDeclaration(propDecl);
                    if (!!id && isIdentifier(id) && idText(id) === "set") {
                      return propDecl;
                    }
                  });
                }
              });
              Debug.assert(!!setter);
              const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0;
              const setterDeclaration = (_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor);
              result.push(setTextRange2(
                context,
                factory.createSetAccessorDeclaration(
                  factory.createModifiersFromModifierFlags(flag),
                  name,
                  [factory.createParameterDeclaration(
                    /*modifiers*/
                    void 0,
                    /*dotDotDotToken*/
                    void 0,
                    paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value",
                    /*questionToken*/
                    void 0,
                    isPrivate ? void 0 : serializeTypeForDeclaration(context, setterDeclaration, getWriteTypeOfSymbol(p), p)
                  )],
                  /*body*/
                  void 0
                ),
                setterDeclaration ?? firstPropertyLikeDecl
              ));
            }
            if (p.flags & 32768 /* GetAccessor */) {
              const isPrivate2 = modifierFlags & 2 /* Private */;
              const getterDeclaration = (_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor);
              result.push(setTextRange2(
                context,
                factory.createGetAccessorDeclaration(
                  factory.createModifiersFromModifierFlags(flag),
                  name,
                  [],
                  isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getterDeclaration, getTypeOfSymbol(p), p),
                  /*body*/
                  void 0
                ),
                getterDeclaration ?? firstPropertyLikeDecl
              ));
            }
            return result;
          } else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) {
            return setTextRange2(
              context,
              createProperty2(
                factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag),
                name,
                p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                isPrivate ? void 0 : serializeTypeForDeclaration(context, (_d = p.declarations) == null ? void 0 : _d.find(isSetAccessorDeclaration), getWriteTypeOfSymbol(p), p),
                // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
                // interface members can't have initializers, however class members _can_
                /*initializer*/
                void 0
              ),
              ((_e = p.declarations) == null ? void 0 : _e.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl
            );
          }
          if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
            const type = getTypeOfSymbol(p);
            const signatures = getSignaturesOfType(type, 0 /* Call */);
            if (flag & 2 /* Private */) {
              return setTextRange2(
                context,
                createProperty2(
                  factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag),
                  name,
                  p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                  /*type*/
                  void 0,
                  /*initializer*/
                  void 0
                ),
                ((_f = p.declarations) == null ? void 0 : _f.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]
              );
            }
            const results2 = [];
            for (const sig of signatures) {
              const decl = signatureToSignatureDeclarationHelper(
                sig,
                methodKind,
                context,
                {
                  name,
                  questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0,
                  modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0
                }
              );
              const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration;
              results2.push(setTextRange2(context, decl, location));
            }
            return results2;
          }
          return Debug.fail(`Unhandled class member kind! ${p.__debugFlags || p.flags}`);
        };
      }
      function serializePropertySymbolForInterface(p, baseType) {
        return serializePropertySymbolForInterfaceWorker(
          p,
          /*isStatic*/
          false,
          baseType
        );
      }
      function serializeSignatures(kind, input, baseType, outputKind) {
        const signatures = getSignaturesOfType(input, kind);
        if (kind === 1 /* Construct */) {
          if (!baseType && every(signatures, (s) => length(s.parameters) === 0)) {
            return [];
          }
          if (baseType) {
            const baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
            if (!length(baseSigs) && every(signatures, (s) => length(s.parameters) === 0)) {
              return [];
            }
            if (baseSigs.length === signatures.length) {
              let failed2 = false;
              for (let i = 0; i < baseSigs.length; i++) {
                if (!compareSignaturesIdentical(
                  signatures[i],
                  baseSigs[i],
                  /*partialMatch*/
                  false,
                  /*ignoreThisTypes*/
                  false,
                  /*ignoreReturnTypes*/
                  true,
                  compareTypesIdentical
                )) {
                  failed2 = true;
                  break;
                }
              }
              if (!failed2) {
                return [];
              }
            }
          }
          let privateProtected = 0;
          for (const s of signatures) {
            if (s.declaration) {
              privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, 2 /* Private */ | 4 /* Protected */);
            }
          }
          if (privateProtected) {
            return [setTextRange2(
              context,
              factory.createConstructorDeclaration(
                factory.createModifiersFromModifierFlags(privateProtected),
                /*parameters*/
                [],
                /*body*/
                void 0
              ),
              signatures[0].declaration
            )];
          }
        }
        const results2 = [];
        for (const sig of signatures) {
          const decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
          results2.push(setTextRange2(context, decl, sig.declaration));
        }
        return results2;
      }
      function serializeIndexSignatures(input, baseType) {
        const results2 = [];
        for (const info of getIndexInfosOfType(input)) {
          if (baseType) {
            const baseInfo = getIndexInfoOfType(baseType, info.keyType);
            if (baseInfo) {
              if (isTypeIdenticalTo(info.type, baseInfo.type)) {
                continue;
              }
            }
          }
          results2.push(indexInfoToIndexSignatureDeclarationHelper(
            info,
            context,
            /*typeNode*/
            void 0
          ));
        }
        return results2;
      }
      function serializeBaseType(t, staticType, rootName) {
        const ref = trySerializeAsTypeReference(t, 111551 /* Value */);
        if (ref) {
          return ref;
        }
        const tempName = getUnusedName(`${rootName}_base`);
        const statement = factory.createVariableStatement(
          /*modifiers*/
          void 0,
          factory.createVariableDeclarationList([
            factory.createVariableDeclaration(
              tempName,
              /*exclamationToken*/
              void 0,
              typeToTypeNodeHelper(staticType, context)
            )
          ], 2 /* Const */)
        );
        addResult(statement, 0 /* None */);
        return factory.createExpressionWithTypeArguments(
          factory.createIdentifier(tempName),
          /*typeArguments*/
          void 0
        );
      }
      function trySerializeAsTypeReference(t, flags) {
        let typeArgs;
        let reference;
        if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
          typeArgs = map(getTypeArguments(t), (t2) => typeToTypeNodeHelper(t2, context));
          reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
        } else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
          reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
        }
        if (reference) {
          return factory.createExpressionWithTypeArguments(reference, typeArgs);
        }
      }
      function serializeImplementedType(t) {
        const ref = trySerializeAsTypeReference(t, 788968 /* Type */);
        if (ref) {
          return ref;
        }
        if (t.symbol) {
          return factory.createExpressionWithTypeArguments(
            symbolToExpression(t.symbol, context, 788968 /* Type */),
            /*typeArguments*/
            void 0
          );
        }
      }
      function getUnusedName(input, symbol) {
        var _a2, _b;
        const id = symbol ? getSymbolId(symbol) : void 0;
        if (id) {
          if (context.remappedSymbolNames.has(id)) {
            return context.remappedSymbolNames.get(id);
          }
        }
        if (symbol) {
          input = getNameCandidateWorker(symbol, input);
        }
        let i = 0;
        const original = input;
        while ((_a2 = context.usedSymbolNames) == null ? void 0 : _a2.has(input)) {
          i++;
          input = `${original}_${i}`;
        }
        (_b = context.usedSymbolNames) == null ? void 0 : _b.add(input);
        if (id) {
          context.remappedSymbolNames.set(id, input);
        }
        return input;
      }
      function getNameCandidateWorker(symbol, localName) {
        if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
          const restoreFlags = saveRestoreFlags(context);
          context.flags |= 16777216 /* InInitialEntityName */;
          const nameCandidate = getNameOfSymbolAsWritten(symbol, context);
          restoreFlags();
          localName = nameCandidate.length > 0 && isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? stripQuotes(nameCandidate) : nameCandidate;
        }
        if (localName === "default" /* Default */) {
          localName = "_default";
        } else if (localName === "export=" /* ExportEquals */) {
          localName = "_exports";
        }
        localName = isIdentifierText(localName, languageVersion) && !isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-z0-9]/gi, "_");
        return localName;
      }
      function getInternalSymbolName(symbol, localName) {
        const id = getSymbolId(symbol);
        if (context.remappedSymbolNames.has(id)) {
          return context.remappedSymbolNames.get(id);
        }
        localName = getNameCandidateWorker(symbol, localName);
        context.remappedSymbolNames.set(id, localName);
        return localName;
      }
    }
  }
  function typePredicateToString(typePredicate, enclosingDeclaration, flags = 16384 /* UseAliasDefinedOutsideCurrentScope */, writer) {
    return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker);
    function typePredicateToStringWorker(writer2) {
      const nodeBuilderFlags = toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */;
      const predicate = nodeBuilder.typePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, nodeBuilderFlags);
      const printer = createPrinterWithRemoveComments();
      const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
      printer.writeNode(
        4 /* Unspecified */,
        predicate,
        /*sourceFile*/
        sourceFile,
        writer2
      );
      return writer2;
    }
  }
  function formatUnionTypes(types) {
    const result = [];
    let flags = 0;
    for (let i = 0; i < types.length; i++) {
      const t = types[i];
      flags |= t.flags;
      if (!(t.flags & 98304 /* Nullable */)) {
        if (t.flags & (512 /* BooleanLiteral */ | 1056 /* EnumLike */)) {
          const baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLikeType(t);
          if (baseType.flags & 1048576 /* Union */) {
            const count = baseType.types.length;
            if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
              result.push(baseType);
              i += count - 1;
              continue;
            }
          }
        }
        result.push(t);
      }
    }
    if (flags & 65536 /* Null */) result.push(nullType);
    if (flags & 32768 /* Undefined */) result.push(undefinedType);
    return result || types;
  }
  function visibilityToString(flags) {
    if (flags === 2 /* Private */) {
      return "private";
    }
    if (flags === 4 /* Protected */) {
      return "protected";
    }
    return "public";
  }
  function getTypeAliasForTypeLiteral(type) {
    if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) {
      const node = walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
      if (isTypeAliasDeclaration(node)) {
        return getSymbolOfDeclaration(node);
      }
    }
    return void 0;
  }
  function isTopLevelInExternalModuleAugmentation(node) {
    return node && node.parent && node.parent.kind === 268 /* ModuleBlock */ && isExternalModuleAugmentation(node.parent.parent);
  }
  function isDefaultBindingContext(location) {
    return location.kind === 307 /* SourceFile */ || isAmbientModule(location);
  }
  function getNameOfSymbolFromNameType(symbol, context) {
    const nameType = getSymbolLinks(symbol).nameType;
    if (nameType) {
      if (nameType.flags & 384 /* StringOrNumberLiteral */) {
        const name = "" + nameType.value;
        if (!isIdentifierText(name, getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) {
          return `"${escapeString(name, 34 /* doubleQuote */)}"`;
        }
        if (isNumericLiteralName(name) && startsWith(name, "-")) {
          return `[${name}]`;
        }
        return name;
      }
      if (nameType.flags & 8192 /* UniqueESSymbol */) {
        return `[${getNameOfSymbolAsWritten(nameType.symbol, context)}]`;
      }
    }
  }
  function getNameOfSymbolAsWritten(symbol, context) {
    var _a;
    if ((_a = context == null ? void 0 : context.remappedSymbolReferences) == null ? void 0 : _a.has(getSymbolId(symbol))) {
      symbol = context.remappedSymbolReferences.get(getSymbolId(symbol));
    }
    if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && // If it's not the first part of an entity name, it must print as `default`
    (!(context.flags & 16777216 /* InInitialEntityName */) || // if the symbol is synthesized, it will only be referenced externally it must print as `default`
    !symbol.declarations || // if not in the same binding context (source file, module declaration), it must print as `default`
    context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext))) {
      return "default";
    }
    if (symbol.declarations && symbol.declarations.length) {
      let declaration = firstDefined(symbol.declarations, (d) => getNameOfDeclaration(d) ? d : void 0);
      const name2 = declaration && getNameOfDeclaration(declaration);
      if (declaration && name2) {
        if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) {
          return symbolName(symbol);
        }
        if (isComputedPropertyName(name2) && !(getCheckFlags(symbol) & 4096 /* Late */)) {
          const nameType = getSymbolLinks(symbol).nameType;
          if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
            const result = getNameOfSymbolFromNameType(symbol, context);
            if (result !== void 0) {
              return result;
            }
          }
        }
        return declarationNameToString(name2);
      }
      if (!declaration) {
        declaration = symbol.declarations[0];
      }
      if (declaration.parent && declaration.parent.kind === 260 /* VariableDeclaration */) {
        return declarationNameToString(declaration.parent.name);
      }
      switch (declaration.kind) {
        case 231 /* ClassExpression */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
          if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
            context.encounteredError = true;
          }
          return declaration.kind === 231 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
      }
    }
    const name = getNameOfSymbolFromNameType(symbol, context);
    return name !== void 0 ? name : symbolName(symbol);
  }
  function isDeclarationVisible(node) {
    if (node) {
      const links = getNodeLinks(node);
      if (links.isVisible === void 0) {
        links.isVisible = !!determineIfDeclarationIsVisible();
      }
      return links.isVisible;
    }
    return false;
    function determineIfDeclarationIsVisible() {
      switch (node.kind) {
        case 338 /* JSDocCallbackTag */:
        case 346 /* JSDocTypedefTag */:
        case 340 /* JSDocEnumTag */:
          return !!(node.parent && node.parent.parent && node.parent.parent.parent && isSourceFile(node.parent.parent.parent));
        case 208 /* BindingElement */:
          return isDeclarationVisible(node.parent.parent);
        case 260 /* VariableDeclaration */:
          if (isBindingPattern(node.name) && !node.name.elements.length) {
            return false;
          }
        // falls through
        case 267 /* ModuleDeclaration */:
        case 263 /* ClassDeclaration */:
        case 264 /* InterfaceDeclaration */:
        case 265 /* TypeAliasDeclaration */:
        case 262 /* FunctionDeclaration */:
        case 266 /* EnumDeclaration */:
        case 271 /* ImportEqualsDeclaration */:
          if (isExternalModuleAugmentation(node)) {
            return true;
          }
          const parent = getDeclarationContainer(node);
          if (!(getCombinedModifierFlagsCached(node) & 32 /* Export */) && !(node.kind !== 271 /* ImportEqualsDeclaration */ && parent.kind !== 307 /* SourceFile */ && parent.flags & 33554432 /* Ambient */)) {
            return isGlobalSourceFile(parent);
          }
          return isDeclarationVisible(parent);
        case 172 /* PropertyDeclaration */:
        case 171 /* PropertySignature */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 174 /* MethodDeclaration */:
        case 173 /* MethodSignature */:
          if (hasEffectiveModifier(node, 2 /* Private */ | 4 /* Protected */)) {
            return false;
          }
        // Public properties/methods are visible if its parents are visible, so:
        // falls through
        case 176 /* Constructor */:
        case 180 /* ConstructSignature */:
        case 179 /* CallSignature */:
        case 181 /* IndexSignature */:
        case 169 /* Parameter */:
        case 268 /* ModuleBlock */:
        case 184 /* FunctionType */:
        case 185 /* ConstructorType */:
        case 187 /* TypeLiteral */:
        case 183 /* TypeReference */:
        case 188 /* ArrayType */:
        case 189 /* TupleType */:
        case 192 /* UnionType */:
        case 193 /* IntersectionType */:
        case 196 /* ParenthesizedType */:
        case 202 /* NamedTupleMember */:
          return isDeclarationVisible(node.parent);
        // Default binding, import specifier and namespace import is visible
        // only on demand so by default it is not visible
        case 273 /* ImportClause */:
        case 274 /* NamespaceImport */:
        case 276 /* ImportSpecifier */:
          return false;
        // Type parameters are always visible
        case 168 /* TypeParameter */:
        // Source file and namespace export are always visible
        // falls through
        case 307 /* SourceFile */:
        case 270 /* NamespaceExportDeclaration */:
          return true;
        // Export assignments do not create name bindings outside the module
        case 277 /* ExportAssignment */:
          return false;
        default:
          return false;
      }
    }
  }
  function collectLinkedAliases(node, setVisibility) {
    let exportSymbol;
    if (node.kind !== 11 /* StringLiteral */ && node.parent && node.parent.kind === 277 /* ExportAssignment */) {
      exportSymbol = resolveName(
        node,
        node,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
    } else if (node.parent.kind === 281 /* ExportSpecifier */) {
      exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
    }
    let result;
    let visited;
    if (exportSymbol) {
      visited = /* @__PURE__ */ new Set();
      visited.add(getSymbolId(exportSymbol));
      buildVisibleNodeList(exportSymbol.declarations);
    }
    return result;
    function buildVisibleNodeList(declarations) {
      forEach(declarations, (declaration) => {
        const resultNode = getAnyImportSyntax(declaration) || declaration;
        if (setVisibility) {
          getNodeLinks(declaration).isVisible = true;
        } else {
          result = result || [];
          pushIfUnique(result, resultNode);
        }
        if (isInternalModuleImportEqualsDeclaration(declaration)) {
          const internalModuleReference = declaration.moduleReference;
          const firstIdentifier = getFirstIdentifier(internalModuleReference);
          const importSymbol = resolveName(
            declaration,
            firstIdentifier.escapedText,
            111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          );
          if (importSymbol && visited) {
            if (tryAddToSet(visited, getSymbolId(importSymbol))) {
              buildVisibleNodeList(importSymbol.declarations);
            }
          }
        }
      });
    }
  }
  function pushTypeResolution(target, propertyName) {
    const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
    if (resolutionCycleStartIndex >= 0) {
      const { length: length2 } = resolutionTargets;
      for (let i = resolutionCycleStartIndex; i < length2; i++) {
        resolutionResults[i] = false;
      }
      return false;
    }
    resolutionTargets.push(target);
    resolutionResults.push(
      /*items*/
      true
    );
    resolutionPropertyNames.push(propertyName);
    return true;
  }
  function findResolutionCycleStartIndex(target, propertyName) {
    for (let i = resolutionTargets.length - 1; i >= resolutionStart; i--) {
      if (resolutionTargetHasProperty(resolutionTargets[i], resolutionPropertyNames[i])) {
        return -1;
      }
      if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
        return i;
      }
    }
    return -1;
  }
  function resolutionTargetHasProperty(target, propertyName) {
    switch (propertyName) {
      case 0 /* Type */:
        return !!getSymbolLinks(target).type;
      case 2 /* DeclaredType */:
        return !!getSymbolLinks(target).declaredType;
      case 1 /* ResolvedBaseConstructorType */:
        return !!target.resolvedBaseConstructorType;
      case 3 /* ResolvedReturnType */:
        return !!target.resolvedReturnType;
      case 4 /* ImmediateBaseConstraint */:
        return !!target.immediateBaseConstraint;
      case 5 /* ResolvedTypeArguments */:
        return !!target.resolvedTypeArguments;
      case 6 /* ResolvedBaseTypes */:
        return !!target.baseTypesResolved;
      case 7 /* WriteType */:
        return !!getSymbolLinks(target).writeType;
      case 8 /* ParameterInitializerContainsUndefined */:
        return getNodeLinks(target).parameterInitializerContainsUndefined !== void 0;
    }
    return Debug.assertNever(propertyName);
  }
  function popTypeResolution() {
    resolutionTargets.pop();
    resolutionPropertyNames.pop();
    return resolutionResults.pop();
  }
  function getDeclarationContainer(node) {
    return findAncestor(getRootDeclaration(node), (node2) => {
      switch (node2.kind) {
        case 260 /* VariableDeclaration */:
        case 261 /* VariableDeclarationList */:
        case 276 /* ImportSpecifier */:
        case 275 /* NamedImports */:
        case 274 /* NamespaceImport */:
        case 273 /* ImportClause */:
          return false;
        default:
          return true;
      }
    }).parent;
  }
  function getTypeOfPrototypeProperty(prototype) {
    const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
    return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, (_) => anyType)) : classType;
  }
  function getTypeOfPropertyOfType(type, name) {
    const prop = getPropertyOfType(type, name);
    return prop ? getTypeOfSymbol(prop) : void 0;
  }
  function getTypeOfPropertyOrIndexSignatureOfType(type, name) {
    var _a;
    let propType;
    return getTypeOfPropertyOfType(type, name) || (propType = (_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) && addOptionality(
      propType,
      /*isProperty*/
      true,
      /*isOptional*/
      true
    );
  }
  function isTypeAny(type) {
    return type && (type.flags & 1 /* Any */) !== 0;
  }
  function isErrorType(type) {
    return type === errorType || !!(type.flags & 1 /* Any */ && type.aliasSymbol);
  }
  function getTypeForBindingElementParent(node, checkMode) {
    if (checkMode !== 0 /* Normal */) {
      return getTypeForVariableLikeDeclaration(
        node,
        /*includeOptionality*/
        false,
        checkMode
      );
    }
    const symbol = getSymbolOfDeclaration(node);
    return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(
      node,
      /*includeOptionality*/
      false,
      checkMode
    );
  }
  function getRestType(source, properties, symbol) {
    source = filterType(source, (t) => !(t.flags & 98304 /* Nullable */));
    if (source.flags & 131072 /* Never */) {
      return emptyObjectType;
    }
    if (source.flags & 1048576 /* Union */) {
      return mapType(source, (t) => getRestType(t, properties, symbol));
    }
    let omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName));
    const spreadableProperties = [];
    const unspreadableToRestKeys = [];
    for (const prop of getPropertiesOfType(source)) {
      const literalTypeFromProperty = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */);
      if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) && isSpreadableProperty(prop)) {
        spreadableProperties.push(prop);
      } else {
        unspreadableToRestKeys.push(literalTypeFromProperty);
      }
    }
    if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
      if (unspreadableToRestKeys.length) {
        omitKeyType = getUnionType([omitKeyType, ...unspreadableToRestKeys]);
      }
      if (omitKeyType.flags & 131072 /* Never */) {
        return source;
      }
      const omitTypeAlias = getGlobalOmitSymbol();
      if (!omitTypeAlias) {
        return errorType;
      }
      return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
    }
    const members = createSymbolTable();
    for (const prop of spreadableProperties) {
      members.set(prop.escapedName, getSpreadSymbol(
        prop,
        /*readonly*/
        false
      ));
    }
    const result = createAnonymousType(symbol, members, emptyArray, emptyArray, getIndexInfosOfType(source));
    result.objectFlags |= 4194304 /* ObjectRestType */;
    return result;
  }
  function isGenericTypeWithUndefinedConstraint(type) {
    return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */);
  }
  function getNonUndefinedType(type) {
    const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t) : type;
    return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */);
  }
  function getFlowTypeOfDestructuring(node, declaredType) {
    const reference = getSyntheticElementAccess(node);
    return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
  }
  function getSyntheticElementAccess(node) {
    const parentAccess = getParentElementAccess(node);
    if (parentAccess && canHaveFlowNode(parentAccess) && parentAccess.flowNode) {
      const propName = getDestructuringPropertyName(node);
      if (propName) {
        const literal = setTextRange(parseNodeFactory.createStringLiteral(propName), node);
        const lhsExpr = isLeftHandSideExpression(parentAccess) ? parentAccess : parseNodeFactory.createParenthesizedExpression(parentAccess);
        const result = setTextRange(parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
        setParent(literal, result);
        setParent(result, node);
        if (lhsExpr !== parentAccess) {
          setParent(lhsExpr, result);
        }
        result.flowNode = parentAccess.flowNode;
        return result;
      }
    }
  }
  function getParentElementAccess(node) {
    const ancestor = node.parent.parent;
    switch (ancestor.kind) {
      case 208 /* BindingElement */:
      case 303 /* PropertyAssignment */:
        return getSyntheticElementAccess(ancestor);
      case 209 /* ArrayLiteralExpression */:
        return getSyntheticElementAccess(node.parent);
      case 260 /* VariableDeclaration */:
        return ancestor.initializer;
      case 226 /* BinaryExpression */:
        return ancestor.right;
    }
  }
  function getDestructuringPropertyName(node) {
    const parent = node.parent;
    if (node.kind === 208 /* BindingElement */ && parent.kind === 206 /* ObjectBindingPattern */) {
      return getLiteralPropertyNameText(node.propertyName || node.name);
    }
    if (node.kind === 303 /* PropertyAssignment */ || node.kind === 304 /* ShorthandPropertyAssignment */) {
      return getLiteralPropertyNameText(node.name);
    }
    return "" + parent.elements.indexOf(node);
  }
  function getLiteralPropertyNameText(name) {
    const type = getLiteralTypeFromPropertyName(name);
    return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : void 0;
  }
  function getTypeForBindingElement(declaration) {
    const checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */;
    const parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode);
    return parentType && getBindingElementTypeFromParentType(
      declaration,
      parentType,
      /*noTupleBoundsCheck*/
      false
    );
  }
  function getBindingElementTypeFromParentType(declaration, parentType, noTupleBoundsCheck) {
    if (isTypeAny(parentType)) {
      return parentType;
    }
    const pattern = declaration.parent;
    if (strictNullChecks && declaration.flags & 33554432 /* Ambient */ && isPartOfParameterDeclaration(declaration)) {
      parentType = getNonNullableType(parentType);
    } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) {
      parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
    }
    const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* AllowMissing */ : 0);
    let type;
    if (pattern.kind === 206 /* ObjectBindingPattern */) {
      if (declaration.dotDotDotToken) {
        parentType = getReducedType(parentType);
        if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
          error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types);
          return errorType;
        }
        const literalMembers = [];
        for (const element of pattern.elements) {
          if (!element.dotDotDotToken) {
            literalMembers.push(element.propertyName || element.name);
          }
        }
        type = getRestType(parentType, literalMembers, declaration.symbol);
      } else {
        const name = declaration.propertyName || declaration.name;
        const indexType = getLiteralTypeFromPropertyName(name);
        const declaredType = getIndexedAccessType(parentType, indexType, accessFlags, name);
        type = getFlowTypeOfDestructuring(declaration, declaredType);
      }
    } else {
      const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
      const index = pattern.elements.indexOf(declaration);
      if (declaration.dotDotDotToken) {
        const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t);
        type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType);
      } else if (isArrayLikeType(parentType)) {
        const indexType = getNumberLiteralType(index);
        const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType;
        type = getFlowTypeOfDestructuring(declaration, declaredType);
      } else {
        type = elementType;
      }
    }
    if (!declaration.initializer) {
      return type;
    }
    if (getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration))) {
      return strictNullChecks && !hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */) ? getNonUndefinedType(type) : type;
    }
    return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */));
  }
  function getTypeForDeclarationFromJSDocComment(declaration) {
    const jsdocType = getJSDocType(declaration);
    if (jsdocType) {
      return getTypeFromTypeNode(jsdocType);
    }
    return void 0;
  }
  function isNullOrUndefined2(node) {
    const expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return expr.kind === 106 /* NullKeyword */ || expr.kind === 80 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
  }
  function isEmptyArrayLiteral2(node) {
    const expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return expr.kind === 209 /* ArrayLiteralExpression */ && expr.elements.length === 0;
  }
  function addOptionality(type, isProperty = false, isOptional = true) {
    return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type;
  }
  function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) {
    if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 249 /* ForInStatement */) {
      const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(
        declaration.parent.parent.expression,
        /*checkMode*/
        checkMode
      )));
      return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
    }
    if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) {
      const forOfStatement = declaration.parent.parent;
      return checkRightHandSideOfForOf(forOfStatement) || anyType;
    }
    if (isBindingPattern(declaration.parent)) {
      return getTypeForBindingElement(declaration);
    }
    const isProperty = isPropertyDeclaration(declaration) && !hasAccessorModifier(declaration) || isPropertySignature(declaration) || isJSDocPropertyTag(declaration);
    const isOptional = includeOptionality && isOptionalDeclaration(declaration);
    const declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
    if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
      if (declaredType) {
        return isTypeAny(declaredType) || declaredType === unknownType ? declaredType : errorType;
      }
      return useUnknownInCatchVariables ? unknownType : anyType;
    }
    if (declaredType) {
      return addOptionality(declaredType, isProperty, isOptional);
    }
    if ((noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && !(getCombinedModifierFlagsCached(declaration) & 32 /* Export */) && !(declaration.flags & 33554432 /* Ambient */)) {
      if (!(getCombinedNodeFlagsCached(declaration) & 6 /* Constant */) && (!declaration.initializer || isNullOrUndefined2(declaration.initializer))) {
        return autoType;
      }
      if (declaration.initializer && isEmptyArrayLiteral2(declaration.initializer)) {
        return autoArrayType;
      }
    }
    if (isParameter(declaration)) {
      if (!declaration.symbol) {
        return;
      }
      const func = declaration.parent;
      if (func.kind === 178 /* SetAccessor */ && hasBindableName(func)) {
        const getter = getDeclarationOfKind(getSymbolOfDeclaration(declaration.parent), 177 /* GetAccessor */);
        if (getter) {
          const getterSignature = getSignatureFromDeclaration(getter);
          const thisParameter = getAccessorThisParameter(func);
          if (thisParameter && declaration === thisParameter) {
            Debug.assert(!thisParameter.type);
            return getTypeOfSymbol(getterSignature.thisParameter);
          }
          return getReturnTypeOfSignature(getterSignature);
        }
      }
      const parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration);
      if (parameterTypeOfTypeTag) return parameterTypeOfTypeTag;
      const type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
      if (type) {
        return addOptionality(
          type,
          /*isProperty*/
          false,
          isOptional
        );
      }
    }
    if (hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
      if (isInJSFile(declaration) && !isParameter(declaration)) {
        const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfDeclaration(declaration), getDeclaredExpandoInitializer(declaration));
        if (containerObjectType) {
          return containerObjectType;
        }
      }
      const type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration, checkMode));
      return addOptionality(type, isProperty, isOptional);
    }
    if (isPropertyDeclaration(declaration) && (noImplicitAny || isInJSFile(declaration))) {
      if (!hasStaticModifier(declaration)) {
        const constructor = findConstructorDeclaration(declaration.parent);
        const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0;
        return type && addOptionality(
          type,
          /*isProperty*/
          true,
          isOptional
        );
      } else {
        const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration);
        const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0;
        return type && addOptionality(
          type,
          /*isProperty*/
          true,
          isOptional
        );
      }
    }
    if (isJsxAttribute(declaration)) {
      return trueType;
    }
    if (isBindingPattern(declaration.name)) {
      return getTypeFromBindingPattern(
        declaration.name,
        /*includePatternInType*/
        false,
        /*reportErrors*/
        true
      );
    }
    return void 0;
  }
  function isConstructorDeclaredProperty(symbol) {
    if (symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration)) {
      const links = getSymbolLinks(symbol);
      if (links.isConstructorDeclaredProperty === void 0) {
        links.isConstructorDeclaredProperty = false;
        links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration) => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 212 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(
          /*declaredType*/
          void 0,
          declaration,
          symbol,
          declaration
        ));
      }
      return links.isConstructorDeclaredProperty;
    }
    return false;
  }
  function isAutoTypedProperty(symbol) {
    const declaration = symbol.valueDeclaration;
    return declaration && isPropertyDeclaration(declaration) && !getEffectiveTypeAnnotationNode(declaration) && !declaration.initializer && (noImplicitAny || isInJSFile(declaration));
  }
  function getDeclaringConstructor(symbol) {
    if (!symbol.declarations) {
      return;
    }
    for (const declaration of symbol.declarations) {
      const container = getThisContainer(
        declaration,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (container && (container.kind === 176 /* Constructor */ || isJSConstructor(container))) {
        return container;
      }
    }
  }
  function getFlowTypeFromCommonJSExport(symbol) {
    const file = getSourceFileOfNode(symbol.declarations[0]);
    const accessName = unescapeLeadingUnderscores(symbol.escapedName);
    const areAllModuleExports = symbol.declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression));
    const reference = areAllModuleExports ? factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("module"), factory.createIdentifier("exports")), accessName) : factory.createPropertyAccessExpression(factory.createIdentifier("exports"), accessName);
    if (areAllModuleExports) {
      setParent(reference.expression.expression, reference.expression);
    }
    setParent(reference.expression, reference);
    setParent(reference, file);
    reference.flowNode = file.endFlowNode;
    return getFlowTypeOfReference(reference, autoType, undefinedType);
  }
  function getFlowTypeInStaticBlocks(symbol, staticBlocks) {
    const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName);
    for (const staticBlock of staticBlocks) {
      const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName);
      setParent(reference.expression, reference);
      setParent(reference, staticBlock);
      reference.flowNode = staticBlock.returnFlowNode;
      const flowType = getFlowTypeOfProperty(reference, symbol);
      if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
        error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
      }
      if (everyType(flowType, isNullableType)) {
        continue;
      }
      return convertAutoToAny(flowType);
    }
  }
  function getFlowTypeInConstructor(symbol, constructor) {
    const accessName = startsWith(symbol.escapedName, "__#") ? factory.createPrivateIdentifier(symbol.escapedName.split("@")[1]) : unescapeLeadingUnderscores(symbol.escapedName);
    const reference = factory.createPropertyAccessExpression(factory.createThis(), accessName);
    setParent(reference.expression, reference);
    setParent(reference, constructor);
    reference.flowNode = constructor.returnFlowNode;
    const flowType = getFlowTypeOfProperty(reference, symbol);
    if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
      error(symbol.valueDeclaration, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
    }
    return everyType(flowType, isNullableType) ? void 0 : convertAutoToAny(flowType);
  }
  function getFlowTypeOfProperty(reference, prop) {
    const initialType = (prop == null ? void 0 : prop.valueDeclaration) && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & 128 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
    return getFlowTypeOfReference(reference, autoType, initialType);
  }
  function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
    const container = getAssignedExpandoInitializer(symbol.valueDeclaration);
    if (container) {
      const tag = isInJSFile(container) ? getJSDocTypeTag(container) : void 0;
      if (tag && tag.typeExpression) {
        return getTypeFromTypeNode(tag.typeExpression);
      }
      const containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
      return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
    }
    let type;
    let definedInConstructor = false;
    let definedInMethod = false;
    if (isConstructorDeclaredProperty(symbol)) {
      type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
    }
    if (!type) {
      let types;
      if (symbol.declarations) {
        let jsdocType;
        for (const declaration of symbol.declarations) {
          const expression = isBinaryExpression(declaration) || isCallExpression(declaration) ? declaration : isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : void 0;
          if (!expression) {
            continue;
          }
          const kind = isAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression);
          if (kind === 4 /* ThisProperty */ || isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
            if (isDeclarationInConstructor(expression)) {
              definedInConstructor = true;
            } else {
              definedInMethod = true;
            }
          }
          if (!isCallExpression(expression)) {
            jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
          }
          if (!jsdocType) {
            (types || (types = [])).push(isBinaryExpression(expression) || isCallExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
          }
        }
        type = jsdocType;
      }
      if (!type) {
        if (!length(types)) {
          return errorType;
        }
        let constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : void 0;
        if (definedInMethod) {
          const propType = getTypeOfPropertyInBaseClass(symbol);
          if (propType) {
            (constructorTypes || (constructorTypes = [])).push(propType);
            definedInConstructor = true;
          }
        }
        const sourceTypes = some(constructorTypes, (t) => !!(t.flags & ~98304 /* Nullable */)) ? constructorTypes : types;
        type = getUnionType(sourceTypes);
      }
    }
    const widened = getWidenedType(addOptionality(
      type,
      /*isProperty*/
      false,
      definedInMethod && !definedInConstructor
    ));
    if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) {
      reportImplicitAny(symbol.valueDeclaration, anyType);
      return anyType;
    }
    return widened;
  }
  function getJSContainerObjectType(decl, symbol, init) {
    var _a, _b;
    if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) {
      return void 0;
    }
    const exports2 = createSymbolTable();
    while (isBinaryExpression(decl) || isPropertyAccessExpression(decl)) {
      const s2 = getSymbolOfNode(decl);
      if ((_a = s2 == null ? void 0 : s2.exports) == null ? void 0 : _a.size) {
        mergeSymbolTable(exports2, s2.exports);
      }
      decl = isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
    }
    const s = getSymbolOfNode(decl);
    if ((_b = s == null ? void 0 : s.exports) == null ? void 0 : _b.size) {
      mergeSymbolTable(exports2, s.exports);
    }
    const type = createAnonymousType(symbol, exports2, emptyArray, emptyArray, emptyArray);
    type.objectFlags |= 4096 /* JSLiteral */;
    return type;
  }
  function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
    var _a;
    const typeNode = getEffectiveTypeAnnotationNode(expression.parent);
    if (typeNode) {
      const type = getWidenedType(getTypeFromTypeNode(typeNode));
      if (!declaredType) {
        return type;
      } else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) {
        errorNextVariableOrPropertyDeclarationMustHaveSameType(
          /*firstDeclaration*/
          void 0,
          declaredType,
          declaration,
          type
        );
      }
    }
    if ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) {
      const possiblyAnnotatedSymbol = getFunctionExpressionParentSymbolOrSymbol(symbol.parent);
      if (possiblyAnnotatedSymbol.valueDeclaration) {
        const typeNode2 = getEffectiveTypeAnnotationNode(possiblyAnnotatedSymbol.valueDeclaration);
        if (typeNode2) {
          const annotationSymbol = getPropertyOfType(getTypeFromTypeNode(typeNode2), symbol.escapedName);
          if (annotationSymbol) {
            return getNonMissingTypeOfSymbol(annotationSymbol);
          }
        }
      }
    }
    return declaredType;
  }
  function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
    if (isCallExpression(expression)) {
      if (resolvedSymbol) {
        return getTypeOfSymbol(resolvedSymbol);
      }
      const objectLitType = checkExpressionCached(expression.arguments[2]);
      const valueType = getTypeOfPropertyOfType(objectLitType, "value");
      if (valueType) {
        return valueType;
      }
      const getFunc = getTypeOfPropertyOfType(objectLitType, "get");
      if (getFunc) {
        const getSig = getSingleCallSignature(getFunc);
        if (getSig) {
          return getReturnTypeOfSignature(getSig);
        }
      }
      const setFunc = getTypeOfPropertyOfType(objectLitType, "set");
      if (setFunc) {
        const setSig = getSingleCallSignature(setFunc);
        if (setSig) {
          return getTypeOfFirstParameterOfSignature(setSig);
        }
      }
      return anyType;
    }
    if (containsSameNamedThisProperty(expression.left, expression.right)) {
      return anyType;
    }
    const isDirectExport = kind === 1 /* ExportsProperty */ && (isPropertyAccessExpression(expression.left) || isElementAccessExpression(expression.left)) && (isModuleExportsAccessExpression(expression.left.expression) || isIdentifier(expression.left.expression) && isExportsIdentifier(expression.left.expression));
    const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : isDirectExport ? getRegularTypeOfLiteralType(checkExpressionCached(expression.right)) : getWidenedLiteralType(checkExpressionCached(expression.right));
    if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) {
      const exportedType = resolveStructuredTypeMembers(type);
      const members = createSymbolTable();
      copyEntries(exportedType.members, members);
      const initialSize = members.size;
      if (resolvedSymbol && !resolvedSymbol.exports) {
        resolvedSymbol.exports = createSymbolTable();
      }
      (resolvedSymbol || symbol).exports.forEach((s, name) => {
        var _a;
        const exportedMember = members.get(name);
        if (exportedMember && exportedMember !== s && !(s.flags & 2097152 /* Alias */)) {
          if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
            if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) {
              const unescapedName = unescapeLeadingUnderscores(s.escapedName);
              const exportedMemberName = ((_a = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)) == null ? void 0 : _a.name) || exportedMember.valueDeclaration;
              addRelatedInfo(
                error(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName),
                createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)
              );
              addRelatedInfo(
                error(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName),
                createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)
              );
            }
            const union = createSymbol(s.flags | exportedMember.flags, name);
            union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
            union.valueDeclaration = exportedMember.valueDeclaration;
            union.declarations = concatenate(exportedMember.declarations, s.declarations);
            members.set(name, union);
          } else {
            members.set(name, mergeSymbol(s, exportedMember));
          }
        } else {
          members.set(name, s);
        }
      });
      const result = createAnonymousType(
        initialSize !== members.size ? void 0 : exportedType.symbol,
        // Only set the type's symbol if it looks to be the same as the original type
        members,
        exportedType.callSignatures,
        exportedType.constructSignatures,
        exportedType.indexInfos
      );
      if (initialSize === members.size) {
        if (type.aliasSymbol) {
          result.aliasSymbol = type.aliasSymbol;
          result.aliasTypeArguments = type.aliasTypeArguments;
        }
        if (getObjectFlags(type) & 4 /* Reference */) {
          result.aliasSymbol = type.symbol;
          const args = getTypeArguments(type);
          result.aliasTypeArguments = length(args) ? args : void 0;
        }
      }
      result.objectFlags |= getPropagatingFlagsOfTypes([type]) | getObjectFlags(type) & (4096 /* JSLiteral */ | 16384 /* ArrayLiteral */ | 128 /* ObjectLiteral */);
      if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
        result.objectFlags |= 16777216 /* IsClassInstanceClone */;
      }
      return result;
    }
    if (isEmptyArrayLiteralType(type)) {
      reportImplicitAny(expression, anyArrayType);
      return anyArrayType;
    }
    return type;
  }
  function containsSameNamedThisProperty(thisProperty, expression) {
    return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 110 /* ThisKeyword */ && forEachChildRecursively(expression, (n) => isMatchingReference(thisProperty, n));
  }
  function isDeclarationInConstructor(expression) {
    const thisContainer = getThisContainer(
      expression,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    return thisContainer.kind === 176 /* Constructor */ || thisContainer.kind === 262 /* FunctionDeclaration */ || thisContainer.kind === 218 /* FunctionExpression */ && !isPrototypePropertyAssignment(thisContainer.parent);
  }
  function getConstructorDefinedThisAssignmentTypes(types, declarations) {
    Debug.assert(types.length === declarations.length);
    return types.filter((_, i) => {
      const declaration = declarations[i];
      const expression = isBinaryExpression(declaration) ? declaration : isBinaryExpression(declaration.parent) ? declaration.parent : void 0;
      return expression && isDeclarationInConstructor(expression);
    });
  }
  function getTypeFromBindingElement(element, includePatternInType, reportErrors2) {
    if (element.initializer) {
      const contextualType = isBindingPattern(element.name) ? getTypeFromBindingPattern(
        element.name,
        /*includePatternInType*/
        true,
        /*reportErrors*/
        false
      ) : unknownType;
      return addOptionality(getWidenedLiteralTypeForInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType)));
    }
    if (isBindingPattern(element.name)) {
      return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors2);
    }
    if (reportErrors2 && !declarationBelongsToPrivateAmbientMember(element)) {
      reportImplicitAny(element, anyType);
    }
    return includePatternInType ? nonInferrableAnyType : anyType;
  }
  function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) {
    const members = createSymbolTable();
    let stringIndexInfo;
    let objectFlags = 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
    forEach(pattern.elements, (e) => {
      const name = e.propertyName || e.name;
      if (e.dotDotDotToken) {
        stringIndexInfo = createIndexInfo(
          stringType,
          anyType,
          /*isReadonly*/
          false
        );
        return;
      }
      const exprType = getLiteralTypeFromPropertyName(name);
      if (!isTypeUsableAsPropertyName(exprType)) {
        objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
        return;
      }
      const text = getPropertyNameFromType(exprType);
      const flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
      const symbol = createSymbol(flags, text);
      symbol.links.type = getTypeFromBindingElement(e, includePatternInType, reportErrors2);
      members.set(symbol.escapedName, symbol);
    });
    const result = createAnonymousType(
      /*symbol*/
      void 0,
      members,
      emptyArray,
      emptyArray,
      stringIndexInfo ? [stringIndexInfo] : emptyArray
    );
    result.objectFlags |= objectFlags;
    if (includePatternInType) {
      result.pattern = pattern;
      result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */;
    }
    return result;
  }
  function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2) {
    const elements = pattern.elements;
    const lastElement = lastOrUndefined(elements);
    const restElement = lastElement && lastElement.kind === 208 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : void 0;
    if (elements.length === 0 || elements.length === 1 && restElement) {
      return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
    }
    const elementTypes = map(elements, (e) => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors2));
    const minLength = findLastIndex(elements, (e) => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1;
    const elementFlags = map(elements, (e, i) => e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */);
    let result = createTupleType(elementTypes, elementFlags);
    if (includePatternInType) {
      result = cloneTypeReference(result);
      result.pattern = pattern;
      result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */;
    }
    return result;
  }
  function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors2 = false) {
    if (includePatternInType) contextualBindingPatterns.push(pattern);
    const result = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2);
    if (includePatternInType) contextualBindingPatterns.pop();
    return result;
  }
  function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors2) {
    return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(
      declaration,
      /*includeOptionality*/
      true,
      0 /* Normal */
    ), declaration, reportErrors2);
  }
  function getTypeFromImportAttributes(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const symbol = createSymbol(4096 /* ObjectLiteral */, "__importAttributes" /* ImportAttributes */);
      const members = createSymbolTable();
      forEach(node.elements, (attr) => {
        const member = createSymbol(4 /* Property */, getNameFromImportAttribute(attr));
        member.parent = symbol;
        member.links.type = checkImportAttribute(attr);
        member.links.target = member;
        members.set(member.escapedName, member);
      });
      const type = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
      type.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* NonInferrableType */;
      links.resolvedType = type;
    }
    return links.resolvedType;
  }
  function isGlobalSymbolConstructor(node) {
    const symbol = getSymbolOfNode(node);
    const globalSymbol = getGlobalESSymbolConstructorTypeSymbol(
      /*reportErrors*/
      false
    );
    return globalSymbol && symbol && symbol === globalSymbol;
  }
  function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors2) {
    if (type) {
      if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) {
        type = getESSymbolLikeTypeForNode(declaration);
      }
      if (reportErrors2) {
        reportErrorsFromWidening(declaration, type);
      }
      if (type.flags & 8192 /* UniqueESSymbol */ && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfDeclaration(declaration)) {
        type = esSymbolType;
      }
      return getWidenedType(type);
    }
    type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
    if (reportErrors2) {
      if (!declarationBelongsToPrivateAmbientMember(declaration)) {
        reportImplicitAny(declaration, type);
      }
    }
    return type;
  }
  function declarationBelongsToPrivateAmbientMember(declaration) {
    const root = getRootDeclaration(declaration);
    const memberDeclaration = root.kind === 169 /* Parameter */ ? root.parent : root;
    return isPrivateWithinAmbient(memberDeclaration);
  }
  function tryGetTypeFromEffectiveTypeNode(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
  }
  function isParameterOfContextSensitiveSignature(symbol) {
    let decl = symbol.valueDeclaration;
    if (!decl) {
      return false;
    }
    if (isBindingElement(decl)) {
      decl = walkUpBindingElementsAndPatterns(decl);
    }
    if (isParameter(decl)) {
      return isContextSensitiveFunctionOrObjectLiteralMethod(decl.parent);
    }
    return false;
  }
  function getTypeOfVariableOrParameterOrProperty(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
      if (!links.type && !isParameterOfContextSensitiveSignature(symbol)) {
        links.type = type;
      }
      return type;
    }
    return links.type;
  }
  function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
    if (symbol.flags & 4194304 /* Prototype */) {
      return getTypeOfPrototypeProperty(symbol);
    }
    if (symbol === requireSymbol) {
      return anyType;
    }
    if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) {
      const fileSymbol = getSymbolOfDeclaration(getSourceFileOfNode(symbol.valueDeclaration));
      const result = createSymbol(fileSymbol.flags, "exports");
      result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
      result.parent = symbol;
      result.links.target = fileSymbol;
      if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration;
      if (fileSymbol.members) result.members = new Map(fileSymbol.members);
      if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports);
      const members = createSymbolTable();
      members.set("exports", result);
      return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
    }
    Debug.assertIsDefined(symbol.valueDeclaration);
    const declaration = symbol.valueDeclaration;
    if (isSourceFile(declaration) && isJsonSourceFile(declaration)) {
      if (!declaration.statements.length) {
        return emptyObjectType;
      }
      return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
    }
    if (isAccessor(declaration)) {
      return getTypeOfAccessors(symbol);
    }
    if (!pushTypeResolution(symbol, 0 /* Type */)) {
      if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      return reportCircularityError(symbol);
    }
    let type;
    if (declaration.kind === 277 /* ExportAssignment */) {
      type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration);
    } else if (isBinaryExpression(declaration) || isInJSFile(declaration) && (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent))) {
      type = getWidenedTypeForAssignmentDeclaration(symbol);
    } else if (isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isIdentifier(declaration) || isStringLiteralLike(declaration) || isNumericLiteral(declaration) || isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration) || isMethodSignature(declaration) || isSourceFile(declaration)) {
      if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      type = isBinaryExpression(declaration.parent) ? getWidenedTypeForAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
    } else if (isPropertyAssignment(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
    } else if (isJsxAttribute(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
    } else if (isShorthandPropertyAssignment(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
    } else if (isObjectLiteralMethod(declaration)) {
      type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
    } else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) {
      type = getWidenedTypeForVariableLikeDeclaration(
        declaration,
        /*reportErrors*/
        true
      );
    } else if (isEnumDeclaration(declaration)) {
      type = getTypeOfFuncClassEnumModule(symbol);
    } else if (isEnumMember(declaration)) {
      type = getTypeOfEnumMember(symbol);
    } else {
      return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol));
    }
    if (!popTypeResolution()) {
      if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
        return getTypeOfFuncClassEnumModule(symbol);
      }
      return reportCircularityError(symbol);
    }
    return type;
  }
  function getAnnotatedAccessorTypeNode(accessor) {
    if (accessor) {
      switch (accessor.kind) {
        case 177 /* GetAccessor */:
          const getterTypeAnnotation = getEffectiveReturnTypeNode(accessor);
          return getterTypeAnnotation;
        case 178 /* SetAccessor */:
          const setterTypeAnnotation = getEffectiveSetAccessorTypeAnnotationNode(accessor);
          return setterTypeAnnotation;
        case 172 /* PropertyDeclaration */:
          Debug.assert(hasAccessorModifier(accessor));
          const accessorTypeAnnotation = getEffectiveTypeAnnotationNode(accessor);
          return accessorTypeAnnotation;
      }
    }
    return void 0;
  }
  function getAnnotatedAccessorType(accessor) {
    const node = getAnnotatedAccessorTypeNode(accessor);
    return node && getTypeFromTypeNode(node);
  }
  function getAnnotatedAccessorThisParameter(accessor) {
    const parameter = getAccessorThisParameter(accessor);
    return parameter && parameter.symbol;
  }
  function getThisTypeOfDeclaration(declaration) {
    return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
  }
  function getTypeOfAccessors(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        return errorType;
      }
      const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */);
      const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */);
      const accessor = tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration);
      let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && getWidenedTypeForVariableLikeDeclaration(
        accessor,
        /*reportErrors*/
        true
      );
      if (!type) {
        if (setter && !isPrivateWithinAmbient(setter)) {
          errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
        } else if (getter && !isPrivateWithinAmbient(getter)) {
          errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
        } else if (accessor && !isPrivateWithinAmbient(accessor)) {
          errorOrSuggestion(noImplicitAny, accessor, Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), "any");
        }
        type = anyType;
      }
      if (!popTypeResolution()) {
        if (getAnnotatedAccessorTypeNode(getter)) {
          error(getter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getAnnotatedAccessorTypeNode(setter)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getAnnotatedAccessorTypeNode(accessor)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        } else if (getter && noImplicitAny) {
          error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol));
        }
        type = anyType;
      }
      links.type ?? (links.type = type);
    }
    return links.type;
  }
  function getWriteTypeOfAccessors(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.writeType) {
      if (!pushTypeResolution(symbol, 7 /* WriteType */)) {
        return errorType;
      }
      const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration);
      let writeType = getAnnotatedAccessorType(setter);
      if (!popTypeResolution()) {
        if (getAnnotatedAccessorTypeNode(setter)) {
          error(setter, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        }
        writeType = anyType;
      }
      links.writeType ?? (links.writeType = writeType || getTypeOfAccessors(symbol));
    }
    return links.writeType;
  }
  function getBaseTypeVariableOfClass(symbol) {
    const baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
    return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : baseConstructorType.flags & 2097152 /* Intersection */ ? find(baseConstructorType.types, (t) => !!(t.flags & 8650752 /* TypeVariable */)) : void 0;
  }
  function getTypeOfFuncClassEnumModule(symbol) {
    let links = getSymbolLinks(symbol);
    const originalLinks = links;
    if (!links.type) {
      const expando = symbol.valueDeclaration && getSymbolOfExpando(
        symbol.valueDeclaration,
        /*allowDeclaration*/
        false
      );
      if (expando) {
        const merged = mergeJSSymbols(symbol, expando);
        if (merged) {
          symbol = merged;
          links = merged.links;
        }
      }
      originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
    }
    return links.type;
  }
  function getTypeOfFuncClassEnumModuleWorker(symbol) {
    const declaration = symbol.valueDeclaration;
    if (symbol.flags & 1536 /* Module */ && isShorthandAmbientModuleSymbol(symbol)) {
      return anyType;
    } else if (declaration && (declaration.kind === 226 /* BinaryExpression */ || isAccessExpression(declaration) && declaration.parent.kind === 226 /* BinaryExpression */)) {
      return getWidenedTypeForAssignmentDeclaration(symbol);
    } else if (symbol.flags & 512 /* ValueModule */ && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
      const resolvedModule = resolveExternalModuleSymbol(symbol);
      if (resolvedModule !== symbol) {
        if (!pushTypeResolution(symbol, 0 /* Type */)) {
          return errorType;
        }
        const exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
        const type2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? void 0 : resolvedModule);
        if (!popTypeResolution()) {
          return reportCircularityError(symbol);
        }
        return type2;
      }
    }
    const type = createObjectType(16 /* Anonymous */, symbol);
    if (symbol.flags & 32 /* Class */) {
      const baseTypeVariable = getBaseTypeVariableOfClass(symbol);
      return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
    } else {
      return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(
        type,
        /*isProperty*/
        true
      ) : type;
    }
  }
  function getTypeOfEnumMember(symbol) {
    const links = getSymbolLinks(symbol);
    return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
  }
  function getTypeOfAlias(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        return errorType;
      }
      const targetSymbol = resolveAlias(symbol);
      const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(
        getDeclarationOfAliasSymbol(symbol),
        /*dontRecursivelyResolve*/
        true
      );
      const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0);
      links.type ?? (links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType);
      if (!popTypeResolution()) {
        reportCircularityError(exportSymbol ?? symbol);
        return links.type ?? (links.type = errorType);
      }
    }
    return links.type;
  }
  function getTypeOfInstantiatedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    return links.type || (links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper));
  }
  function getWriteTypeOfInstantiatedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    return links.writeType || (links.writeType = instantiateType(getWriteTypeOfSymbol(links.target), links.mapper));
  }
  function reportCircularityError(symbol) {
    const declaration = symbol.valueDeclaration;
    if (declaration) {
      if (getEffectiveTypeAnnotationNode(declaration)) {
        error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
        return errorType;
      }
      if (noImplicitAny && (declaration.kind !== 169 /* Parameter */ || declaration.initializer)) {
        error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
      }
    } else if (symbol.flags & 2097152 /* Alias */) {
      const node = getDeclarationOfAliasSymbol(symbol);
      if (node) {
        error(node, Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
      }
    }
    return anyType;
  }
  function getTypeOfSymbolWithDeferredType(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      Debug.assertIsDefined(links.deferralParent);
      Debug.assertIsDefined(links.deferralConstituents);
      links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
    }
    return links.type;
  }
  function getWriteTypeOfSymbolWithDeferredType(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.writeType && links.deferralWriteConstituents) {
      Debug.assertIsDefined(links.deferralParent);
      Debug.assertIsDefined(links.deferralConstituents);
      links.writeType = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralWriteConstituents) : getIntersectionType(links.deferralWriteConstituents);
    }
    return links.writeType;
  }
  function getWriteTypeOfSymbol(symbol) {
    const checkFlags = getCheckFlags(symbol);
    if (symbol.flags & 4 /* Property */) {
      return checkFlags & 2 /* SyntheticProperty */ ? checkFlags & 65536 /* DeferredType */ ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : (
        // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty
        symbol.links.writeType || symbol.links.type
      ) : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */));
    }
    if (symbol.flags & 98304 /* Accessor */) {
      return checkFlags & 1 /* Instantiated */ ? getWriteTypeOfInstantiatedSymbol(symbol) : getWriteTypeOfAccessors(symbol);
    }
    return getTypeOfSymbol(symbol);
  }
  function getTypeOfSymbol(symbol) {
    const checkFlags = getCheckFlags(symbol);
    if (checkFlags & 65536 /* DeferredType */) {
      return getTypeOfSymbolWithDeferredType(symbol);
    }
    if (checkFlags & 1 /* Instantiated */) {
      return getTypeOfInstantiatedSymbol(symbol);
    }
    if (checkFlags & 262144 /* Mapped */) {
      return getTypeOfMappedSymbol(symbol);
    }
    if (checkFlags & 8192 /* ReverseMapped */) {
      return getTypeOfReverseMappedSymbol(symbol);
    }
    if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
      return getTypeOfVariableOrParameterOrProperty(symbol);
    }
    if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
      return getTypeOfFuncClassEnumModule(symbol);
    }
    if (symbol.flags & 8 /* EnumMember */) {
      return getTypeOfEnumMember(symbol);
    }
    if (symbol.flags & 98304 /* Accessor */) {
      return getTypeOfAccessors(symbol);
    }
    if (symbol.flags & 2097152 /* Alias */) {
      return getTypeOfAlias(symbol);
    }
    return errorType;
  }
  function getNonMissingTypeOfSymbol(symbol) {
    return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */));
  }
  function isReferenceToSomeType(type, targets) {
    if (type === void 0 || (getObjectFlags(type) & 4 /* Reference */) === 0) {
      return false;
    }
    for (const target of targets) {
      if (type.target === target) {
        return true;
      }
    }
    return false;
  }
  function isReferenceToType(type, target) {
    return type !== void 0 && target !== void 0 && (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target;
  }
  function getTargetType(type) {
    return getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
  }
  function hasBaseType(type, checkBase) {
    return check(type);
    function check(type2) {
      if (getObjectFlags(type2) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
        const target = getTargetType(type2);
        return target === checkBase || some(getBaseTypes(target), check);
      } else if (type2.flags & 2097152 /* Intersection */) {
        return some(type2.types, check);
      }
      return false;
    }
  }
  function appendTypeParameters(typeParameters, declarations) {
    for (const declaration of declarations) {
      typeParameters = appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(declaration)));
    }
    return typeParameters;
  }
  function getOuterTypeParameters(node, includeThisTypes) {
    while (true) {
      node = node.parent;
      if (node && isBinaryExpression(node)) {
        const assignmentKind = getAssignmentDeclarationKind(node);
        if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
          const symbol = getSymbolOfDeclaration(node.left);
          if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, (d) => node === d)) {
            node = symbol.parent.valueDeclaration;
          }
        }
      }
      if (!node) {
        return void 0;
      }
      const kind = node.kind;
      switch (kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */:
        case 264 /* InterfaceDeclaration */:
        case 179 /* CallSignature */:
        case 180 /* ConstructSignature */:
        case 173 /* MethodSignature */:
        case 184 /* FunctionType */:
        case 185 /* ConstructorType */:
        case 317 /* JSDocFunctionType */:
        case 262 /* FunctionDeclaration */:
        case 174 /* MethodDeclaration */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
        case 265 /* TypeAliasDeclaration */:
        case 345 /* JSDocTemplateTag */:
        case 346 /* JSDocTypedefTag */:
        case 340 /* JSDocEnumTag */:
        case 338 /* JSDocCallbackTag */:
        case 200 /* MappedType */:
        case 194 /* ConditionalType */: {
          const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
          if ((kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || isObjectLiteralMethod(node)) && isContextSensitive(node)) {
            const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* Call */));
            if (signature && signature.typeParameters) {
              return [...outerTypeParameters || emptyArray, ...signature.typeParameters];
            }
          }
          if (kind === 200 /* MappedType */) {
            return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter)));
          } else if (kind === 194 /* ConditionalType */) {
            return concatenate(outerTypeParameters, getInferTypeParameters(node));
          }
          const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node));
          const thisType = includeThisTypes && (kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType;
          return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
        }
        case 341 /* JSDocParameterTag */:
          const paramSymbol = getParameterSymbolFromJSDoc(node);
          if (paramSymbol) {
            node = paramSymbol.valueDeclaration;
          }
          break;
        case 320 /* JSDoc */: {
          const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
          return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, (t) => isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters;
        }
      }
    }
  }
  function getOuterTypeParametersOfClassOrInterface(symbol) {
    var _a;
    const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a = symbol.declarations) == null ? void 0 : _a.find((decl) => {
      if (decl.kind === 264 /* InterfaceDeclaration */) {
        return true;
      }
      if (decl.kind !== 260 /* VariableDeclaration */) {
        return false;
      }
      const initializer = decl.initializer;
      return !!initializer && (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 219 /* ArrowFunction */);
    });
    Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
    return getOuterTypeParameters(declaration);
  }
  function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
    if (!symbol.declarations) {
      return;
    }
    let result;
    for (const node of symbol.declarations) {
      if (node.kind === 264 /* InterfaceDeclaration */ || node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || isJSConstructor(node) || isTypeAlias(node)) {
        const declaration = node;
        result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration));
      }
    }
    return result;
  }
  function getTypeParametersOfClassOrInterface(symbol) {
    return concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
  }
  function isMixinConstructorType(type) {
    const signatures = getSignaturesOfType(type, 1 /* Construct */);
    if (signatures.length === 1) {
      const s = signatures[0];
      if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) {
        const paramType = getTypeOfParameter(s.parameters[0]);
        return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType;
      }
    }
    return false;
  }
  function isConstructorType(type) {
    if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
      return true;
    }
    if (type.flags & 8650752 /* TypeVariable */) {
      const constraint = getBaseConstraintOfType(type);
      return !!constraint && isMixinConstructorType(constraint);
    }
    return false;
  }
  function getBaseTypeNodeOfClass(type) {
    const decl = getClassLikeDeclarationOfSymbol(type.symbol);
    return decl && getEffectiveBaseTypeNode(decl);
  }
  function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
    const typeArgCount = length(typeArgumentNodes);
    const isJavascript = isInJSFile(location);
    return filter(getSignaturesOfType(type, 1 /* Construct */), (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters));
  }
  function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
    const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
    const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode);
    return sameMap(signatures, (sig) => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig);
  }
  function getBaseConstructorTypeOfClass(type) {
    if (!type.resolvedBaseConstructorType) {
      const decl = getClassLikeDeclarationOfSymbol(type.symbol);
      const extended = decl && getEffectiveBaseTypeNode(decl);
      const baseTypeNode = getBaseTypeNodeOfClass(type);
      if (!baseTypeNode) {
        return type.resolvedBaseConstructorType = undefinedType;
      }
      if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
        return errorType;
      }
      const baseConstructorType = checkExpression(baseTypeNode.expression);
      if (extended && baseTypeNode !== extended) {
        Debug.assert(!extended.typeArguments);
        checkExpression(extended.expression);
      }
      if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
        resolveStructuredTypeMembers(baseConstructorType);
      }
      if (!popTypeResolution()) {
        error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
        return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType);
      }
      if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
        const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
        if (baseConstructorType.flags & 262144 /* TypeParameter */) {
          const constraint = getConstraintFromTypeParameter(baseConstructorType);
          let ctorReturn = unknownType;
          if (constraint) {
            const ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
            if (ctorSig[0]) {
              ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
            }
          }
          if (baseConstructorType.symbol.declarations) {
            addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
          }
        }
        return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType);
      }
      type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = baseConstructorType);
    }
    return type.resolvedBaseConstructorType;
  }
  function getImplementsTypes(type) {
    let resolvedImplementsTypes = emptyArray;
    if (type.symbol.declarations) {
      for (const declaration of type.symbol.declarations) {
        const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration);
        if (!implementsTypeNodes) continue;
        for (const node of implementsTypeNodes) {
          const implementsType = getTypeFromTypeNode(node);
          if (!isErrorType(implementsType)) {
            if (resolvedImplementsTypes === emptyArray) {
              resolvedImplementsTypes = [implementsType];
            } else {
              resolvedImplementsTypes.push(implementsType);
            }
          }
        }
      }
    }
    return resolvedImplementsTypes;
  }
  function reportCircularBaseType(node, type) {
    error(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(
      type,
      /*enclosingDeclaration*/
      void 0,
      2 /* WriteArrayAsGenericType */
    ));
  }
  function getBaseTypes(type) {
    if (!type.baseTypesResolved) {
      if (pushTypeResolution(type, 6 /* ResolvedBaseTypes */)) {
        if (type.objectFlags & 8 /* Tuple */) {
          type.resolvedBaseTypes = [getTupleBaseType(type)];
        } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
          if (type.symbol.flags & 32 /* Class */) {
            resolveBaseTypesOfClass(type);
          }
          if (type.symbol.flags & 64 /* Interface */) {
            resolveBaseTypesOfInterface(type);
          }
        } else {
          Debug.fail("type must be class or interface");
        }
        if (!popTypeResolution() && type.symbol.declarations) {
          for (const declaration of type.symbol.declarations) {
            if (declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 264 /* InterfaceDeclaration */) {
              reportCircularBaseType(declaration, type);
            }
          }
        }
      }
      type.baseTypesResolved = true;
    }
    return type.resolvedBaseTypes;
  }
  function getTupleBaseType(type) {
    const elementTypes = sameMap(type.typeParameters, (t, i) => type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
    return createArrayType(getUnionType(elementTypes || emptyArray), type.readonly);
  }
  function resolveBaseTypesOfClass(type) {
    type.resolvedBaseTypes = resolvingEmptyArray;
    const baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
    if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
      return type.resolvedBaseTypes = emptyArray;
    }
    const baseTypeNode = getBaseTypeNodeOfClass(type);
    let baseType;
    const originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : void 0;
    if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) {
      baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
    } else if (baseConstructorType.flags & 1 /* Any */) {
      baseType = baseConstructorType;
    } else {
      const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
      if (!constructors.length) {
        error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
        return type.resolvedBaseTypes = emptyArray;
      }
      baseType = getReturnTypeOfSignature(constructors[0]);
    }
    if (isErrorType(baseType)) {
      return type.resolvedBaseTypes = emptyArray;
    }
    const reducedBaseType = getReducedType(baseType);
    if (!isValidBaseType(reducedBaseType)) {
      const elaboration = elaborateNeverIntersection(
        /*errorInfo*/
        void 0,
        baseType
      );
      const diagnostic = chainDiagnosticMessages(elaboration, Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType));
      diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(baseTypeNode.expression), baseTypeNode.expression, diagnostic));
      return type.resolvedBaseTypes = emptyArray;
    }
    if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
      error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(
        type,
        /*enclosingDeclaration*/
        void 0,
        2 /* WriteArrayAsGenericType */
      ));
      return type.resolvedBaseTypes = emptyArray;
    }
    if (type.resolvedBaseTypes === resolvingEmptyArray) {
      type.members = void 0;
    }
    return type.resolvedBaseTypes = [reducedBaseType];
  }
  function areAllOuterTypeParametersApplied(type) {
    const outerTypeParameters = type.outerTypeParameters;
    if (outerTypeParameters) {
      const last2 = outerTypeParameters.length - 1;
      const typeArguments = getTypeArguments(type);
      return outerTypeParameters[last2].symbol !== typeArguments[last2].symbol;
    }
    return true;
  }
  function isValidBaseType(type) {
    if (type.flags & 262144 /* TypeParameter */) {
      const constraint = getBaseConstraintOfType(type);
      if (constraint) {
        return isValidBaseType(constraint);
      }
    }
    return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || type.flags & 2097152 /* Intersection */ && every(type.types, isValidBaseType));
  }
  function resolveBaseTypesOfInterface(type) {
    type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
    if (type.symbol.declarations) {
      for (const declaration of type.symbol.declarations) {
        if (declaration.kind === 264 /* InterfaceDeclaration */ && getInterfaceBaseTypeNodes(declaration)) {
          for (const node of getInterfaceBaseTypeNodes(declaration)) {
            const baseType = getReducedType(getTypeFromTypeNode(node));
            if (!isErrorType(baseType)) {
              if (isValidBaseType(baseType)) {
                if (type !== baseType && !hasBaseType(baseType, type)) {
                  if (type.resolvedBaseTypes === emptyArray) {
                    type.resolvedBaseTypes = [baseType];
                  } else {
                    type.resolvedBaseTypes.push(baseType);
                  }
                } else {
                  reportCircularBaseType(declaration, type);
                }
              } else {
                error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
              }
            }
          }
        }
      }
    }
  }
  function isThislessInterface(symbol) {
    if (!symbol.declarations) {
      return true;
    }
    for (const declaration of symbol.declarations) {
      if (declaration.kind === 264 /* InterfaceDeclaration */) {
        if (declaration.flags & 256 /* ContainsThis */) {
          return false;
        }
        const baseTypeNodes = getInterfaceBaseTypeNodes(declaration);
        if (baseTypeNodes) {
          for (const node of baseTypeNodes) {
            if (isEntityNameExpression(node.expression)) {
              const baseSymbol = resolveEntityName(
                node.expression,
                788968 /* Type */,
                /*ignoreErrors*/
                true
              );
              if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
                return false;
              }
            }
          }
        }
      }
    }
    return true;
  }
  function getDeclaredTypeOfClassOrInterface(symbol) {
    let links = getSymbolLinks(symbol);
    const originalLinks = links;
    if (!links.declaredType) {
      const kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
      const merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration));
      if (merged) {
        symbol = merged;
        links = merged.links;
      }
      const type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
      const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
      const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
      if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
        type.objectFlags |= 4 /* Reference */;
        type.typeParameters = concatenate(outerTypeParameters, localTypeParameters);
        type.outerTypeParameters = outerTypeParameters;
        type.localTypeParameters = localTypeParameters;
        type.instantiations = /* @__PURE__ */ new Map();
        type.instantiations.set(getTypeListId(type.typeParameters), type);
        type.target = type;
        type.resolvedTypeArguments = type.typeParameters;
        type.thisType = createTypeParameter(symbol);
        type.thisType.isThisType = true;
        type.thisType.constraint = type;
      }
    }
    return links.declaredType;
  }
  function getDeclaredTypeOfTypeAlias(symbol) {
    var _a;
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
        return errorType;
      }
      const declaration = Debug.checkDefined((_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias), "Type alias symbol with no valid declaration found");
      const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
      let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
      if (popTypeResolution()) {
        const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
        if (typeParameters) {
          links.typeParameters = typeParameters;
          links.instantiations = /* @__PURE__ */ new Map();
          links.instantiations.set(getTypeListId(typeParameters), type);
        }
        if (type === intrinsicMarkerType && symbol.escapedName === "BuiltinIteratorReturn") {
          type = getBuiltinIteratorReturnType();
        }
      } else {
        type = errorType;
        if (declaration.kind === 340 /* JSDocEnumTag */) {
          error(declaration.typeExpression.type, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
        } else {
          error(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
        }
      }
      links.declaredType ?? (links.declaredType = type);
    }
    return links.declaredType;
  }
  function getBaseTypeOfEnumLikeType(type) {
    return type.flags & 1056 /* EnumLike */ && type.symbol.flags & 8 /* EnumMember */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
  }
  function getDeclaredTypeOfEnum(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      const memberTypeList = [];
      if (symbol.declarations) {
        for (const declaration of symbol.declarations) {
          if (declaration.kind === 266 /* EnumDeclaration */) {
            for (const member of declaration.members) {
              if (hasBindableName(member)) {
                const memberSymbol = getSymbolOfDeclaration(member);
                const value = getEnumMemberValue(member).value;
                const memberType = getFreshTypeOfLiteralType(
                  value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol)
                );
                getSymbolLinks(memberSymbol).declaredType = memberType;
                memberTypeList.push(getRegularTypeOfLiteralType(memberType));
              }
            }
          }
        }
      }
      const enumType = memberTypeList.length ? getUnionType(
        memberTypeList,
        1 /* Literal */,
        symbol,
        /*aliasTypeArguments*/
        void 0
      ) : createComputedEnumType(symbol);
      if (enumType.flags & 1048576 /* Union */) {
        enumType.flags |= 1024 /* EnumLiteral */;
        enumType.symbol = symbol;
      }
      links.declaredType = enumType;
    }
    return links.declaredType;
  }
  function createComputedEnumType(symbol) {
    const regularType = createTypeWithSymbol(32 /* Enum */, symbol);
    const freshType = createTypeWithSymbol(32 /* Enum */, symbol);
    regularType.regularType = regularType;
    regularType.freshType = freshType;
    freshType.regularType = regularType;
    freshType.freshType = freshType;
    return regularType;
  }
  function getDeclaredTypeOfEnumMember(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.declaredType) {
      const enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
      if (!links.declaredType) {
        links.declaredType = enumType;
      }
    }
    return links.declaredType;
  }
  function getDeclaredTypeOfTypeParameter(symbol) {
    const links = getSymbolLinks(symbol);
    return links.declaredType || (links.declaredType = createTypeParameter(symbol));
  }
  function getDeclaredTypeOfAlias(symbol) {
    const links = getSymbolLinks(symbol);
    return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
  }
  function getDeclaredTypeOfSymbol(symbol) {
    return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
  }
  function tryGetDeclaredTypeOfSymbol(symbol) {
    if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
      return getDeclaredTypeOfClassOrInterface(symbol);
    }
    if (symbol.flags & 524288 /* TypeAlias */) {
      return getDeclaredTypeOfTypeAlias(symbol);
    }
    if (symbol.flags & 262144 /* TypeParameter */) {
      return getDeclaredTypeOfTypeParameter(symbol);
    }
    if (symbol.flags & 384 /* Enum */) {
      return getDeclaredTypeOfEnum(symbol);
    }
    if (symbol.flags & 8 /* EnumMember */) {
      return getDeclaredTypeOfEnumMember(symbol);
    }
    if (symbol.flags & 2097152 /* Alias */) {
      return getDeclaredTypeOfAlias(symbol);
    }
    return void 0;
  }
  function isThislessType(node) {
    switch (node.kind) {
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 154 /* StringKeyword */:
      case 150 /* NumberKeyword */:
      case 163 /* BigIntKeyword */:
      case 136 /* BooleanKeyword */:
      case 155 /* SymbolKeyword */:
      case 151 /* ObjectKeyword */:
      case 116 /* VoidKeyword */:
      case 157 /* UndefinedKeyword */:
      case 146 /* NeverKeyword */:
      case 201 /* LiteralType */:
        return true;
      case 188 /* ArrayType */:
        return isThislessType(node.elementType);
      case 183 /* TypeReference */:
        return !node.typeArguments || node.typeArguments.every(isThislessType);
    }
    return false;
  }
  function isThislessTypeParameter(node) {
    const constraint = getEffectiveConstraintOfTypeParameter(node);
    return !constraint || isThislessType(constraint);
  }
  function isThislessVariableLikeDeclaration(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    return typeNode ? isThislessType(typeNode) : !hasInitializer(node);
  }
  function isThislessFunctionLikeDeclaration(node) {
    const returnType = getEffectiveReturnTypeNode(node);
    const typeParameters = getEffectiveTypeParameterDeclarations(node);
    return (node.kind === 176 /* Constructor */ || !!returnType && isThislessType(returnType)) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter);
  }
  function isThisless(symbol) {
    if (symbol.declarations && symbol.declarations.length === 1) {
      const declaration = symbol.declarations[0];
      if (declaration) {
        switch (declaration.kind) {
          case 172 /* PropertyDeclaration */:
          case 171 /* PropertySignature */:
            return isThislessVariableLikeDeclaration(declaration);
          case 174 /* MethodDeclaration */:
          case 173 /* MethodSignature */:
          case 176 /* Constructor */:
          case 177 /* GetAccessor */:
          case 178 /* SetAccessor */:
            return isThislessFunctionLikeDeclaration(declaration);
        }
      }
    }
    return false;
  }
  function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
    const result = createSymbolTable();
    for (const symbol of symbols) {
      result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
    }
    return result;
  }
  function addInheritedMembers(symbols, baseSymbols) {
    for (const base of baseSymbols) {
      if (isStaticPrivateIdentifierProperty(base)) {
        continue;
      }
      const derived = symbols.get(base.escapedName);
      if (!derived || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) && !isConstructorDeclaredProperty(derived) && !getContainingClassStaticBlock(derived.valueDeclaration)) {
        symbols.set(base.escapedName, base);
        symbols.set(base.escapedName, base);
      }
    }
  }
  function isStaticPrivateIdentifierProperty(s) {
    return !!s.valueDeclaration && isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && isStatic(s.valueDeclaration);
  }
  function resolveDeclaredMembers(type) {
    if (!type.declaredProperties) {
      const symbol = type.symbol;
      const members = getMembersOfSymbol(symbol);
      type.declaredProperties = getNamedMembers(members);
      type.declaredCallSignatures = emptyArray;
      type.declaredConstructSignatures = emptyArray;
      type.declaredIndexInfos = emptyArray;
      type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
      type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
      type.declaredIndexInfos = getIndexInfosOfSymbol(symbol);
    }
    return type;
  }
  function isLateBindableName(node) {
    return isLateBindableAST(node) && isTypeUsableAsPropertyName(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression));
  }
  function isLateBindableIndexSignature(node) {
    return isLateBindableAST(node) && isTypeUsableAsIndexSignature(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression));
  }
  function isLateBindableAST(node) {
    if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) {
      return false;
    }
    const expr = isComputedPropertyName(node) ? node.expression : node.argumentExpression;
    return isEntityNameExpression(expr);
  }
  function isTypeUsableAsIndexSignature(type) {
    return isTypeAssignableTo(type, stringNumberSymbolType);
  }
  function isLateBoundName(name) {
    return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) === 64 /* at */;
  }
  function hasLateBindableName(node) {
    const name = getNameOfDeclaration(node);
    return !!name && isLateBindableName(name);
  }
  function hasLateBindableIndexSignature(node) {
    const name = getNameOfDeclaration(node);
    return !!name && isLateBindableIndexSignature(name);
  }
  function hasBindableName(node) {
    return !hasDynamicName(node) || hasLateBindableName(node);
  }
  function isNonBindableDynamicName(node) {
    return isDynamicName(node) && !isLateBindableName(node);
  }
  function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
    Debug.assert(!!(getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
    symbol.flags |= symbolFlags;
    getSymbolLinks(member.symbol).lateSymbol = symbol;
    if (!symbol.declarations) {
      symbol.declarations = [member];
    } else if (!member.symbol.isReplaceableByMethod) {
      symbol.declarations.push(member);
    }
    if (symbolFlags & 111551 /* Value */) {
      if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
        symbol.valueDeclaration = member;
      }
    }
  }
  function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
    Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
    const links = getNodeLinks(decl);
    if (!links.resolvedSymbol) {
      links.resolvedSymbol = decl.symbol;
      const declName = isBinaryExpression(decl) ? decl.left : decl.name;
      const type = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
      if (isTypeUsableAsPropertyName(type)) {
        const memberName = getPropertyNameFromType(type);
        const symbolFlags = decl.symbol.flags;
        let lateSymbol = lateSymbols.get(memberName);
        if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
        const earlySymbol = earlySymbols && earlySymbols.get(memberName);
        if (!(parent.flags & 32 /* Class */) && lateSymbol.flags & getExcludedSymbolFlags(symbolFlags)) {
          const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
          const name = !(type.flags & 8192 /* UniqueESSymbol */) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName);
          forEach(declarations, (declaration) => error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name));
          error(declName || decl, Diagnostics.Duplicate_property_0, name);
          lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
        }
        lateSymbol.links.nameType = type;
        addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
        if (lateSymbol.parent) {
          Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
        } else {
          lateSymbol.parent = parent;
        }
        return links.resolvedSymbol = lateSymbol;
      }
    }
    return links.resolvedSymbol;
  }
  function lateBindIndexSignature(parent, earlySymbols, lateSymbols, decl) {
    let indexSymbol = lateSymbols.get("__index" /* Index */);
    if (!indexSymbol) {
      const early = earlySymbols == null ? void 0 : earlySymbols.get("__index" /* Index */);
      if (!early) {
        indexSymbol = createSymbol(0 /* None */, "__index" /* Index */, 4096 /* Late */);
      } else {
        indexSymbol = cloneSymbol(early);
        indexSymbol.links.checkFlags |= 4096 /* Late */;
      }
      lateSymbols.set("__index" /* Index */, indexSymbol);
    }
    if (!indexSymbol.declarations) {
      indexSymbol.declarations = [decl];
    } else if (!decl.symbol.isReplaceableByMethod) {
      indexSymbol.declarations.push(decl);
    }
  }
  function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
    const links = getSymbolLinks(symbol);
    if (!links[resolutionKind]) {
      const isStatic2 = resolutionKind === "resolvedExports" /* resolvedExports */;
      const earlySymbols = !isStatic2 ? symbol.members : symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol).exports : symbol.exports;
      links[resolutionKind] = earlySymbols || emptySymbols;
      const lateSymbols = createSymbolTable();
      for (const decl of symbol.declarations || emptyArray) {
        const members = getMembersOfDeclaration(decl);
        if (members) {
          for (const member of members) {
            if (isStatic2 === hasStaticModifier(member)) {
              if (hasLateBindableName(member)) {
                lateBindMember(symbol, earlySymbols, lateSymbols, member);
              } else if (hasLateBindableIndexSignature(member)) {
                lateBindIndexSignature(symbol, earlySymbols, lateSymbols, member);
              }
            }
          }
        }
      }
      const assignments = getFunctionExpressionParentSymbolOrSymbol(symbol).assignmentDeclarationMembers;
      if (assignments) {
        const decls = arrayFrom(assignments.values());
        for (const member of decls) {
          const assignmentKind = getAssignmentDeclarationKind(member);
          const isInstanceMember = assignmentKind === 3 /* PrototypeProperty */ || isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind) || assignmentKind === 9 /* ObjectDefinePrototypeProperty */ || assignmentKind === 6 /* Prototype */;
          if (isStatic2 === !isInstanceMember) {
            if (hasLateBindableName(member)) {
              lateBindMember(symbol, earlySymbols, lateSymbols, member);
            }
          }
        }
      }
      let resolved = combineSymbolTables(earlySymbols, lateSymbols);
      if (symbol.flags & 33554432 /* Transient */ && links.cjsExportMerged && symbol.declarations) {
        for (const decl of symbol.declarations) {
          const original = getSymbolLinks(decl.symbol)[resolutionKind];
          if (!resolved) {
            resolved = original;
            continue;
          }
          if (!original) continue;
          original.forEach((s, name) => {
            const existing = resolved.get(name);
            if (!existing) resolved.set(name, s);
            else if (existing === s) return;
            else resolved.set(name, mergeSymbol(existing, s));
          });
        }
      }
      links[resolutionKind] = resolved || emptySymbols;
    }
    return links[resolutionKind];
  }
  function getMembersOfSymbol(symbol) {
    return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */) : symbol.members || emptySymbols;
  }
  function getLateBoundSymbol(symbol) {
    if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
      const links = getSymbolLinks(symbol);
      if (!links.lateSymbol && some(symbol.declarations, hasLateBindableName)) {
        const parent = getMergedSymbol(symbol.parent);
        if (some(symbol.declarations, hasStaticModifier)) {
          getExportsOfSymbol(parent);
        } else {
          getMembersOfSymbol(parent);
        }
      }
      return links.lateSymbol || (links.lateSymbol = symbol);
    }
    return symbol;
  }
  function getTypeWithThisArgument(type, thisArgument, needApparentType) {
    if (getObjectFlags(type) & 4 /* Reference */) {
      const target = type.target;
      const typeArguments = getTypeArguments(type);
      return length(target.typeParameters) === length(typeArguments) ? createTypeReference(target, concatenate(typeArguments, [thisArgument || target.thisType])) : type;
    } else if (type.flags & 2097152 /* Intersection */) {
      const types = sameMap(type.types, (t) => getTypeWithThisArgument(t, thisArgument, needApparentType));
      return types !== type.types ? getIntersectionType(types) : type;
    }
    return needApparentType ? getApparentType(type) : type;
  }
  function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
    let mapper;
    let members;
    let callSignatures;
    let constructSignatures;
    let indexInfos;
    if (rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
      members = source.symbol ? getMembersOfSymbol(source.symbol) : createSymbolTable(source.declaredProperties);
      callSignatures = source.declaredCallSignatures;
      constructSignatures = source.declaredConstructSignatures;
      indexInfos = source.declaredIndexInfos;
    } else {
      mapper = createTypeMapper(typeParameters, typeArguments);
      members = createInstantiatedSymbolTable(
        source.declaredProperties,
        mapper,
        /*mappingThisOnly*/
        typeParameters.length === 1
      );
      callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
      constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
      indexInfos = instantiateIndexInfos(source.declaredIndexInfos, mapper);
    }
    const baseTypes = getBaseTypes(source);
    if (baseTypes.length) {
      if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
        const symbolTable = createSymbolTable(source.declaredProperties);
        const sourceIndex = getIndexSymbol(source.symbol);
        if (sourceIndex) {
          symbolTable.set("__index" /* Index */, sourceIndex);
        }
        members = symbolTable;
      }
      setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
      const thisArgument = lastOrUndefined(typeArguments);
      for (const baseType of baseTypes) {
        const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
        addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
        callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
        constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
        const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [anyBaseTypeIndexInfo];
        indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, (info) => !findIndexInfo(indexInfos, info.keyType)));
      }
    }
    setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos);
  }
  function resolveClassOrInterfaceMembers(type) {
    resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray);
  }
  function resolveTypeReferenceMembers(type) {
    const source = resolveDeclaredMembers(type.target);
    const typeParameters = concatenate(source.typeParameters, [source.thisType]);
    const typeArguments = getTypeArguments(type);
    const paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : concatenate(typeArguments, [type]);
    resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
  }
  function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
    const sig = new Signature5(checker, flags);
    sig.declaration = declaration;
    sig.typeParameters = typeParameters;
    sig.parameters = parameters;
    sig.thisParameter = thisParameter;
    sig.resolvedReturnType = resolvedReturnType;
    sig.resolvedTypePredicate = resolvedTypePredicate;
    sig.minArgumentCount = minArgumentCount;
    sig.resolvedMinArgumentCount = void 0;
    sig.target = void 0;
    sig.mapper = void 0;
    sig.compositeSignatures = void 0;
    sig.compositeKind = void 0;
    return sig;
  }
  function cloneSignature(sig) {
    const result = createSignature(
      sig.declaration,
      sig.typeParameters,
      sig.thisParameter,
      sig.parameters,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      sig.minArgumentCount,
      sig.flags & 167 /* PropagatingFlags */
    );
    result.target = sig.target;
    result.mapper = sig.mapper;
    result.compositeSignatures = sig.compositeSignatures;
    result.compositeKind = sig.compositeKind;
    return result;
  }
  function createUnionSignature(signature, unionSignatures) {
    const result = cloneSignature(signature);
    result.compositeSignatures = unionSignatures;
    result.compositeKind = 1048576 /* Union */;
    result.target = void 0;
    result.mapper = void 0;
    return result;
  }
  function getOptionalCallSignature(signature, callChainFlags) {
    if ((signature.flags & 24 /* CallChainFlags */) === callChainFlags) {
      return signature;
    }
    if (!signature.optionalCallSignatureCache) {
      signature.optionalCallSignatureCache = {};
    }
    const key = callChainFlags === 8 /* IsInnerCallChain */ ? "inner" : "outer";
    return signature.optionalCallSignatureCache[key] || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
  }
  function createOptionalCallSignature(signature, callChainFlags) {
    Debug.assert(callChainFlags === 8 /* IsInnerCallChain */ || callChainFlags === 16 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
    const result = cloneSignature(signature);
    result.flags |= callChainFlags;
    return result;
  }
  function getExpandedParameters(sig, skipUnionExpanding) {
    if (signatureHasRestParameter(sig)) {
      const restIndex = sig.parameters.length - 1;
      const restSymbol = sig.parameters[restIndex];
      const restType = getTypeOfSymbol(restSymbol);
      if (isTupleType(restType)) {
        return [expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol)];
      } else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) {
        return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restSymbol));
      }
    }
    return [sig.parameters];
    function expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol) {
      const elementTypes = getTypeArguments(restType);
      const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restSymbol);
      const restParams = map(elementTypes, (t, i) => {
        const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType);
        const flags = restType.target.elementFlags[i];
        const checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ : flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
        const symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
        symbol.links.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
        return symbol;
      });
      return concatenate(sig.parameters.slice(0, restIndex), restParams);
    }
    function getUniqAssociatedNamesFromTupleType(type, restSymbol) {
      const names = map(type.target.labeledElementDeclarations, (labeledElement, i) => getTupleElementLabel(labeledElement, i, type.target.elementFlags[i], restSymbol));
      if (names) {
        const duplicates = [];
        const uniqueNames = /* @__PURE__ */ new Set();
        for (let i = 0; i < names.length; i++) {
          const name = names[i];
          if (!tryAddToSet(uniqueNames, name)) {
            duplicates.push(i);
          }
        }
        const counters = /* @__PURE__ */ new Map();
        for (const i of duplicates) {
          let counter = counters.get(names[i]) ?? 1;
          let name;
          while (!tryAddToSet(uniqueNames, name = `${names[i]}_${counter}`)) {
            counter++;
          }
          names[i] = name;
          counters.set(names[i], counter + 1);
        }
      }
      return names;
    }
  }
  function getDefaultConstructSignatures(classType) {
    const baseConstructorType = getBaseConstructorTypeOfClass(classType);
    const baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
    const declaration = getClassLikeDeclarationOfSymbol(classType.symbol);
    const isAbstract = !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */);
    if (baseSignatures.length === 0) {
      return [createSignature(
        /*declaration*/
        void 0,
        classType.localTypeParameters,
        /*thisParameter*/
        void 0,
        emptyArray,
        classType,
        /*resolvedTypePredicate*/
        void 0,
        0,
        isAbstract ? 4 /* Abstract */ : 0 /* None */
      )];
    }
    const baseTypeNode = getBaseTypeNodeOfClass(classType);
    const isJavaScript = isInJSFile(baseTypeNode);
    const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
    const typeArgCount = length(typeArguments);
    const result = [];
    for (const baseSig of baseSignatures) {
      const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
      const typeParamCount = length(baseSig.typeParameters);
      if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
        const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
        sig.typeParameters = classType.localTypeParameters;
        sig.resolvedReturnType = classType;
        sig.flags = isAbstract ? sig.flags | 4 /* Abstract */ : sig.flags & ~4 /* Abstract */;
        result.push(sig);
      }
    }
    return result;
  }
  function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
    for (const s of signatureList) {
      if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
        return s;
      }
    }
  }
  function findMatchingSignatures(signatureLists, signature, listIndex) {
    if (signature.typeParameters) {
      if (listIndex > 0) {
        return void 0;
      }
      for (let i = 1; i < signatureLists.length; i++) {
        if (!findMatchingSignature(
          signatureLists[i],
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          false
        )) {
          return void 0;
        }
      }
      return [signature];
    }
    let result;
    for (let i = 0; i < signatureLists.length; i++) {
      const match = i === listIndex ? signature : findMatchingSignature(
        signatureLists[i],
        signature,
        /*partialMatch*/
        false,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        true
      ) || findMatchingSignature(
        signatureLists[i],
        signature,
        /*partialMatch*/
        true,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        true
      );
      if (!match) {
        return void 0;
      }
      result = appendIfUnique(result, match);
    }
    return result;
  }
  function getUnionSignatures(signatureLists) {
    let result;
    let indexWithLengthOverOne;
    for (let i = 0; i < signatureLists.length; i++) {
      if (signatureLists[i].length === 0) return emptyArray;
      if (signatureLists[i].length > 1) {
        indexWithLengthOverOne = indexWithLengthOverOne === void 0 ? i : -1;
      }
      for (const signature of signatureLists[i]) {
        if (!result || !findMatchingSignature(
          result,
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          true
        )) {
          const unionSignatures = findMatchingSignatures(signatureLists, signature, i);
          if (unionSignatures) {
            let s = signature;
            if (unionSignatures.length > 1) {
              let thisParameter = signature.thisParameter;
              const firstThisParameterOfUnionSignatures = forEach(unionSignatures, (sig) => sig.thisParameter);
              if (firstThisParameterOfUnionSignatures) {
                const thisType = getIntersectionType(mapDefined(unionSignatures, (sig) => sig.thisParameter && getTypeOfSymbol(sig.thisParameter)));
                thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
              }
              s = createUnionSignature(signature, unionSignatures);
              s.thisParameter = thisParameter;
            }
            (result || (result = [])).push(s);
          }
        }
      }
    }
    if (!length(result) && indexWithLengthOverOne !== -1) {
      const masterList = signatureLists[indexWithLengthOverOne !== void 0 ? indexWithLengthOverOne : 0];
      let results = masterList.slice();
      for (const signatures of signatureLists) {
        if (signatures !== masterList) {
          const signature = signatures[0];
          Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
          results = !!signature.typeParameters && some(results, (s) => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? void 0 : map(results, (sig) => combineSignaturesOfUnionMembers(sig, signature));
          if (!results) {
            break;
          }
        }
      }
      result = results;
    }
    return result || emptyArray;
  }
  function compareTypeParametersIdentical(sourceParams, targetParams) {
    if (length(sourceParams) !== length(targetParams)) {
      return false;
    }
    if (!sourceParams || !targetParams) {
      return true;
    }
    const mapper = createTypeMapper(targetParams, sourceParams);
    for (let i = 0; i < sourceParams.length; i++) {
      const source = sourceParams[i];
      const target = targetParams[i];
      if (source === target) continue;
      if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) return false;
    }
    return true;
  }
  function combineUnionThisParam(left, right, mapper) {
    if (!left || !right) {
      return left || right;
    }
    const thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
    return createSymbolWithType(left, thisType);
  }
  function combineUnionParameters(left, right, mapper) {
    const leftCount = getParameterCount(left);
    const rightCount = getParameterCount(right);
    const longest = leftCount >= rightCount ? left : right;
    const shorter = longest === left ? right : left;
    const longestCount = longest === left ? leftCount : rightCount;
    const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right);
    const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
    const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
    for (let i = 0; i < longestCount; i++) {
      let longestParamType = tryGetTypeAtPosition(longest, i);
      if (longest === right) {
        longestParamType = instantiateType(longestParamType, mapper);
      }
      let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
      if (shorter === right) {
        shorterParamType = instantiateType(shorterParamType, mapper);
      }
      const unionParamType = getIntersectionType([longestParamType, shorterParamType]);
      const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1;
      const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
      const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i);
      const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i);
      const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0;
      const paramSymbol = createSymbol(
        1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0),
        paramName || `arg${i}`,
        isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0
      );
      paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
      params[i] = paramSymbol;
    }
    if (needsExtraRestElement) {
      const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* RestParameter */);
      restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount));
      if (shorter === right) {
        restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper);
      }
      params[longestCount] = restParamSymbol;
    }
    return params;
  }
  function combineSignaturesOfUnionMembers(left, right) {
    const typeParams = left.typeParameters || right.typeParameters;
    let paramMapper;
    if (left.typeParameters && right.typeParameters) {
      paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
    }
    let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */);
    const declaration = left.declaration;
    const params = combineUnionParameters(left, right, paramMapper);
    const lastParam = lastOrUndefined(params);
    if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) {
      flags |= 1 /* HasRestParameter */;
    }
    const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper);
    const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
    const result = createSignature(
      declaration,
      typeParams,
      thisParam,
      params,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      minArgCount,
      flags
    );
    result.compositeKind = 1048576 /* Union */;
    result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]);
    if (paramMapper) {
      result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
    } else if (left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures) {
      result.mapper = left.mapper;
    }
    return result;
  }
  function getUnionIndexInfos(types) {
    const sourceInfos = getIndexInfosOfType(types[0]);
    if (sourceInfos) {
      const result = [];
      for (const info of sourceInfos) {
        const indexType = info.keyType;
        if (every(types, (t) => !!getIndexInfoOfType(t, indexType))) {
          result.push(createIndexInfo(indexType, getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly)));
        }
      }
      return result;
    }
    return emptyArray;
  }
  function resolveUnionTypeMembers(type) {
    const callSignatures = getUnionSignatures(map(type.types, (t) => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */)));
    const constructSignatures = getUnionSignatures(map(type.types, (t) => getSignaturesOfType(t, 1 /* Construct */)));
    const indexInfos = getUnionIndexInfos(type.types);
    setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, indexInfos);
  }
  function intersectTypes(type1, type2) {
    return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
  }
  function findMixins(types) {
    const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, 1 /* Construct */).length > 0);
    const mixinFlags = map(types, isMixinConstructorType);
    if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) {
      const firstMixinIndex = mixinFlags.indexOf(
        /*searchElement*/
        true
      );
      mixinFlags[firstMixinIndex] = false;
    }
    return mixinFlags;
  }
  function includeMixinType(type, types, mixinFlags, index) {
    const mixedTypes = [];
    for (let i = 0; i < types.length; i++) {
      if (i === index) {
        mixedTypes.push(type);
      } else if (mixinFlags[i]) {
        mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
      }
    }
    return getIntersectionType(mixedTypes);
  }
  function resolveIntersectionTypeMembers(type) {
    let callSignatures;
    let constructSignatures;
    let indexInfos;
    const types = type.types;
    const mixinFlags = findMixins(types);
    const mixinCount = countWhere(mixinFlags, (b) => b);
    for (let i = 0; i < types.length; i++) {
      const t = type.types[i];
      if (!mixinFlags[i]) {
        let signatures = getSignaturesOfType(t, 1 /* Construct */);
        if (signatures.length && mixinCount > 0) {
          signatures = map(signatures, (s) => {
            const clone = cloneSignature(s);
            clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
            return clone;
          });
        }
        constructSignatures = appendSignatures(constructSignatures, signatures);
      }
      callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
      indexInfos = reduceLeft(getIndexInfosOfType(t), (infos, newInfo) => appendIndexInfo(
        infos,
        newInfo,
        /*union*/
        false
      ), indexInfos);
    }
    setStructuredTypeMembers(type, emptySymbols, callSignatures || emptyArray, constructSignatures || emptyArray, indexInfos || emptyArray);
  }
  function appendSignatures(signatures, newSignatures) {
    for (const sig of newSignatures) {
      if (!signatures || every(signatures, (s) => !compareSignaturesIdentical(
        s,
        sig,
        /*partialMatch*/
        false,
        /*ignoreThisTypes*/
        false,
        /*ignoreReturnTypes*/
        false,
        compareTypesIdentical
      ))) {
        signatures = append(signatures, sig);
      }
    }
    return signatures;
  }
  function appendIndexInfo(indexInfos, newInfo, union) {
    if (indexInfos) {
      for (let i = 0; i < indexInfos.length; i++) {
        const info = indexInfos[i];
        if (info.keyType === newInfo.keyType) {
          indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly);
          return indexInfos;
        }
      }
    }
    return append(indexInfos, newInfo);
  }
  function resolveAnonymousTypeMembers(type) {
    if (type.target) {
      setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
      const members2 = createInstantiatedSymbolTable(
        getPropertiesOfObjectType(type.target),
        type.mapper,
        /*mappingThisOnly*/
        false
      );
      const callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
      const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
      const indexInfos2 = instantiateIndexInfos(getIndexInfosOfType(type.target), type.mapper);
      setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2);
      return;
    }
    const symbol = getMergedSymbol(type.symbol);
    if (symbol.flags & 2048 /* TypeLiteral */) {
      setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
      const members2 = getMembersOfSymbol(symbol);
      const callSignatures = getSignaturesOfSymbol(members2.get("__call" /* Call */));
      const constructSignatures = getSignaturesOfSymbol(members2.get("__new" /* New */));
      const indexInfos2 = getIndexInfosOfSymbol(symbol);
      setStructuredTypeMembers(type, members2, callSignatures, constructSignatures, indexInfos2);
      return;
    }
    let members = getExportsOfSymbol(symbol);
    let indexInfos;
    if (symbol === globalThisSymbol) {
      const varsOnly = /* @__PURE__ */ new Map();
      members.forEach((p) => {
        var _a;
        if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) {
          varsOnly.set(p.escapedName, p);
        }
      });
      members = varsOnly;
    }
    let baseConstructorIndexInfo;
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, emptyArray);
    if (symbol.flags & 32 /* Class */) {
      const classType = getDeclaredTypeOfClassOrInterface(symbol);
      const baseConstructorType = getBaseConstructorTypeOfClass(classType);
      if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
        members = createSymbolTable(getNamedOrIndexSignatureMembers(members));
        addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
      } else if (baseConstructorType === anyType) {
        baseConstructorIndexInfo = anyBaseTypeIndexInfo;
      }
    }
    const indexSymbol = getIndexSymbolFromSymbolTable(members);
    if (indexSymbol) {
      indexInfos = getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(members.values()));
    } else {
      if (baseConstructorIndexInfo) {
        indexInfos = append(indexInfos, baseConstructorIndexInfo);
      }
      if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || some(type.properties, (prop) => !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */)))) {
        indexInfos = append(indexInfos, enumNumberIndexInfo);
      }
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray);
    if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
      type.callSignatures = getSignaturesOfSymbol(symbol);
    }
    if (symbol.flags & 32 /* Class */) {
      const classType = getDeclaredTypeOfClassOrInterface(symbol);
      let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : emptyArray;
      if (symbol.flags & 16 /* Function */) {
        constructSignatures = addRange(
          constructSignatures.slice(),
          mapDefined(
            type.callSignatures,
            (sig) => isJSConstructor(sig.declaration) ? createSignature(
              sig.declaration,
              sig.typeParameters,
              sig.thisParameter,
              sig.parameters,
              classType,
              /*resolvedTypePredicate*/
              void 0,
              sig.minArgumentCount,
              sig.flags & 167 /* PropagatingFlags */
            ) : void 0
          )
        );
      }
      if (!constructSignatures.length) {
        constructSignatures = getDefaultConstructSignatures(classType);
      }
      type.constructSignatures = constructSignatures;
    }
  }
  function replaceIndexedAccess(instantiable, type, replacement) {
    return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getNumberLiteralType(0), createTupleType([replacement])]));
  }
  function getLimitedConstraint(type) {
    const constraint = getConstraintTypeFromMappedType(type.mappedType);
    if (!(constraint.flags & 1048576 /* Union */ || constraint.flags & 2097152 /* Intersection */)) {
      return;
    }
    const origin = constraint.flags & 1048576 /* Union */ ? constraint.origin : constraint;
    if (!origin || !(origin.flags & 2097152 /* Intersection */)) {
      return;
    }
    const limitedConstraint = getIntersectionType(origin.types.filter((t) => t !== type.constraintType));
    return limitedConstraint !== neverType ? limitedConstraint : void 0;
  }
  function resolveReverseMappedTypeMembers(type) {
    const indexInfo = getIndexInfoOfType(type.source, stringType);
    const modifiers = getMappedTypeModifiers(type.mappedType);
    const readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
    const optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
    const indexInfos = indexInfo ? [createIndexInfo(stringType, inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType) || unknownType, readonlyMask && indexInfo.isReadonly)] : emptyArray;
    const members = createSymbolTable();
    const limitedConstraint = getLimitedConstraint(type);
    for (const prop of getPropertiesOfType(type.source)) {
      if (limitedConstraint) {
        const propertyNameType = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */);
        if (!isTypeAssignableTo(propertyNameType, limitedConstraint)) {
          continue;
        }
      }
      const checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
      const inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
      inferredProp.declarations = prop.declarations;
      inferredProp.links.nameType = getSymbolLinks(prop).nameType;
      inferredProp.links.propertyType = getTypeOfSymbol(prop);
      if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) {
        const newTypeParam = type.constraintType.type.objectType;
        const newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam);
        inferredProp.links.mappedType = newMappedType;
        inferredProp.links.constraintType = getIndexType(newTypeParam);
      } else {
        inferredProp.links.mappedType = type.mappedType;
        inferredProp.links.constraintType = type.constraintType;
      }
      members.set(prop.escapedName, inferredProp);
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos);
  }
  function getLowerBoundOfKeyType(type) {
    if (type.flags & 4194304 /* Index */) {
      const t = getApparentType(type.type);
      return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
    }
    if (type.flags & 16777216 /* Conditional */) {
      if (type.root.isDistributive) {
        const checkType = type.checkType;
        const constraint = getLowerBoundOfKeyType(checkType);
        if (constraint !== checkType) {
          return getConditionalTypeInstantiation(
            type,
            prependTypeMapping(type.root.checkType, constraint, type.mapper),
            /*forConstraint*/
            false
          );
        }
      }
      return type;
    }
    if (type.flags & 1048576 /* Union */) {
      return mapType(
        type,
        getLowerBoundOfKeyType,
        /*noReductions*/
        true
      );
    }
    if (type.flags & 2097152 /* Intersection */) {
      const types = type.types;
      if (types.length === 2 && !!(types[0].flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */)) && types[1] === emptyTypeLiteralType) {
        return type;
      }
      return getIntersectionType(sameMap(type.types, getLowerBoundOfKeyType));
    }
    return type;
  }
  function getIsLateCheckFlag(s) {
    return getCheckFlags(s) & 4096 /* Late */;
  }
  function forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(type, include, stringsOnly, cb) {
    for (const prop of getPropertiesOfType(type)) {
      cb(getLiteralTypeFromProperty(prop, include));
    }
    if (type.flags & 1 /* Any */) {
      cb(stringType);
    } else {
      for (const info of getIndexInfosOfType(type)) {
        if (!stringsOnly || info.keyType.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
          cb(info.keyType);
        }
      }
    }
  }
  function resolveMappedTypeMembers(type) {
    const members = createSymbolTable();
    let indexInfos;
    setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray);
    const typeParameter = getTypeParameterFromMappedType(type);
    const constraintType = getConstraintTypeFromMappedType(type);
    const mappedType = type.target || type;
    const nameType = getNameTypeFromMappedType(mappedType);
    const shouldLinkPropDeclarations = getMappedTypeNameTypeKind(mappedType) !== 2 /* Remapping */;
    const templateType = getTemplateTypeFromMappedType(mappedType);
    const modifiersType = getApparentType(getModifiersTypeFromMappedType(type));
    const templateModifiers = getMappedTypeModifiers(type);
    const include = 8576 /* StringOrNumberLiteralOrUnique */;
    if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
      forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(
        modifiersType,
        include,
        /*stringsOnly*/
        false,
        addMemberForKeyType
      );
    } else {
      forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
    }
    setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray);
    function addMemberForKeyType(keyType) {
      const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
      forEachType(propNameType, (t) => addMemberForKeyTypeWorker(keyType, t));
    }
    function addMemberForKeyTypeWorker(keyType, propNameType) {
      if (isTypeUsableAsPropertyName(propNameType)) {
        const propName = getPropertyNameFromType(propNameType);
        const existingProp = members.get(propName);
        if (existingProp) {
          existingProp.links.nameType = getUnionType([existingProp.links.nameType, propNameType]);
          existingProp.links.keyType = getUnionType([existingProp.links.keyType, keyType]);
        } else {
          const modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : void 0;
          const isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
          const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
          const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
          const lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0;
          const prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
          prop.links.mappedType = type;
          prop.links.nameType = propNameType;
          prop.links.keyType = keyType;
          if (modifiersProp) {
            prop.links.syntheticOrigin = modifiersProp;
            prop.declarations = shouldLinkPropDeclarations ? modifiersProp.declarations : void 0;
          }
          members.set(propName, prop);
        }
      } else if (isValidIndexKeyType(propNameType) || propNameType.flags & (1 /* Any */ | 32 /* Enum */)) {
        const indexKeyType = propNameType.flags & (1 /* Any */ | 4 /* String */) ? stringType : propNameType.flags & (8 /* Number */ | 32 /* Enum */) ? numberType : propNameType;
        const propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
        const modifiersIndexInfo = getApplicableIndexInfo(modifiersType, propNameType);
        const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && (modifiersIndexInfo == null ? void 0 : modifiersIndexInfo.isReadonly));
        const indexInfo = createIndexInfo(indexKeyType, propType, isReadonly);
        indexInfos = appendIndexInfo(
          indexInfos,
          indexInfo,
          /*union*/
          true
        );
      }
    }
  }
  function getTypeOfMappedSymbol(symbol) {
    var _a;
    if (!symbol.links.type) {
      const mappedType = symbol.links.mappedType;
      if (!pushTypeResolution(symbol, 0 /* Type */)) {
        mappedType.containsError = true;
        return errorType;
      }
      const templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
      const mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.links.keyType);
      const propType = instantiateType(templateType, mapper);
      let type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(
        propType,
        /*isProperty*/
        true
      ) : symbol.links.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) : propType;
      if (!popTypeResolution()) {
        error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
        type = errorType;
      }
      (_a = symbol.links).type ?? (_a.type = type);
    }
    return symbol.links.type;
  }
  function getTypeParameterFromMappedType(type) {
    return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(type.declaration.typeParameter)));
  }
  function getConstraintTypeFromMappedType(type) {
    return type.constraintType || (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
  }
  function getNameTypeFromMappedType(type) {
    return type.declaration.nameType ? type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) : void 0;
  }
  function getTemplateTypeFromMappedType(type) {
    return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality(
      getTypeFromTypeNode(type.declaration.type),
      /*isProperty*/
      true,
      !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)
    ), type.mapper) : errorType);
  }
  function getConstraintDeclarationForMappedType(type) {
    return getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
  }
  function isMappedTypeWithKeyofConstraintDeclaration(type) {
    const constraintDeclaration = getConstraintDeclarationForMappedType(type);
    return constraintDeclaration.kind === 198 /* TypeOperator */ && constraintDeclaration.operator === 143 /* KeyOfKeyword */;
  }
  function getModifiersTypeFromMappedType(type) {
    if (!type.modifiersType) {
      if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
        type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
      } else {
        const declaredType = getTypeFromMappedTypeNode(type.declaration);
        const constraint = getConstraintTypeFromMappedType(declaredType);
        const extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
        type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
      }
    }
    return type.modifiersType;
  }
  function getMappedTypeModifiers(type) {
    const declaration = type.declaration;
    return (declaration.readonlyToken ? declaration.readonlyToken.kind === 41 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) | (declaration.questionToken ? declaration.questionToken.kind === 41 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
  }
  function getMappedTypeOptionality(type) {
    const modifiers = getMappedTypeModifiers(type);
    return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
  }
  function getCombinedMappedTypeOptionality(type) {
    if (getObjectFlags(type) & 32 /* Mapped */) {
      return getMappedTypeOptionality(type) || getCombinedMappedTypeOptionality(getModifiersTypeFromMappedType(type));
    }
    if (type.flags & 2097152 /* Intersection */) {
      const optionality = getCombinedMappedTypeOptionality(type.types[0]);
      return every(type.types, (t, i) => i === 0 || getCombinedMappedTypeOptionality(t) === optionality) ? optionality : 0;
    }
    return 0;
  }
  function isPartialMappedType(type) {
    return !!(getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
  }
  function isGenericMappedType(type) {
    if (getObjectFlags(type) & 32 /* Mapped */) {
      const constraint = getConstraintTypeFromMappedType(type);
      if (isGenericIndexType(constraint)) {
        return true;
      }
      const nameType = getNameTypeFromMappedType(type);
      if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) {
        return true;
      }
    }
    return false;
  }
  function getMappedTypeNameTypeKind(type) {
    const nameType = getNameTypeFromMappedType(type);
    if (!nameType) {
      return 0 /* None */;
    }
    return isTypeAssignableTo(nameType, getTypeParameterFromMappedType(type)) ? 1 /* Filtering */ : 2 /* Remapping */;
  }
  function resolveStructuredTypeMembers(type) {
    if (!type.members) {
      if (type.flags & 524288 /* Object */) {
        if (type.objectFlags & 4 /* Reference */) {
          resolveTypeReferenceMembers(type);
        } else if (type.objectFlags & 3 /* ClassOrInterface */) {
          resolveClassOrInterfaceMembers(type);
        } else if (type.objectFlags & 1024 /* ReverseMapped */) {
          resolveReverseMappedTypeMembers(type);
        } else if (type.objectFlags & 16 /* Anonymous */) {
          resolveAnonymousTypeMembers(type);
        } else if (type.objectFlags & 32 /* Mapped */) {
          resolveMappedTypeMembers(type);
        } else {
          Debug.fail("Unhandled object type " + Debug.formatObjectFlags(type.objectFlags));
        }
      } else if (type.flags & 1048576 /* Union */) {
        resolveUnionTypeMembers(type);
      } else if (type.flags & 2097152 /* Intersection */) {
        resolveIntersectionTypeMembers(type);
      } else {
        Debug.fail("Unhandled type " + Debug.formatTypeFlags(type.flags));
      }
    }
    return type;
  }
  function getPropertiesOfObjectType(type) {
    if (type.flags & 524288 /* Object */) {
      return resolveStructuredTypeMembers(type).properties;
    }
    return emptyArray;
  }
  function getPropertyOfObjectType(type, name) {
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      const symbol = resolved.members.get(name);
      if (symbol && symbolIsValue(symbol)) {
        return symbol;
      }
    }
  }
  function getPropertiesOfUnionOrIntersectionType(type) {
    if (!type.resolvedProperties) {
      const members = createSymbolTable();
      for (const current of type.types) {
        for (const prop of getPropertiesOfType(current)) {
          if (!members.has(prop.escapedName)) {
            const combinedProp = getPropertyOfUnionOrIntersectionType(
              type,
              prop.escapedName,
              /*skipObjectFunctionPropertyAugment*/
              !!(type.flags & 2097152 /* Intersection */)
            );
            if (combinedProp) {
              members.set(prop.escapedName, combinedProp);
            }
          }
        }
        if (type.flags & 1048576 /* Union */ && getIndexInfosOfType(current).length === 0) {
          break;
        }
      }
      type.resolvedProperties = getNamedMembers(members);
    }
    return type.resolvedProperties;
  }
  function getPropertiesOfType(type) {
    type = getReducedApparentType(type);
    return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type);
  }
  function forEachPropertyOfType(type, action) {
    type = getReducedApparentType(type);
    if (type.flags & 3670016 /* StructuredType */) {
      resolveStructuredTypeMembers(type).members.forEach((symbol, escapedName) => {
        if (isNamedMember(symbol, escapedName)) {
          action(symbol, escapedName);
        }
      });
    }
  }
  function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
    const list = obj.properties;
    return list.some((property) => {
      const nameType = property.name && (isJsxNamespacedName(property.name) ? getStringLiteralType(getTextOfJsxAttributeName(property.name)) : getLiteralTypeFromPropertyName(property.name));
      const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0;
      const expected = name === void 0 ? void 0 : getTypeOfPropertyOfType(contextualType, name);
      return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
    });
  }
  function getAllPossiblePropertiesOfTypes(types) {
    const unionType = getUnionType(types);
    if (!(unionType.flags & 1048576 /* Union */)) {
      return getAugmentedPropertiesOfType(unionType);
    }
    const props = createSymbolTable();
    for (const memberType of types) {
      for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) {
        if (!props.has(escapedName)) {
          const prop = createUnionOrIntersectionProperty(unionType, escapedName);
          if (prop) props.set(escapedName, prop);
        }
      }
    }
    return arrayFrom(props.values());
  }
  function getConstraintOfType(type) {
    return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type);
  }
  function getConstraintOfTypeParameter(typeParameter) {
    return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : void 0;
  }
  function isConstMappedType(type, depth) {
    const typeVariable = getHomomorphicTypeVariable(type);
    return !!typeVariable && isConstTypeVariable(typeVariable, depth);
  }
  function isConstTypeVariable(type, depth = 0) {
    var _a;
    return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 4096 /* Const */)) || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || getObjectFlags(type) & 32 /* Mapped */ && isConstMappedType(type, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0));
  }
  function getConstraintOfIndexedAccess(type) {
    return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0;
  }
  function getSimplifiedTypeOrConstraint(type) {
    const simplified = getSimplifiedType(
      type,
      /*writing*/
      false
    );
    return simplified !== type ? simplified : getConstraintOfType(type);
  }
  function getConstraintFromIndexedAccess(type) {
    if (isMappedTypeGenericIndexedAccess(type)) {
      return substituteIndexedMappedType(type.objectType, type.indexType);
    }
    const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
    if (indexConstraint && indexConstraint !== type.indexType) {
      const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags);
      if (indexedAccess) {
        return indexedAccess;
      }
    }
    const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
    if (objectConstraint && objectConstraint !== type.objectType) {
      return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.accessFlags);
    }
    return void 0;
  }
  function getDefaultConstraintOfConditionalType(type) {
    if (!type.resolvedDefaultConstraint) {
      const trueConstraint = getInferredTrueTypeFromConditionalType(type);
      const falseConstraint = getFalseTypeFromConditionalType(type);
      type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
    }
    return type.resolvedDefaultConstraint;
  }
  function getConstraintOfDistributiveConditionalType(type) {
    if (type.resolvedConstraintOfDistributive !== void 0) {
      return type.resolvedConstraintOfDistributive || void 0;
    }
    if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
      const simplified = getSimplifiedType(
        type.checkType,
        /*writing*/
        false
      );
      const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
      if (constraint && constraint !== type.checkType) {
        const instantiated = getConditionalTypeInstantiation(
          type,
          prependTypeMapping(type.root.checkType, constraint, type.mapper),
          /*forConstraint*/
          true
        );
        if (!(instantiated.flags & 131072 /* Never */)) {
          type.resolvedConstraintOfDistributive = instantiated;
          return instantiated;
        }
      }
    }
    type.resolvedConstraintOfDistributive = false;
    return void 0;
  }
  function getConstraintFromConditionalType(type) {
    return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
  }
  function getConstraintOfConditionalType(type) {
    return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : void 0;
  }
  function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
    let constraints;
    let hasDisjointDomainType = false;
    for (const t of types) {
      if (t.flags & 465829888 /* Instantiable */) {
        let constraint = getConstraintOfType(t);
        while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
          constraint = getConstraintOfType(constraint);
        }
        if (constraint) {
          constraints = append(constraints, constraint);
          if (targetIsUnion) {
            constraints = append(constraints, t);
          }
        }
      } else if (t.flags & 469892092 /* DisjointDomains */ || isEmptyAnonymousObjectType(t)) {
        hasDisjointDomainType = true;
      }
    }
    if (constraints && (targetIsUnion || hasDisjointDomainType)) {
      if (hasDisjointDomainType) {
        for (const t of types) {
          if (t.flags & 469892092 /* DisjointDomains */ || isEmptyAnonymousObjectType(t)) {
            constraints = append(constraints, t);
          }
        }
      }
      return getNormalizedType(
        getIntersectionType(constraints, 2 /* NoConstraintReduction */),
        /*writing*/
        false
      );
    }
    return void 0;
  }
  function getBaseConstraintOfType(type) {
    if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) {
      const constraint = getResolvedBaseConstraint(type);
      return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0;
    }
    return type.flags & 4194304 /* Index */ ? stringNumberSymbolType : void 0;
  }
  function getBaseConstraintOrType(type) {
    return getBaseConstraintOfType(type) || type;
  }
  function hasNonCircularBaseConstraint(type) {
    return getResolvedBaseConstraint(type) !== circularConstraintType;
  }
  function getResolvedBaseConstraint(type) {
    if (type.resolvedBaseConstraint) {
      return type.resolvedBaseConstraint;
    }
    const stack = [];
    return type.resolvedBaseConstraint = getImmediateBaseConstraint(type);
    function getImmediateBaseConstraint(t) {
      if (!t.immediateBaseConstraint) {
        if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
          return circularConstraintType;
        }
        let result;
        const identity2 = getRecursionIdentity(t);
        if (stack.length < 10 || stack.length < 50 && !contains(stack, identity2)) {
          stack.push(identity2);
          result = computeBaseConstraint(getSimplifiedType(
            t,
            /*writing*/
            false
          ));
          stack.pop();
        }
        if (!popTypeResolution()) {
          if (t.flags & 262144 /* TypeParameter */) {
            const errorNode = getConstraintDeclaration(t);
            if (errorNode) {
              const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
              if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) {
                addRelatedInfo(diagnostic, createDiagnosticForNode(currentNode, Diagnostics.Circularity_originates_in_type_at_this_location));
              }
            }
          }
          result = circularConstraintType;
        }
        t.immediateBaseConstraint ?? (t.immediateBaseConstraint = result || noConstraintType);
      }
      return t.immediateBaseConstraint;
    }
    function getBaseConstraint(t) {
      const c = getImmediateBaseConstraint(t);
      return c !== noConstraintType && c !== circularConstraintType ? c : void 0;
    }
    function computeBaseConstraint(t) {
      if (t.flags & 262144 /* TypeParameter */) {
        const constraint = getConstraintFromTypeParameter(t);
        return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint);
      }
      if (t.flags & 3145728 /* UnionOrIntersection */) {
        const types = t.types;
        const baseTypes = [];
        let different = false;
        for (const type2 of types) {
          const baseType = getBaseConstraint(type2);
          if (baseType) {
            if (baseType !== type2) {
              different = true;
            }
            baseTypes.push(baseType);
          } else {
            different = true;
          }
        }
        if (!different) {
          return t;
        }
        return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : void 0;
      }
      if (t.flags & 4194304 /* Index */) {
        return stringNumberSymbolType;
      }
      if (t.flags & 134217728 /* TemplateLiteral */) {
        const types = t.types;
        const constraints = mapDefined(types, getBaseConstraint);
        return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
      }
      if (t.flags & 268435456 /* StringMapping */) {
        const constraint = getBaseConstraint(t.type);
        return constraint && constraint !== t.type ? getStringMappingType(t.symbol, constraint) : stringType;
      }
      if (t.flags & 8388608 /* IndexedAccess */) {
        if (isMappedTypeGenericIndexedAccess(t)) {
          return getBaseConstraint(substituteIndexedMappedType(t.objectType, t.indexType));
        }
        const baseObjectType = getBaseConstraint(t.objectType);
        const baseIndexType = getBaseConstraint(t.indexType);
        const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags);
        return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
      }
      if (t.flags & 16777216 /* Conditional */) {
        const constraint = getConstraintFromConditionalType(t);
        return constraint && getBaseConstraint(constraint);
      }
      if (t.flags & 33554432 /* Substitution */) {
        return getBaseConstraint(getSubstitutionIntersection(t));
      }
      if (isGenericTupleType(t)) {
        const newElements = map(getElementTypes(t), (v, i) => {
          const constraint = v.flags & 262144 /* TypeParameter */ && t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v;
          return constraint !== v && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v;
        });
        return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations);
      }
      return t;
    }
  }
  function getApparentTypeOfIntersectionType(type, thisArgument) {
    if (type === thisArgument) {
      return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(
        type,
        thisArgument,
        /*needApparentType*/
        true
      ));
    }
    const key = `I${getTypeId(type)},${getTypeId(thisArgument)}`;
    return getCachedType(key) ?? setCachedType(key, getTypeWithThisArgument(
      type,
      thisArgument,
      /*needApparentType*/
      true
    ));
  }
  function getResolvedTypeParameterDefault(typeParameter) {
    if (!typeParameter.default) {
      if (typeParameter.target) {
        const targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
        typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
      } else {
        typeParameter.default = resolvingDefaultType;
        const defaultDeclaration = typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default);
        const defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
        if (typeParameter.default === resolvingDefaultType) {
          typeParameter.default = defaultType;
        }
      }
    } else if (typeParameter.default === resolvingDefaultType) {
      typeParameter.default = circularConstraintType;
    }
    return typeParameter.default;
  }
  function getDefaultFromTypeParameter(typeParameter) {
    const defaultType = getResolvedTypeParameterDefault(typeParameter);
    return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : void 0;
  }
  function hasNonCircularTypeParameterDefault(typeParameter) {
    return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
  }
  function hasTypeParameterDefault(typeParameter) {
    return !!(typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default));
  }
  function getApparentTypeOfMappedType(type) {
    return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
  }
  function getResolvedApparentTypeOfMappedType(type) {
    const target = type.target ?? type;
    const typeVariable = getHomomorphicTypeVariable(target);
    if (typeVariable && !target.declaration.nameType) {
      const modifiersType = getModifiersTypeFromMappedType(type);
      const baseConstraint = isGenericMappedType(modifiersType) ? getApparentTypeOfMappedType(modifiersType) : getBaseConstraintOfType(modifiersType);
      if (baseConstraint && everyType(baseConstraint, (t) => isArrayOrTupleType(t) || isArrayOrTupleOrIntersection(t))) {
        return instantiateType(target, prependTypeMapping(typeVariable, baseConstraint, type.mapper));
      }
    }
    return type;
  }
  function isArrayOrTupleOrIntersection(type) {
    return !!(type.flags & 2097152 /* Intersection */) && every(type.types, isArrayOrTupleType);
  }
  function isMappedTypeGenericIndexedAccess(type) {
    let objectType;
    return !!(type.flags & 8388608 /* IndexedAccess */ && getObjectFlags(objectType = type.objectType) & 32 /* Mapped */ && !isGenericMappedType(objectType) && isGenericIndexType(type.indexType) && !(getMappedTypeModifiers(objectType) & 8 /* ExcludeOptional */) && !objectType.declaration.nameType);
  }
  function getApparentType(type) {
    const t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
    const objectFlags = getObjectFlags(t);
    return objectFlags & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : objectFlags & 4 /* Reference */ && t !== type ? getTypeWithThisArgument(t, type) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t, type) : t.flags & 402653316 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType() : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType() : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : t.flags & 4194304 /* Index */ ? stringNumberSymbolType : t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType : t;
  }
  function getReducedApparentType(type) {
    return getReducedType(getApparentType(getReducedType(type)));
  }
  function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) {
    var _a, _b, _c;
    let singleProp;
    let propSet;
    let indexTypes;
    const isUnion = containingType.flags & 1048576 /* Union */;
    let optionalFlag;
    let syntheticFlag = 4 /* SyntheticMethod */;
    let checkFlags = isUnion ? 0 : 8 /* Readonly */;
    let mergedInstantiations = false;
    for (const current of containingType.types) {
      const type = getApparentType(current);
      if (!(isErrorType(type) || type.flags & 131072 /* Never */)) {
        const prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
        const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
        if (prop) {
          if (prop.flags & 106500 /* ClassMember */) {
            optionalFlag ?? (optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */);
            if (isUnion) {
              optionalFlag |= prop.flags & 16777216 /* Optional */;
            } else {
              optionalFlag &= prop.flags;
            }
          }
          if (!singleProp) {
            singleProp = prop;
          } else if (prop !== singleProp) {
            const isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp);
            if (isInstantiation && compareProperties(singleProp, prop, (a, b) => a === b ? -1 /* True */ : 0 /* False */) === -1 /* True */) {
              mergedInstantiations = !!singleProp.parent && !!length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent));
            } else {
              if (!propSet) {
                propSet = /* @__PURE__ */ new Map();
                propSet.set(getSymbolId(singleProp), singleProp);
              }
              const id = getSymbolId(prop);
              if (!propSet.has(id)) {
                propSet.set(id, prop);
              }
            }
          }
          if (isUnion && isReadonlySymbol(prop)) {
            checkFlags |= 8 /* Readonly */;
          } else if (!isUnion && !isReadonlySymbol(prop)) {
            checkFlags &= ~8 /* Readonly */;
          }
          checkFlags |= (!(modifiers & 6 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | (modifiers & 4 /* Protected */ ? 512 /* ContainsProtected */ : 0) | (modifiers & 2 /* Private */ ? 1024 /* ContainsPrivate */ : 0) | (modifiers & 256 /* Static */ ? 2048 /* ContainsStatic */ : 0);
          if (!isPrototypeProperty(prop)) {
            syntheticFlag = 2 /* SyntheticProperty */;
          }
        } else if (isUnion) {
          const indexInfo = !isLateBoundName(name) && getApplicableIndexInfoForName(type, name);
          if (indexInfo) {
            checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
            indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
          } else if (isObjectLiteralType(type) && !(getObjectFlags(type) & 2097152 /* ContainsSpread */)) {
            checkFlags |= 32 /* WritePartial */;
            indexTypes = append(indexTypes, undefinedType);
          } else {
            checkFlags |= 16 /* ReadPartial */;
          }
        }
      }
    }
    if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */) && !(propSet && getCommonDeclarationsOfSymbols(propSet.values()))) {
      return void 0;
    }
    if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
      if (mergedInstantiations) {
        const links = (_a = tryCast(singleProp, isTransientSymbol)) == null ? void 0 : _a.links;
        const clone = createSymbolWithType(singleProp, links == null ? void 0 : links.type);
        clone.parent = (_c = (_b = singleProp.valueDeclaration) == null ? void 0 : _b.symbol) == null ? void 0 : _c.parent;
        clone.links.containingType = containingType;
        clone.links.mapper = links == null ? void 0 : links.mapper;
        clone.links.writeType = getWriteTypeOfSymbol(singleProp);
        return clone;
      } else {
        return singleProp;
      }
    }
    const props = propSet ? arrayFrom(propSet.values()) : [singleProp];
    let declarations;
    let firstType;
    let nameType;
    const propTypes = [];
    let writeTypes;
    let firstValueDeclaration;
    let hasNonUniformValueDeclaration = false;
    for (const prop of props) {
      if (!firstValueDeclaration) {
        firstValueDeclaration = prop.valueDeclaration;
      } else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
        hasNonUniformValueDeclaration = true;
      }
      declarations = addRange(declarations, prop.declarations);
      const type = getTypeOfSymbol(prop);
      if (!firstType) {
        firstType = type;
        nameType = getSymbolLinks(prop).nameType;
      }
      const writeType = getWriteTypeOfSymbol(prop);
      if (writeTypes || writeType !== type) {
        writeTypes = append(!writeTypes ? propTypes.slice() : writeTypes, writeType);
      }
      if (type !== firstType) {
        checkFlags |= 64 /* HasNonUniformType */;
      }
      if (isLiteralType(type) || isPatternLiteralType(type)) {
        checkFlags |= 128 /* HasLiteralType */;
      }
      if (type.flags & 131072 /* Never */ && type !== uniqueLiteralType) {
        checkFlags |= 131072 /* HasNeverType */;
      }
      propTypes.push(type);
    }
    addRange(propTypes, indexTypes);
    const result = createSymbol(4 /* Property */ | (optionalFlag ?? 0), name, syntheticFlag | checkFlags);
    result.links.containingType = containingType;
    if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
      result.valueDeclaration = firstValueDeclaration;
      if (firstValueDeclaration.symbol.parent) {
        result.parent = firstValueDeclaration.symbol.parent;
      }
    }
    result.declarations = declarations;
    result.links.nameType = nameType;
    if (propTypes.length > 2) {
      result.links.checkFlags |= 65536 /* DeferredType */;
      result.links.deferralParent = containingType;
      result.links.deferralConstituents = propTypes;
      result.links.deferralWriteConstituents = writeTypes;
    } else {
      result.links.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
      if (writeTypes) {
        result.links.writeType = isUnion ? getUnionType(writeTypes) : getIntersectionType(writeTypes);
      }
    }
    return result;
  }
  function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) {
    var _a, _b, _c;
    let property = skipObjectFunctionPropertyAugment ? (_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) == null ? void 0 : _a.get(name) : (_b = type.propertyCache) == null ? void 0 : _b.get(name);
    if (!property) {
      property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
      if (property) {
        const properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment || (type.propertyCacheWithoutObjectFunctionPropertyAugment = createSymbolTable()) : type.propertyCache || (type.propertyCache = createSymbolTable());
        properties.set(name, property);
        if (skipObjectFunctionPropertyAugment && !(getCheckFlags(property) & 48 /* Partial */) && !((_c = type.propertyCache) == null ? void 0 : _c.get(name))) {
          const properties2 = type.propertyCache || (type.propertyCache = createSymbolTable());
          properties2.set(name, property);
        }
      }
    }
    return property;
  }
  function getCommonDeclarationsOfSymbols(symbols) {
    let commonDeclarations;
    for (const symbol of symbols) {
      if (!symbol.declarations) {
        return void 0;
      }
      if (!commonDeclarations) {
        commonDeclarations = new Set(symbol.declarations);
        continue;
      }
      commonDeclarations.forEach((declaration) => {
        if (!contains(symbol.declarations, declaration)) {
          commonDeclarations.delete(declaration);
        }
      });
      if (commonDeclarations.size === 0) {
        return void 0;
      }
    }
    return commonDeclarations;
  }
  function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) {
    const property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
    return property && !(getCheckFlags(property) & 16 /* ReadPartial */) ? property : void 0;
  }
  function getReducedType(type) {
    if (type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */) {
      return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
    } else if (type.flags & 2097152 /* Intersection */) {
      if (!(type.objectFlags & 16777216 /* IsNeverIntersectionComputed */)) {
        type.objectFlags |= 16777216 /* IsNeverIntersectionComputed */ | (some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 33554432 /* IsNeverIntersection */ : 0);
      }
      return type.objectFlags & 33554432 /* IsNeverIntersection */ ? neverType : type;
    }
    return type;
  }
  function getReducedUnionType(unionType) {
    const reducedTypes = sameMap(unionType.types, getReducedType);
    if (reducedTypes === unionType.types) {
      return unionType;
    }
    const reduced = getUnionType(reducedTypes);
    if (reduced.flags & 1048576 /* Union */) {
      reduced.resolvedReducedType = reduced;
    }
    return reduced;
  }
  function isNeverReducedProperty(prop) {
    return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
  }
  function isDiscriminantWithNeverType(prop) {
    return !(prop.flags & 16777216 /* Optional */) && (getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
  }
  function isConflictingPrivateProperty(prop) {
    return !prop.valueDeclaration && !!(getCheckFlags(prop) & 1024 /* ContainsPrivate */);
  }
  function isGenericReducibleType(type) {
    return !!(type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */ && some(type.types, isGenericReducibleType) || type.flags & 2097152 /* Intersection */ && isReducibleIntersection(type));
  }
  function isReducibleIntersection(type) {
    const uniqueFilled = type.uniqueLiteralFilledInstantiation || (type.uniqueLiteralFilledInstantiation = instantiateType(type, uniqueLiteralMapper));
    return getReducedType(uniqueFilled) !== uniqueFilled;
  }
  function elaborateNeverIntersection(errorInfo, type) {
    if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 33554432 /* IsNeverIntersection */) {
      const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
      if (neverProp) {
        return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          536870912 /* NoTypeReduction */
        ), symbolToString(neverProp));
      }
      const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
      if (privateProp) {
        return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          536870912 /* NoTypeReduction */
        ), symbolToString(privateProp));
      }
    }
    return errorInfo;
  }
  function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment, includeTypeOnlyMembers) {
    var _a, _b;
    type = getReducedApparentType(type);
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      const symbol = resolved.members.get(name);
      if (symbol && !includeTypeOnlyMembers && ((_a = type.symbol) == null ? void 0 : _a.flags) & 512 /* ValueModule */ && ((_b = getSymbolLinks(type.symbol).typeOnlyExportStarMap) == null ? void 0 : _b.has(name))) {
        return void 0;
      }
      if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) {
        return symbol;
      }
      if (skipObjectFunctionPropertyAugment) return void 0;
      const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : resolved.constructSignatures.length ? globalNewableFunctionType : void 0;
      if (functionType) {
        const symbol2 = getPropertyOfObjectType(functionType, name);
        if (symbol2) {
          return symbol2;
        }
      }
      return getPropertyOfObjectType(globalObjectType, name);
    }
    if (type.flags & 2097152 /* Intersection */) {
      const prop = getPropertyOfUnionOrIntersectionType(
        type,
        name,
        /*skipObjectFunctionPropertyAugment*/
        true
      );
      if (prop) {
        return prop;
      }
      if (!skipObjectFunctionPropertyAugment) {
        return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
      }
      return void 0;
    }
    if (type.flags & 1048576 /* Union */) {
      return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
    }
    return void 0;
  }
  function getSignaturesOfStructuredType(type, kind) {
    if (type.flags & 3670016 /* StructuredType */) {
      const resolved = resolveStructuredTypeMembers(type);
      return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
    }
    return emptyArray;
  }
  function getSignaturesOfType(type, kind) {
    const result = getSignaturesOfStructuredType(getReducedApparentType(type), kind);
    if (kind === 0 /* Call */ && !length(result) && type.flags & 1048576 /* Union */) {
      if (type.arrayFallbackSignatures) {
        return type.arrayFallbackSignatures;
      }
      let memberName;
      if (everyType(type, (t) => {
        var _a;
        return !!((_a = t.symbol) == null ? void 0 : _a.parent) && isArrayOrTupleSymbol(t.symbol.parent) && (!memberName ? (memberName = t.symbol.escapedName, true) : memberName === t.symbol.escapedName);
      })) {
        const arrayArg = mapType(type, (t) => getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper));
        const arrayType = createArrayType(arrayArg, someType(type, (t) => isReadonlyArraySymbol(t.symbol.parent)));
        return type.arrayFallbackSignatures = getSignaturesOfType(getTypeOfPropertyOfType(arrayType, memberName), kind);
      }
      type.arrayFallbackSignatures = result;
    }
    return result;
  }
  function isArrayOrTupleSymbol(symbol) {
    if (!symbol || !globalArrayType.symbol || !globalReadonlyArrayType.symbol) {
      return false;
    }
    return !!getSymbolIfSameReference(symbol, globalArrayType.symbol) || !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol);
  }
  function isReadonlyArraySymbol(symbol) {
    if (!symbol || !globalReadonlyArrayType.symbol) {
      return false;
    }
    return !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol);
  }
  function findIndexInfo(indexInfos, keyType) {
    return find(indexInfos, (info) => info.keyType === keyType);
  }
  function findApplicableIndexInfo(indexInfos, keyType) {
    let stringIndexInfo;
    let applicableInfo;
    let applicableInfos;
    for (const info of indexInfos) {
      if (info.keyType === stringType) {
        stringIndexInfo = info;
      } else if (isApplicableIndexType(keyType, info.keyType)) {
        if (!applicableInfo) {
          applicableInfo = info;
        } else {
          (applicableInfos || (applicableInfos = [applicableInfo])).push(info);
        }
      }
    }
    return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, (info) => info.type)), reduceLeft(
      applicableInfos,
      (isReadonly, info) => isReadonly && info.isReadonly,
      /*initial*/
      true
    )) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0;
  }
  function isApplicableIndexType(source, target) {
    return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || target === numberType && (source === numericStringType || !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value));
  }
  function getIndexInfosOfStructuredType(type) {
    if (type.flags & 3670016 /* StructuredType */) {
      const resolved = resolveStructuredTypeMembers(type);
      return resolved.indexInfos;
    }
    return emptyArray;
  }
  function getIndexInfosOfType(type) {
    return getIndexInfosOfStructuredType(getReducedApparentType(type));
  }
  function getIndexInfoOfType(type, keyType) {
    return findIndexInfo(getIndexInfosOfType(type), keyType);
  }
  function getIndexTypeOfType(type, keyType) {
    var _a;
    return (_a = getIndexInfoOfType(type, keyType)) == null ? void 0 : _a.type;
  }
  function getApplicableIndexInfos(type, keyType) {
    return getIndexInfosOfType(type).filter((info) => isApplicableIndexType(keyType, info.keyType));
  }
  function getApplicableIndexInfo(type, keyType) {
    return findApplicableIndexInfo(getIndexInfosOfType(type), keyType);
  }
  function getApplicableIndexInfoForName(type, name) {
    return getApplicableIndexInfo(type, isLateBoundName(name) ? esSymbolType : getStringLiteralType(unescapeLeadingUnderscores(name)));
  }
  function getTypeParametersFromDeclaration(declaration) {
    var _a;
    let result;
    for (const node of getEffectiveTypeParameterDeclarations(declaration)) {
      result = appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
    }
    return (result == null ? void 0 : result.length) ? result : isFunctionDeclaration(declaration) ? (_a = getSignatureOfTypeTag(declaration)) == null ? void 0 : _a.typeParameters : void 0;
  }
  function symbolsToArray(symbols) {
    const result = [];
    symbols.forEach((symbol, id) => {
      if (!isReservedMemberName(id)) {
        result.push(symbol);
      }
    });
    return result;
  }
  function tryFindAmbientModule(moduleName, withAugmentations) {
    if (isExternalModuleNameRelative(moduleName)) {
      return void 0;
    }
    const symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
    return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
  }
  function hasEffectiveQuestionToken(node) {
    return hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isParameter(node) && isJSDocOptionalParameter(node);
  }
  function isOptionalParameter(node) {
    if (hasEffectiveQuestionToken(node)) {
      return true;
    }
    if (!isParameter(node)) {
      return false;
    }
    if (node.initializer) {
      const signature = getSignatureFromDeclaration(node.parent);
      const parameterIndex = node.parent.parameters.indexOf(node);
      Debug.assert(parameterIndex >= 0);
      return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
    }
    const iife = getImmediatelyInvokedFunctionExpression(node.parent);
    if (iife) {
      return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= getEffectiveCallArguments(iife).length;
    }
    return false;
  }
  function isOptionalPropertyDeclaration(node) {
    return isPropertyDeclaration(node) && !hasAccessorModifier(node) && node.questionToken;
  }
  function createTypePredicate(kind, parameterName, parameterIndex, type) {
    return { kind, parameterName, parameterIndex, type };
  }
  function getMinTypeArgumentCount(typeParameters) {
    let minTypeArgumentCount = 0;
    if (typeParameters) {
      for (let i = 0; i < typeParameters.length; i++) {
        if (!hasTypeParameterDefault(typeParameters[i])) {
          minTypeArgumentCount = i + 1;
        }
      }
    }
    return minTypeArgumentCount;
  }
  function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
    const numTypeParameters = length(typeParameters);
    if (!numTypeParameters) {
      return [];
    }
    const numTypeArguments = length(typeArguments);
    if (isJavaScriptImplicitAny || numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters) {
      const result = typeArguments ? typeArguments.slice() : [];
      for (let i = numTypeArguments; i < numTypeParameters; i++) {
        result[i] = errorType;
      }
      const baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
      for (let i = numTypeArguments; i < numTypeParameters; i++) {
        let defaultType = getDefaultFromTypeParameter(typeParameters[i]);
        if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
          defaultType = anyType;
        }
        result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
      }
      result.length = typeParameters.length;
      return result;
    }
    return typeArguments && typeArguments.slice();
  }
  function getSignatureFromDeclaration(declaration) {
    const links = getNodeLinks(declaration);
    if (!links.resolvedSignature) {
      const parameters = [];
      let flags = 0 /* None */;
      let minArgumentCount = 0;
      let thisParameter;
      let thisTag = isInJSFile(declaration) ? getJSDocThisTag(declaration) : void 0;
      let hasThisParameter = false;
      const iife = getImmediatelyInvokedFunctionExpression(declaration);
      const isJSConstructSignature = isJSDocConstructSignature(declaration);
      const isUntypedSignatureInJSFile = !iife && isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration);
      if (isUntypedSignatureInJSFile) {
        flags |= 32 /* IsUntypedSignatureInJSFile */;
      }
      for (let i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
        const param = declaration.parameters[i];
        if (isInJSFile(param) && isJSDocThisTag(param)) {
          thisTag = param;
          continue;
        }
        let paramSymbol = param.symbol;
        const type = isJSDocParameterTag(param) ? param.typeExpression && param.typeExpression.type : param.type;
        if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !isBindingPattern(param.name)) {
          const resolvedSymbol = resolveName(
            param,
            paramSymbol.escapedName,
            111551 /* Value */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          );
          paramSymbol = resolvedSymbol;
        }
        if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
          hasThisParameter = true;
          thisParameter = param.symbol;
        } else {
          parameters.push(paramSymbol);
        }
        if (type && type.kind === 201 /* LiteralType */) {
          flags |= 2 /* HasLiteralTypes */;
        }
        const isOptionalParameter2 = hasEffectiveQuestionToken(param) || isParameter(param) && param.initializer || isRestParameter(param) || iife && parameters.length > iife.arguments.length && !type;
        if (!isOptionalParameter2) {
          minArgumentCount = parameters.length;
        }
      }
      if ((declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */) && hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) {
        const otherKind = declaration.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */;
        const other = getDeclarationOfKind(getSymbolOfDeclaration(declaration), otherKind);
        if (other) {
          thisParameter = getAnnotatedAccessorThisParameter(other);
        }
      }
      if (thisTag && thisTag.typeExpression) {
        thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression));
      }
      const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration;
      const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0;
      const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
      if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
        flags |= 1 /* HasRestParameter */;
      }
      if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 64 /* Abstract */) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 64 /* Abstract */)) {
        flags |= 4 /* Abstract */;
      }
      links.resolvedSignature = createSignature(
        declaration,
        typeParameters,
        thisParameter,
        parameters,
        /*resolvedReturnType*/
        void 0,
        /*resolvedTypePredicate*/
        void 0,
        minArgumentCount,
        flags
      );
    }
    return links.resolvedSignature;
  }
  function maybeAddJsSyntheticRestParameter(declaration, parameters) {
    if (isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
      return false;
    }
    const lastParam = lastOrUndefined(declaration.parameters);
    const lastParamTags = lastParam ? getJSDocParameterTags(lastParam) : getJSDocTags(declaration).filter(isJSDocParameterTag);
    const lastParamVariadicType = firstDefined(lastParamTags, (p) => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : void 0);
    const syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
    if (lastParamVariadicType) {
      syntheticArgsSymbol.links.type = createArrayType(getTypeFromTypeNode(lastParamVariadicType.type));
    } else {
      syntheticArgsSymbol.links.checkFlags |= 65536 /* DeferredType */;
      syntheticArgsSymbol.links.deferralParent = neverType;
      syntheticArgsSymbol.links.deferralConstituents = [anyArrayType];
      syntheticArgsSymbol.links.deferralWriteConstituents = [anyArrayType];
    }
    if (lastParamVariadicType) {
      parameters.pop();
    }
    parameters.push(syntheticArgsSymbol);
    return true;
  }
  function getSignatureOfTypeTag(node) {
    if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return void 0;
    const typeTag = getJSDocTypeTag(node);
    return (typeTag == null ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
  }
  function getParameterTypeOfTypeTag(func, parameter) {
    const signature = getSignatureOfTypeTag(func);
    if (!signature) return void 0;
    const pos = func.parameters.indexOf(parameter);
    return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
  }
  function getReturnTypeOfTypeTag(node) {
    const signature = getSignatureOfTypeTag(node);
    return signature && getReturnTypeOfSignature(signature);
  }
  function containsArgumentsReference(declaration) {
    const links = getNodeLinks(declaration);
    if (links.containsArgumentsReference === void 0) {
      if (links.flags & 512 /* CaptureArguments */) {
        links.containsArgumentsReference = true;
      } else {
        links.containsArgumentsReference = traverse(declaration.body);
      }
    }
    return links.containsArgumentsReference;
    function traverse(node) {
      if (!node) return false;
      switch (node.kind) {
        case 80 /* Identifier */:
          return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol;
        case 172 /* PropertyDeclaration */:
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          return node.name.kind === 167 /* ComputedPropertyName */ && traverse(node.name);
        case 211 /* PropertyAccessExpression */:
        case 212 /* ElementAccessExpression */:
          return traverse(node.expression);
        case 303 /* PropertyAssignment */:
          return traverse(node.initializer);
        default:
          return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && !!forEachChild(node, traverse);
      }
    }
  }
  function getSignaturesOfSymbol(symbol) {
    if (!symbol || !symbol.declarations) return emptyArray;
    const result = [];
    for (let i = 0; i < symbol.declarations.length; i++) {
      const decl = symbol.declarations[i];
      if (!isFunctionLike(decl)) continue;
      if (i > 0 && decl.body) {
        const previous = symbol.declarations[i - 1];
        if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
          continue;
        }
      }
      if (isInJSFile(decl) && decl.jsDoc) {
        const tags = getJSDocOverloadTags(decl);
        if (length(tags)) {
          for (const tag of tags) {
            const jsDocSignature = tag.typeExpression;
            if (jsDocSignature.type === void 0 && !isConstructorDeclaration(decl)) {
              reportImplicitAny(jsDocSignature, anyType);
            }
            result.push(getSignatureFromDeclaration(jsDocSignature));
          }
          continue;
        }
      }
      result.push(
        !isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl) || getSignatureFromDeclaration(decl)
      );
    }
    return result;
  }
  function resolveExternalModuleTypeByLiteral(name) {
    const moduleSym = resolveExternalModuleName(name, name);
    if (moduleSym) {
      const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
      if (resolvedModuleSymbol) {
        return getTypeOfSymbol(resolvedModuleSymbol);
      }
    }
    return anyType;
  }
  function getThisTypeOfSignature(signature) {
    if (signature.thisParameter) {
      return getTypeOfSymbol(signature.thisParameter);
    }
  }
  function getTypePredicateOfSignature(signature) {
    if (!signature.resolvedTypePredicate) {
      if (signature.target) {
        const targetTypePredicate = getTypePredicateOfSignature(signature.target);
        signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
      } else if (signature.compositeSignatures) {
        signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate;
      } else {
        const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration);
        let jsdocPredicate;
        if (!type) {
          const jsdocSignature = getSignatureOfTypeTag(signature.declaration);
          if (jsdocSignature && signature !== jsdocSignature) {
            jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
          }
        }
        if (type || jsdocPredicate) {
          signature.resolvedTypePredicate = type && isTypePredicateNode(type) ? createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate;
        } else if (signature.declaration && isFunctionLikeDeclaration(signature.declaration) && (!signature.resolvedReturnType || signature.resolvedReturnType.flags & 16 /* Boolean */) && getParameterCount(signature) > 0) {
          const { declaration } = signature;
          signature.resolvedTypePredicate = noTypePredicate;
          signature.resolvedTypePredicate = getTypePredicateFromBody(declaration) || noTypePredicate;
        } else {
          signature.resolvedTypePredicate = noTypePredicate;
        }
      }
      Debug.assert(!!signature.resolvedTypePredicate);
    }
    return signature.resolvedTypePredicate === noTypePredicate ? void 0 : signature.resolvedTypePredicate;
  }
  function createTypePredicateFromTypePredicateNode(node, signature) {
    const parameterName = node.parameterName;
    const type = node.type && getTypeFromTypeNode(node.type);
    return parameterName.kind === 197 /* ThisType */ ? createTypePredicate(
      node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */,
      /*parameterName*/
      void 0,
      /*parameterIndex*/
      void 0,
      type
    ) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), type);
  }
  function getUnionOrIntersectionType(types, kind, unionReduction) {
    return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types);
  }
  function getReturnTypeOfSignature(signature) {
    if (!signature.resolvedReturnType) {
      if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
        return errorType;
      }
      let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
      if (signature.flags & 8 /* IsInnerCallChain */) {
        type = addOptionalTypeMarker(type);
      } else if (signature.flags & 16 /* IsOuterCallChain */) {
        type = getOptionalType(type);
      }
      if (!popTypeResolution()) {
        if (signature.declaration) {
          const typeNode = getEffectiveReturnTypeNode(signature.declaration);
          if (typeNode) {
            error(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself);
          } else if (noImplicitAny) {
            const declaration = signature.declaration;
            const name = getNameOfDeclaration(declaration);
            if (name) {
              error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name));
            } else {
              error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions);
            }
          }
        }
        type = anyType;
      }
      signature.resolvedReturnType ?? (signature.resolvedReturnType = type);
    }
    return signature.resolvedReturnType;
  }
  function getReturnTypeFromAnnotation(declaration) {
    if (declaration.kind === 176 /* Constructor */) {
      return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
    }
    const typeNode = getEffectiveReturnTypeNode(declaration);
    if (isJSDocSignature(declaration)) {
      const root = getJSDocRoot(declaration);
      if (root && isConstructorDeclaration(root.parent) && !typeNode) {
        return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol));
      }
    }
    if (isJSDocConstructSignature(declaration)) {
      return getTypeFromTypeNode(declaration.parameters[0].type);
    }
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
    if (declaration.kind === 177 /* GetAccessor */ && hasBindableName(declaration)) {
      const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
      if (jsDocType) {
        return jsDocType;
      }
      const setter = getDeclarationOfKind(getSymbolOfDeclaration(declaration), 178 /* SetAccessor */);
      const setterType = getAnnotatedAccessorType(setter);
      if (setterType) {
        return setterType;
      }
    }
    return getReturnTypeOfTypeTag(declaration);
  }
  function isResolvingReturnTypeOfSignature(signature) {
    return signature.compositeSignatures && some(signature.compositeSignatures, isResolvingReturnTypeOfSignature) || !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
  }
  function getRestTypeOfSignature(signature) {
    return tryGetRestTypeOfSignature(signature) || anyType;
  }
  function tryGetRestTypeOfSignature(signature) {
    if (signatureHasRestParameter(signature)) {
      const sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
      const restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
      return restType && getIndexTypeOfType(restType, numberType);
    }
    return void 0;
  }
  function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
    const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
    if (inferredTypeParameters) {
      const returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
      if (returnSignature) {
        const newReturnSignature = cloneSignature(returnSignature);
        newReturnSignature.typeParameters = inferredTypeParameters;
        const newInstantiatedSignature = cloneSignature(instantiatedSignature);
        newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
        return newInstantiatedSignature;
      }
    }
    return instantiatedSignature;
  }
  function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
    const instantiations = signature.instantiations || (signature.instantiations = /* @__PURE__ */ new Map());
    const id = getTypeListId(typeArguments);
    let instantiation = instantiations.get(id);
    if (!instantiation) {
      instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
    }
    return instantiation;
  }
  function createSignatureInstantiation(signature, typeArguments) {
    return instantiateSignature(
      signature,
      createSignatureTypeMapper(signature, typeArguments),
      /*eraseTypeParameters*/
      true
    );
  }
  function getTypeParametersForMapper(signature) {
    return sameMap(signature.typeParameters, (tp) => tp.mapper ? instantiateType(tp, tp.mapper) : tp);
  }
  function createSignatureTypeMapper(signature, typeArguments) {
    return createTypeMapper(getTypeParametersForMapper(signature), typeArguments);
  }
  function getErasedSignature(signature) {
    return signature.typeParameters ? signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : signature;
  }
  function createErasedSignature(signature) {
    return instantiateSignature(
      signature,
      createTypeEraser(signature.typeParameters),
      /*eraseTypeParameters*/
      true
    );
  }
  function getCanonicalSignature(signature) {
    return signature.typeParameters ? signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : signature;
  }
  function createCanonicalSignature(signature) {
    return getSignatureInstantiation(
      signature,
      map(signature.typeParameters, (tp) => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp),
      isInJSFile(signature.declaration)
    );
  }
  function getImplementationSignature(signature) {
    return signature.typeParameters ? signature.implementationSignatureCache || (signature.implementationSignatureCache = createImplementationSignature(signature)) : signature;
  }
  function createImplementationSignature(signature) {
    return signature.typeParameters ? instantiateSignature(signature, createTypeMapper([], [])) : signature;
  }
  function getBaseSignature(signature) {
    const typeParameters = signature.typeParameters;
    if (typeParameters) {
      if (signature.baseSignatureCache) {
        return signature.baseSignatureCache;
      }
      const typeEraser = createTypeEraser(typeParameters);
      const baseConstraintMapper = createTypeMapper(typeParameters, map(typeParameters, (tp) => getConstraintOfTypeParameter(tp) || unknownType));
      let baseConstraints = map(typeParameters, (tp) => instantiateType(tp, baseConstraintMapper) || unknownType);
      for (let i = 0; i < typeParameters.length - 1; i++) {
        baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper);
      }
      baseConstraints = instantiateTypes(baseConstraints, typeEraser);
      return signature.baseSignatureCache = instantiateSignature(
        signature,
        createTypeMapper(typeParameters, baseConstraints),
        /*eraseTypeParameters*/
        true
      );
    }
    return signature;
  }
  function getOrCreateTypeFromSignature(signature, outerTypeParameters) {
    var _a;
    if (!signature.isolatedSignatureType) {
      const kind = (_a = signature.declaration) == null ? void 0 : _a.kind;
      const isConstructor = kind === void 0 || kind === 176 /* Constructor */ || kind === 180 /* ConstructSignature */ || kind === 185 /* ConstructorType */;
      const type = createObjectType(16 /* Anonymous */ | 134217728 /* SingleSignatureType */, createSymbol(16 /* Function */, "__function" /* Function */));
      if (signature.declaration && !nodeIsSynthesized(signature.declaration)) {
        type.symbol.declarations = [signature.declaration];
        type.symbol.valueDeclaration = signature.declaration;
      }
      outerTypeParameters || (outerTypeParameters = signature.declaration && getOuterTypeParameters(
        signature.declaration,
        /*includeThisTypes*/
        true
      ));
      type.outerTypeParameters = outerTypeParameters;
      type.members = emptySymbols;
      type.properties = emptyArray;
      type.callSignatures = !isConstructor ? [signature] : emptyArray;
      type.constructSignatures = isConstructor ? [signature] : emptyArray;
      type.indexInfos = emptyArray;
      signature.isolatedSignatureType = type;
    }
    return signature.isolatedSignatureType;
  }
  function getIndexSymbol(symbol) {
    return symbol.members ? getIndexSymbolFromSymbolTable(getMembersOfSymbol(symbol)) : void 0;
  }
  function getIndexSymbolFromSymbolTable(symbolTable) {
    return symbolTable.get("__index" /* Index */);
  }
  function createIndexInfo(keyType, type, isReadonly, declaration) {
    return { keyType, type, isReadonly, declaration };
  }
  function getIndexInfosOfSymbol(symbol) {
    const indexSymbol = getIndexSymbol(symbol);
    return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(getMembersOfSymbol(symbol).values())) : emptyArray;
  }
  function getIndexInfosOfIndexSymbol(indexSymbol, siblingSymbols = indexSymbol.parent ? arrayFrom(getMembersOfSymbol(indexSymbol.parent).values()) : void 0) {
    if (indexSymbol.declarations) {
      const indexInfos = [];
      let hasComputedNumberProperty = false;
      let readonlyComputedNumberProperty = true;
      let hasComputedSymbolProperty = false;
      let readonlyComputedSymbolProperty = true;
      let hasComputedStringProperty = false;
      let readonlyComputedStringProperty = true;
      const computedPropertySymbols = [];
      for (const declaration of indexSymbol.declarations) {
        if (isIndexSignatureDeclaration(declaration)) {
          if (declaration.parameters.length === 1) {
            const parameter = declaration.parameters[0];
            if (parameter.type) {
              forEachType(getTypeFromTypeNode(parameter.type), (keyType) => {
                if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) {
                  indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, 8 /* Readonly */), declaration));
                }
              });
            }
          }
        } else if (hasLateBindableIndexSignature(declaration)) {
          const declName = isBinaryExpression(declaration) ? declaration.left : declaration.name;
          const keyType = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
          if (findIndexInfo(indexInfos, keyType)) {
            continue;
          }
          if (isTypeAssignableTo(keyType, stringNumberSymbolType)) {
            if (isTypeAssignableTo(keyType, numberType)) {
              hasComputedNumberProperty = true;
              if (!hasEffectiveReadonlyModifier(declaration)) {
                readonlyComputedNumberProperty = false;
              }
            } else if (isTypeAssignableTo(keyType, esSymbolType)) {
              hasComputedSymbolProperty = true;
              if (!hasEffectiveReadonlyModifier(declaration)) {
                readonlyComputedSymbolProperty = false;
              }
            } else {
              hasComputedStringProperty = true;
              if (!hasEffectiveReadonlyModifier(declaration)) {
                readonlyComputedStringProperty = false;
              }
            }
            computedPropertySymbols.push(declaration.symbol);
          }
        }
      }
      const allPropertySymbols = concatenate(computedPropertySymbols, filter(siblingSymbols, (s) => s !== indexSymbol));
      if (hasComputedStringProperty && !findIndexInfo(indexInfos, stringType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedStringProperty, 0, allPropertySymbols, stringType));
      if (hasComputedNumberProperty && !findIndexInfo(indexInfos, numberType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedNumberProperty, 0, allPropertySymbols, numberType));
      if (hasComputedSymbolProperty && !findIndexInfo(indexInfos, esSymbolType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedSymbolProperty, 0, allPropertySymbols, esSymbolType));
      return indexInfos;
    }
    return emptyArray;
  }
  function isValidIndexKeyType(type) {
    return !!(type.flags & (4 /* String */ | 8 /* Number */ | 4096 /* ESSymbol */)) || isPatternLiteralType(type) || !!(type.flags & 2097152 /* Intersection */) && !isGenericType(type) && some(type.types, isValidIndexKeyType);
  }
  function getConstraintDeclaration(type) {
    return mapDefined(filter(type.symbol && type.symbol.declarations, isTypeParameterDeclaration), getEffectiveConstraintOfTypeParameter)[0];
  }
  function getInferredTypeParameterConstraint(typeParameter, omitTypeReferences) {
    var _a;
    let inferences;
    if ((_a = typeParameter.symbol) == null ? void 0 : _a.declarations) {
      for (const declaration of typeParameter.symbol.declarations) {
        if (declaration.parent.kind === 195 /* InferType */) {
          const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent);
          if (grandParent.kind === 183 /* TypeReference */ && !omitTypeReferences) {
            const typeReference = grandParent;
            const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReference);
            if (typeParameters) {
              const index = typeReference.typeArguments.indexOf(childTypeParameter);
              if (index < typeParameters.length) {
                const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
                if (declaredConstraint) {
                  const mapper = makeDeferredTypeMapper(
                    typeParameters,
                    typeParameters.map((_, index2) => () => {
                      return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2);
                    })
                  );
                  const constraint = instantiateType(declaredConstraint, mapper);
                  if (constraint !== typeParameter) {
                    inferences = append(inferences, constraint);
                  }
                }
              }
            }
          } else if (grandParent.kind === 169 /* Parameter */ && grandParent.dotDotDotToken || grandParent.kind === 191 /* RestType */ || grandParent.kind === 202 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
            inferences = append(inferences, createArrayType(unknownType));
          } else if (grandParent.kind === 204 /* TemplateLiteralTypeSpan */) {
            inferences = append(inferences, stringType);
          } else if (grandParent.kind === 168 /* TypeParameter */ && grandParent.parent.kind === 200 /* MappedType */) {
            inferences = append(inferences, stringNumberSymbolType);
          } else if (grandParent.kind === 200 /* MappedType */ && grandParent.type && skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 194 /* ConditionalType */ && grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 200 /* MappedType */ && grandParent.parent.checkType.type) {
            const checkMappedType2 = grandParent.parent.checkType;
            const nodeType = getTypeFromTypeNode(checkMappedType2.type);
            inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType2.typeParameter)), checkMappedType2.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType2.typeParameter.constraint) : stringNumberSymbolType)));
          }
        }
      }
    }
    return inferences && getIntersectionType(inferences);
  }
  function getConstraintFromTypeParameter(typeParameter) {
    if (!typeParameter.constraint) {
      if (typeParameter.target) {
        const targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
        typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
      } else {
        const constraintDeclaration = getConstraintDeclaration(typeParameter);
        if (!constraintDeclaration) {
          typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
        } else {
          let type = getTypeFromTypeNode(constraintDeclaration);
          if (type.flags & 1 /* Any */ && !isErrorType(type)) {
            type = constraintDeclaration.parent.parent.kind === 200 /* MappedType */ ? stringNumberSymbolType : unknownType;
          }
          typeParameter.constraint = type;
        }
      }
    }
    return typeParameter.constraint === noConstraintType ? void 0 : typeParameter.constraint;
  }
  function getParentSymbolOfTypeParameter(typeParameter) {
    const tp = getDeclarationOfKind(typeParameter.symbol, 168 /* TypeParameter */);
    const host2 = isJSDocTemplateTag(tp.parent) ? getEffectiveContainerForJSDocTemplateTag(tp.parent) : tp.parent;
    return host2 && getSymbolOfNode(host2);
  }
  function getTypeListId(types) {
    let result = "";
    if (types) {
      const length2 = types.length;
      let i = 0;
      while (i < length2) {
        const startId = types[i].id;
        let count = 1;
        while (i + count < length2 && types[i + count].id === startId + count) {
          count++;
        }
        if (result.length) {
          result += ",";
        }
        result += startId;
        if (count > 1) {
          result += ":" + count;
        }
        i += count;
      }
    }
    return result;
  }
  function getAliasId(aliasSymbol, aliasTypeArguments) {
    return aliasSymbol ? `@${getSymbolId(aliasSymbol)}` + (aliasTypeArguments ? `:${getTypeListId(aliasTypeArguments)}` : "") : "";
  }
  function getPropagatingFlagsOfTypes(types, excludeKinds) {
    let result = 0;
    for (const type of types) {
      if (excludeKinds === void 0 || !(type.flags & excludeKinds)) {
        result |= getObjectFlags(type);
      }
    }
    return result & 458752 /* PropagatingFlags */;
  }
  function tryCreateTypeReference(target, typeArguments) {
    if (some(typeArguments) && target === emptyGenericType) {
      return unknownType;
    }
    return createTypeReference(target, typeArguments);
  }
  function createTypeReference(target, typeArguments) {
    const id = getTypeListId(typeArguments);
    let type = target.instantiations.get(id);
    if (!type) {
      type = createObjectType(4 /* Reference */, target.symbol);
      target.instantiations.set(id, type);
      type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0;
      type.target = target;
      type.resolvedTypeArguments = typeArguments;
    }
    return type;
  }
  function cloneTypeReference(source) {
    const type = createTypeWithSymbol(source.flags, source.symbol);
    type.objectFlags = source.objectFlags;
    type.target = source.target;
    type.resolvedTypeArguments = source.resolvedTypeArguments;
    return type;
  }
  function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) {
    if (!aliasSymbol) {
      aliasSymbol = getAliasSymbolForTypeNode(node);
      const localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
      aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments;
    }
    const type = createObjectType(4 /* Reference */, target.symbol);
    type.target = target;
    type.node = node;
    type.mapper = mapper;
    type.aliasSymbol = aliasSymbol;
    type.aliasTypeArguments = aliasTypeArguments;
    return type;
  }
  function getTypeArguments(type) {
    var _a, _b;
    if (!type.resolvedTypeArguments) {
      if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) {
        return concatenate(type.target.outerTypeParameters, (_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray;
      }
      const node = type.node;
      const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode);
      if (popTypeResolution()) {
        type.resolvedTypeArguments ?? (type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments);
      } else {
        type.resolvedTypeArguments ?? (type.resolvedTypeArguments = concatenate(type.target.outerTypeParameters, ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray));
        error(
          type.node || currentNode,
          type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves,
          type.target.symbol && symbolToString(type.target.symbol)
        );
      }
    }
    return type.resolvedTypeArguments;
  }
  function getTypeReferenceArity(type) {
    return length(type.target.typeParameters);
  }
  function getTypeFromClassOrInterfaceReference(node, symbol) {
    const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
    const typeParameters = type.localTypeParameters;
    if (typeParameters) {
      const numTypeArguments = length(node.typeArguments);
      const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
      const isJs = isInJSFile(node);
      const isJsImplicitAny = !noImplicitAny && isJs;
      if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
        const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent);
        const diag2 = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_1_type_argument_s : missingAugmentsTag ? Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
        const typeStr = typeToString(
          type,
          /*enclosingDeclaration*/
          void 0,
          2 /* WriteArrayAsGenericType */
        );
        error(node, diag2, typeStr, minTypeArgumentCount, typeParameters.length);
        if (!isJs) {
          return errorType;
        }
      }
      if (node.kind === 183 /* TypeReference */ && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) {
        return createDeferredTypeReference(
          type,
          node,
          /*mapper*/
          void 0
        );
      }
      const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
      return createTypeReference(type, typeArguments);
    }
    return checkNoTypeArguments(node, symbol) ? type : errorType;
  }
  function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) {
    const type = getDeclaredTypeOfSymbol(symbol);
    if (type === intrinsicMarkerType) {
      const typeKind = intrinsicTypeKinds.get(symbol.escapedName);
      if (typeKind !== void 0 && typeArguments && typeArguments.length === 1) {
        return typeKind === 4 /* NoInfer */ ? getNoInferType(typeArguments[0]) : getStringMappingType(symbol, typeArguments[0]);
      }
    }
    const links = getSymbolLinks(symbol);
    const typeParameters = links.typeParameters;
    const id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
    let instantiation = links.instantiations.get(id);
    if (!instantiation) {
      links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments));
    }
    return instantiation;
  }
  function getTypeFromTypeAliasReference(node, symbol) {
    if (getCheckFlags(symbol) & 1048576 /* Unresolved */) {
      const typeArguments = typeArgumentsFromTypeReferenceNode(node);
      const id = getAliasId(symbol, typeArguments);
      let errorType2 = errorTypes.get(id);
      if (!errorType2) {
        errorType2 = createIntrinsicType(
          1 /* Any */,
          "error",
          /*objectFlags*/
          void 0,
          `alias ${id}`
        );
        errorType2.aliasSymbol = symbol;
        errorType2.aliasTypeArguments = typeArguments;
        errorTypes.set(id, errorType2);
      }
      return errorType2;
    }
    const type = getDeclaredTypeOfSymbol(symbol);
    const typeParameters = getSymbolLinks(symbol).typeParameters;
    if (typeParameters) {
      const numTypeArguments = length(node.typeArguments);
      const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
      if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
        error(
          node,
          minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments,
          symbolToString(symbol),
          minTypeArgumentCount,
          typeParameters.length
        );
        return errorType;
      }
      const aliasSymbol = getAliasSymbolForTypeNode(node);
      let newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : void 0;
      let aliasTypeArguments;
      if (newAliasSymbol) {
        aliasTypeArguments = getTypeArgumentsForAliasSymbol(newAliasSymbol);
      } else if (isTypeReferenceType(node)) {
        const aliasSymbol2 = resolveTypeReferenceName(
          node,
          2097152 /* Alias */,
          /*ignoreErrors*/
          true
        );
        if (aliasSymbol2 && aliasSymbol2 !== unknownSymbol) {
          const resolved = resolveAlias(aliasSymbol2);
          if (resolved && resolved.flags & 524288 /* TypeAlias */) {
            newAliasSymbol = resolved;
            aliasTypeArguments = typeArgumentsFromTypeReferenceNode(node) || (typeParameters ? [] : void 0);
          }
        }
      }
      return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, aliasTypeArguments);
    }
    return checkNoTypeArguments(node, symbol) ? type : errorType;
  }
  function isLocalTypeAlias(symbol) {
    var _a;
    const declaration = (_a = symbol.declarations) == null ? void 0 : _a.find(isTypeAlias);
    return !!(declaration && getContainingFunction(declaration));
  }
  function getTypeReferenceName(node) {
    switch (node.kind) {
      case 183 /* TypeReference */:
        return node.typeName;
      case 233 /* ExpressionWithTypeArguments */:
        const expr = node.expression;
        if (isEntityNameExpression(expr)) {
          return expr;
        }
    }
    return void 0;
  }
  function getSymbolPath(symbol) {
    return symbol.parent ? `${getSymbolPath(symbol.parent)}.${symbol.escapedName}` : symbol.escapedName;
  }
  function getUnresolvedSymbolForEntityName(name) {
    const identifier = name.kind === 166 /* QualifiedName */ ? name.right : name.kind === 211 /* PropertyAccessExpression */ ? name.name : name;
    const text = identifier.escapedText;
    if (text) {
      const parentSymbol = name.kind === 166 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : name.kind === 211 /* PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : void 0;
      const path = parentSymbol ? `${getSymbolPath(parentSymbol)}.${text}` : text;
      let result = unresolvedSymbols.get(path);
      if (!result) {
        unresolvedSymbols.set(path, result = createSymbol(524288 /* TypeAlias */, text, 1048576 /* Unresolved */));
        result.parent = parentSymbol;
        result.links.declaredType = unresolvedType;
      }
      return result;
    }
    return unknownSymbol;
  }
  function resolveTypeReferenceName(typeReference, meaning, ignoreErrors) {
    const name = getTypeReferenceName(typeReference);
    if (!name) {
      return unknownSymbol;
    }
    const symbol = resolveEntityName(name, meaning, ignoreErrors);
    return symbol && symbol !== unknownSymbol ? symbol : ignoreErrors ? unknownSymbol : getUnresolvedSymbolForEntityName(name);
  }
  function getTypeReferenceType(node, symbol) {
    if (symbol === unknownSymbol) {
      return errorType;
    }
    symbol = getExpandoSymbol(symbol) || symbol;
    if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
      return getTypeFromClassOrInterfaceReference(node, symbol);
    }
    if (symbol.flags & 524288 /* TypeAlias */) {
      return getTypeFromTypeAliasReference(node, symbol);
    }
    const res = tryGetDeclaredTypeOfSymbol(symbol);
    if (res) {
      return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
    }
    if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
      const jsdocType = getTypeFromJSDocValueReference(node, symbol);
      if (jsdocType) {
        return jsdocType;
      } else {
        resolveTypeReferenceName(node, 788968 /* Type */);
        return getTypeOfSymbol(symbol);
      }
    }
    return errorType;
  }
  function getTypeFromJSDocValueReference(node, symbol) {
    const links = getNodeLinks(node);
    if (!links.resolvedJSDocType) {
      const valueType = getTypeOfSymbol(symbol);
      let typeType = valueType;
      if (symbol.valueDeclaration) {
        const isImportTypeWithQualifier = node.kind === 205 /* ImportType */ && node.qualifier;
        if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) {
          typeType = getTypeReferenceType(node, valueType.symbol);
        }
      }
      links.resolvedJSDocType = typeType;
    }
    return links.resolvedJSDocType;
  }
  function getNoInferType(type) {
    return isNoInferTargetType(type) ? getOrCreateSubstitutionType(type, unknownType) : type;
  }
  function isNoInferTargetType(type) {
    return !!(type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, isNoInferTargetType) || type.flags & 33554432 /* Substitution */ && !isNoInferType(type) && isNoInferTargetType(type.baseType) || type.flags & 524288 /* Object */ && !isEmptyAnonymousObjectType(type) || type.flags & (465829888 /* Instantiable */ & ~33554432 /* Substitution */) && !isPatternLiteralType(type));
  }
  function isNoInferType(type) {
    return !!(type.flags & 33554432 /* Substitution */ && type.constraint.flags & 2 /* Unknown */);
  }
  function getSubstitutionType(baseType, constraint) {
    return constraint.flags & 3 /* AnyOrUnknown */ || constraint === baseType || baseType.flags & 1 /* Any */ ? baseType : getOrCreateSubstitutionType(baseType, constraint);
  }
  function getOrCreateSubstitutionType(baseType, constraint) {
    const id = `${getTypeId(baseType)}>${getTypeId(constraint)}`;
    const cached = substitutionTypes.get(id);
    if (cached) {
      return cached;
    }
    const result = createType(33554432 /* Substitution */);
    result.baseType = baseType;
    result.constraint = constraint;
    substitutionTypes.set(id, result);
    return result;
  }
  function getSubstitutionIntersection(substitutionType) {
    return isNoInferType(substitutionType) ? substitutionType.baseType : getIntersectionType([substitutionType.constraint, substitutionType.baseType]);
  }
  function isUnaryTupleTypeNode(node) {
    return node.kind === 189 /* TupleType */ && node.elements.length === 1;
  }
  function getImpliedConstraint(type, checkNode, extendsNode) {
    return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : void 0;
  }
  function getConditionalFlowTypeOfType(type, node) {
    let constraints;
    let covariant = true;
    while (node && !isStatement(node) && node.kind !== 320 /* JSDoc */) {
      const parent = node.parent;
      if (parent.kind === 169 /* Parameter */) {
        covariant = !covariant;
      }
      if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 194 /* ConditionalType */ && node === parent.trueType) {
        const constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
        if (constraint) {
          constraints = append(constraints, constraint);
        }
      } else if (type.flags & 262144 /* TypeParameter */ && parent.kind === 200 /* MappedType */ && !parent.nameType && node === parent.type) {
        const mappedType = getTypeFromTypeNode(parent);
        if (getTypeParameterFromMappedType(mappedType) === getActualTypeVariable(type)) {
          const typeParameter = getHomomorphicTypeVariable(mappedType);
          if (typeParameter) {
            const constraint = getConstraintOfTypeParameter(typeParameter);
            if (constraint && everyType(constraint, isArrayOrTupleType)) {
              constraints = append(constraints, getUnionType([numberType, numericStringType]));
            }
          }
        }
      }
      node = parent;
    }
    return constraints ? getSubstitutionType(type, getIntersectionType(constraints)) : type;
  }
  function isJSDocTypeReference(node) {
    return !!(node.flags & 16777216 /* JSDoc */) && (node.kind === 183 /* TypeReference */ || node.kind === 205 /* ImportType */);
  }
  function checkNoTypeArguments(node, symbol) {
    if (node.typeArguments) {
      error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon);
      return false;
    }
    return true;
  }
  function getIntendedTypeFromJSDocTypeReference(node) {
    if (isIdentifier(node.typeName)) {
      const typeArgs = node.typeArguments;
      switch (node.typeName.escapedText) {
        case "String":
          checkNoTypeArguments(node);
          return stringType;
        case "Number":
          checkNoTypeArguments(node);
          return numberType;
        case "Boolean":
          checkNoTypeArguments(node);
          return booleanType;
        case "Void":
          checkNoTypeArguments(node);
          return voidType;
        case "Undefined":
          checkNoTypeArguments(node);
          return undefinedType;
        case "Null":
          checkNoTypeArguments(node);
          return nullType;
        case "Function":
        case "function":
          checkNoTypeArguments(node);
          return globalFunctionType;
        case "array":
          return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : void 0;
        case "promise":
          return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : void 0;
        case "Object":
          if (typeArgs && typeArgs.length === 2) {
            if (isJSDocIndexSignature(node)) {
              const indexed = getTypeFromTypeNode(typeArgs[0]);
              const target = getTypeFromTypeNode(typeArgs[1]);
              const indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo(
                indexed,
                target,
                /*isReadonly*/
                false
              )] : emptyArray;
              return createAnonymousType(
                /*symbol*/
                void 0,
                emptySymbols,
                emptyArray,
                emptyArray,
                indexInfo
              );
            }
            return anyType;
          }
          checkNoTypeArguments(node);
          return !noImplicitAny ? anyType : void 0;
      }
    }
  }
  function getTypeFromJSDocNullableTypeNode(node) {
    const type = getTypeFromTypeNode(node.type);
    return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
  }
  function getTypeFromTypeReference(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      if (isConstTypeReference(node) && isAssertionExpression(node.parent)) {
        links.resolvedSymbol = unknownSymbol;
        return links.resolvedType = checkExpressionCached(node.parent.expression);
      }
      let symbol;
      let type;
      const meaning = 788968 /* Type */;
      if (isJSDocTypeReference(node)) {
        type = getIntendedTypeFromJSDocTypeReference(node);
        if (!type) {
          symbol = resolveTypeReferenceName(
            node,
            meaning,
            /*ignoreErrors*/
            true
          );
          if (symbol === unknownSymbol) {
            symbol = resolveTypeReferenceName(node, meaning | 111551 /* Value */);
          } else {
            resolveTypeReferenceName(node, meaning);
          }
          type = getTypeReferenceType(node, symbol);
        }
      }
      if (!type) {
        symbol = resolveTypeReferenceName(node, meaning);
        type = getTypeReferenceType(node, symbol);
      }
      links.resolvedSymbol = symbol;
      links.resolvedType = type;
    }
    return links.resolvedType;
  }
  function typeArgumentsFromTypeReferenceNode(node) {
    return map(node.typeArguments, getTypeFromTypeNode);
  }
  function getTypeFromTypeQueryNode(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const type = checkExpressionWithTypeArguments(node);
      links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(type));
    }
    return links.resolvedType;
  }
  function getTypeOfGlobalSymbol(symbol, arity) {
    function getTypeDeclaration(symbol2) {
      const declarations = symbol2.declarations;
      if (declarations) {
        for (const declaration of declarations) {
          switch (declaration.kind) {
            case 263 /* ClassDeclaration */:
            case 264 /* InterfaceDeclaration */:
            case 266 /* EnumDeclaration */:
              return declaration;
          }
        }
      }
    }
    if (!symbol) {
      return arity ? emptyGenericType : emptyObjectType;
    }
    const type = getDeclaredTypeOfSymbol(symbol);
    if (!(type.flags & 524288 /* Object */)) {
      error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol));
      return arity ? emptyGenericType : emptyObjectType;
    }
    if (length(type.typeParameters) !== arity) {
      error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
      return arity ? emptyGenericType : emptyObjectType;
    }
    return type;
  }
  function getGlobalValueSymbol(name, reportErrors2) {
    return getGlobalSymbol(name, 111551 /* Value */, reportErrors2 ? Diagnostics.Cannot_find_global_value_0 : void 0);
  }
  function getGlobalTypeSymbol(name, reportErrors2) {
    return getGlobalSymbol(name, 788968 /* Type */, reportErrors2 ? Diagnostics.Cannot_find_global_type_0 : void 0);
  }
  function getGlobalTypeAliasSymbol(name, arity, reportErrors2) {
    const symbol = getGlobalSymbol(name, 788968 /* Type */, reportErrors2 ? Diagnostics.Cannot_find_global_type_0 : void 0);
    if (symbol) {
      getDeclaredTypeOfSymbol(symbol);
      if (length(getSymbolLinks(symbol).typeParameters) !== arity) {
        const decl = symbol.declarations && find(symbol.declarations, isTypeAliasDeclaration);
        error(decl, Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity);
        return void 0;
      }
    }
    return symbol;
  }
  function getGlobalSymbol(name, meaning, diagnostic) {
    return resolveName(
      /*location*/
      void 0,
      name,
      meaning,
      diagnostic,
      /*isUse*/
      false,
      /*excludeGlobals*/
      false
    );
  }
  function getGlobalType(name, arity, reportErrors2) {
    const symbol = getGlobalTypeSymbol(name, reportErrors2);
    return symbol || reportErrors2 ? getTypeOfGlobalSymbol(symbol, arity) : void 0;
  }
  function getGlobalBuiltinTypes(typeNames, arity) {
    let types;
    for (const typeName of typeNames) {
      types = append(types, getGlobalType(
        typeName,
        arity,
        /*reportErrors*/
        false
      ));
    }
    return types ?? emptyArray;
  }
  function getGlobalTypedPropertyDescriptorType() {
    return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType(
      "TypedPropertyDescriptor",
      /*arity*/
      1,
      /*reportErrors*/
      true
    ) || emptyGenericType);
  }
  function getGlobalTemplateStringsArrayType() {
    return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType(
      "TemplateStringsArray",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || emptyObjectType);
  }
  function getGlobalImportMetaType() {
    return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType(
      "ImportMeta",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || emptyObjectType);
  }
  function getGlobalImportMetaExpressionType() {
    if (!deferredGlobalImportMetaExpressionType) {
      const symbol = createSymbol(0 /* None */, "ImportMetaExpression");
      const importMetaType = getGlobalImportMetaType();
      const metaPropertySymbol = createSymbol(4 /* Property */, "meta", 8 /* Readonly */);
      metaPropertySymbol.parent = symbol;
      metaPropertySymbol.links.type = importMetaType;
      const members = createSymbolTable([metaPropertySymbol]);
      symbol.members = members;
      deferredGlobalImportMetaExpressionType = createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
    }
    return deferredGlobalImportMetaExpressionType;
  }
  function getGlobalImportCallOptionsType(reportErrors2) {
    return deferredGlobalImportCallOptionsType || (deferredGlobalImportCallOptionsType = getGlobalType(
      "ImportCallOptions",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalImportAttributesType(reportErrors2) {
    return deferredGlobalImportAttributesType || (deferredGlobalImportAttributesType = getGlobalType(
      "ImportAttributes",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalESSymbolConstructorSymbol(reportErrors2) {
    return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors2));
  }
  function getGlobalESSymbolConstructorTypeSymbol(reportErrors2) {
    return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors2));
  }
  function getGlobalESSymbolType() {
    return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType(
      "Symbol",
      /*arity*/
      0,
      /*reportErrors*/
      false
    )) || emptyObjectType;
  }
  function getGlobalPromiseType(reportErrors2) {
    return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType(
      "Promise",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalPromiseLikeType(reportErrors2) {
    return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType(
      "PromiseLike",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalPromiseConstructorSymbol(reportErrors2) {
    return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors2));
  }
  function getGlobalPromiseConstructorLikeType(reportErrors2) {
    return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType(
      "PromiseConstructorLike",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalAsyncIterableType(reportErrors2) {
    return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType(
      "AsyncIterable",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalAsyncIteratorType(reportErrors2) {
    return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType(
      "AsyncIterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalAsyncIterableIteratorType(reportErrors2) {
    return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType(
      "AsyncIterableIterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalBuiltinAsyncIteratorTypes() {
    return deferredGlobalBuiltinAsyncIteratorTypes ?? (deferredGlobalBuiltinAsyncIteratorTypes = getGlobalBuiltinTypes(["ReadableStreamAsyncIterator"], 1));
  }
  function getGlobalAsyncIteratorObjectType(reportErrors2) {
    return deferredGlobalAsyncIteratorObjectType || (deferredGlobalAsyncIteratorObjectType = getGlobalType(
      "AsyncIteratorObject",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalAsyncGeneratorType(reportErrors2) {
    return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType(
      "AsyncGenerator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIterableType(reportErrors2) {
    return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType(
      "Iterable",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIteratorType(reportErrors2) {
    return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType(
      "Iterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIterableIteratorType(reportErrors2) {
    return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType(
      "IterableIterator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getBuiltinIteratorReturnType() {
    return strictBuiltinIteratorReturn ? undefinedType : anyType;
  }
  function getGlobalBuiltinIteratorTypes() {
    return deferredGlobalBuiltinIteratorTypes ?? (deferredGlobalBuiltinIteratorTypes = getGlobalBuiltinTypes(["ArrayIterator", "MapIterator", "SetIterator", "StringIterator"], 1));
  }
  function getGlobalIteratorObjectType(reportErrors2) {
    return deferredGlobalIteratorObjectType || (deferredGlobalIteratorObjectType = getGlobalType(
      "IteratorObject",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalGeneratorType(reportErrors2) {
    return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType(
      "Generator",
      /*arity*/
      3,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIteratorYieldResultType(reportErrors2) {
    return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType(
      "IteratorYieldResult",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalIteratorReturnResultType(reportErrors2) {
    return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType(
      "IteratorReturnResult",
      /*arity*/
      1,
      reportErrors2
    )) || emptyGenericType;
  }
  function getGlobalDisposableType(reportErrors2) {
    return deferredGlobalDisposableType || (deferredGlobalDisposableType = getGlobalType(
      "Disposable",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalAsyncDisposableType(reportErrors2) {
    return deferredGlobalAsyncDisposableType || (deferredGlobalAsyncDisposableType = getGlobalType(
      "AsyncDisposable",
      /*arity*/
      0,
      reportErrors2
    )) || emptyObjectType;
  }
  function getGlobalTypeOrUndefined(name, arity = 0) {
    const symbol = getGlobalSymbol(
      name,
      788968 /* Type */,
      /*diagnostic*/
      void 0
    );
    return symbol && getTypeOfGlobalSymbol(symbol, arity);
  }
  function getGlobalExtractSymbol() {
    deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalTypeAliasSymbol(
      "Extract",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol);
    return deferredGlobalExtractSymbol === unknownSymbol ? void 0 : deferredGlobalExtractSymbol;
  }
  function getGlobalOmitSymbol() {
    deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalTypeAliasSymbol(
      "Omit",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol);
    return deferredGlobalOmitSymbol === unknownSymbol ? void 0 : deferredGlobalOmitSymbol;
  }
  function getGlobalAwaitedSymbol(reportErrors2) {
    deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeAliasSymbol(
      "Awaited",
      /*arity*/
      1,
      reportErrors2
    ) || (reportErrors2 ? unknownSymbol : void 0));
    return deferredGlobalAwaitedSymbol === unknownSymbol ? void 0 : deferredGlobalAwaitedSymbol;
  }
  function getGlobalBigIntType() {
    return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType(
      "BigInt",
      /*arity*/
      0,
      /*reportErrors*/
      false
    )) || emptyObjectType;
  }
  function getGlobalClassDecoratorContextType(reportErrors2) {
    return deferredGlobalClassDecoratorContextType ?? (deferredGlobalClassDecoratorContextType = getGlobalType(
      "ClassDecoratorContext",
      /*arity*/
      1,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassMethodDecoratorContextType(reportErrors2) {
    return deferredGlobalClassMethodDecoratorContextType ?? (deferredGlobalClassMethodDecoratorContextType = getGlobalType(
      "ClassMethodDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassGetterDecoratorContextType(reportErrors2) {
    return deferredGlobalClassGetterDecoratorContextType ?? (deferredGlobalClassGetterDecoratorContextType = getGlobalType(
      "ClassGetterDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassSetterDecoratorContextType(reportErrors2) {
    return deferredGlobalClassSetterDecoratorContextType ?? (deferredGlobalClassSetterDecoratorContextType = getGlobalType(
      "ClassSetterDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorContextType(reportErrors2) {
    return deferredGlobalClassAccessorDecoratorContextType ?? (deferredGlobalClassAccessorDecoratorContextType = getGlobalType(
      "ClassAccessorDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorTargetType(reportErrors2) {
    return deferredGlobalClassAccessorDecoratorTargetType ?? (deferredGlobalClassAccessorDecoratorTargetType = getGlobalType(
      "ClassAccessorDecoratorTarget",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassAccessorDecoratorResultType(reportErrors2) {
    return deferredGlobalClassAccessorDecoratorResultType ?? (deferredGlobalClassAccessorDecoratorResultType = getGlobalType(
      "ClassAccessorDecoratorResult",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalClassFieldDecoratorContextType(reportErrors2) {
    return deferredGlobalClassFieldDecoratorContextType ?? (deferredGlobalClassFieldDecoratorContextType = getGlobalType(
      "ClassFieldDecoratorContext",
      /*arity*/
      2,
      reportErrors2
    )) ?? emptyGenericType;
  }
  function getGlobalNaNSymbol() {
    return deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol(
      "NaN",
      /*reportErrors*/
      false
    ));
  }
  function getGlobalRecordSymbol() {
    deferredGlobalRecordSymbol || (deferredGlobalRecordSymbol = getGlobalTypeAliasSymbol(
      "Record",
      /*arity*/
      2,
      /*reportErrors*/
      true
    ) || unknownSymbol);
    return deferredGlobalRecordSymbol === unknownSymbol ? void 0 : deferredGlobalRecordSymbol;
  }
  function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
    return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
  }
  function createTypedPropertyDescriptorType(propertyType) {
    return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
  }
  function createIterableType(iteratedType) {
    return createTypeFromGenericGlobalType(getGlobalIterableType(
      /*reportErrors*/
      true
    ), [iteratedType, voidType, undefinedType]);
  }
  function createArrayType(elementType, readonly) {
    return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
  }
  function getTupleElementFlags(node) {
    switch (node.kind) {
      case 190 /* OptionalType */:
        return 2 /* Optional */;
      case 191 /* RestType */:
        return getRestTypeElementFlags(node);
      case 202 /* NamedTupleMember */:
  