etAllAccessorDeclarations(node.parent.members, node);
          if (hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) {
            return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
          }
        }
        if (flags & ~(1025 /* ExportDefault */ | 131072 /* Decorator */)) {
          return grammarErrorOnNode(modifier, Diagnostics.Decorators_are_not_valid_here);
        }
        if (hasLeadingDecorators && flags & 126975 /* Modifier */) {
          Debug.assertIsDefined(firstDecorator);
          const sourceFile = getSourceFileOfNode(modifier);
          if (!hasParseDiagnostics(sourceFile)) {
            addRelatedInfo(
              error(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export),
              createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)
            );
            return true;
          }
          return false;
        }
        flags |= 131072 /* Decorator */;
        if (!(flags & 126975 /* Modifier */)) {
          hasLeadingDecorators = true;
        } else if (flags & 1 /* Export */) {
          sawExportBeforeDecorators = true;
        }
        firstDecorator ?? (firstDecorator = modifier);
      } else {
        if (modifier.kind !== 148 /* ReadonlyKeyword */) {
          if (node.kind === 170 /* PropertySignature */ || node.kind === 172 /* MethodSignature */) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind));
          }
          if (node.kind === 180 /* IndexSignature */ && (modifier.kind !== 126 /* StaticKeyword */ || !isClassLike(node.parent))) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind));
          }
        }
        if (modifier.kind !== 103 /* InKeyword */ && modifier.kind !== 147 /* OutKeyword */ && modifier.kind !== 87 /* ConstKeyword */) {
          if (node.kind === 167 /* TypeParameter */) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind));
          }
        }
        switch (modifier.kind) {
          case 87 /* ConstKeyword */:
            if (node.kind !== 265 /* EnumDeclaration */ && node.kind !== 167 /* TypeParameter */) {
              return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(87 /* ConstKeyword */));
            }
            const parent2 = node.parent;
            if (node.kind === 167 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent2) || isClassLike(parent2) || isFunctionTypeNode(parent2) || isConstructorTypeNode(parent2) || isCallSignatureDeclaration(parent2) || isConstructSignatureDeclaration(parent2) || isMethodSignature(parent2))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind));
            }
            break;
          case 163 /* OverrideKeyword */:
            if (flags & 16384 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override");
            } else if (flags & 2 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare");
            } else if (flags & 64 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly");
            } else if (flags & 128 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor");
            } else if (flags & 512 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async");
            }
            flags |= 16384 /* Override */;
            lastOverride = modifier;
            break;
          case 125 /* PublicKeyword */:
          case 124 /* ProtectedKeyword */:
          case 123 /* PrivateKeyword */:
            const text = visibilityToString(modifierToFlag(modifier.kind));
            if (flags & 28 /* AccessibilityModifier */) {
              return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen);
            } else if (flags & 16384 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override");
            } else if (flags & 32 /* Static */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
            } else if (flags & 128 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor");
            } else if (flags & 64 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
            } else if (flags & 512 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
            } else if (node.parent.kind === 267 /* ModuleBlock */ || node.parent.kind === 311 /* SourceFile */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
            } else if (flags & 256 /* Abstract */) {
              if (modifier.kind === 123 /* PrivateKeyword */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
              } else {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
              }
            } else if (isPrivateIdentifierClassElementDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
            }
            flags |= modifierToFlag(modifier.kind);
            break;
          case 126 /* StaticKeyword */:
            if (flags & 32 /* Static */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static");
            } else if (flags & 64 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
            } else if (flags & 512 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
            } else if (flags & 128 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor");
            } else if (node.parent.kind === 267 /* ModuleBlock */ || node.parent.kind === 311 /* SourceFile */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
            } else if (node.kind === 168 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
            } else if (flags & 256 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
            } else if (flags & 16384 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override");
            }
            flags |= 32 /* Static */;
            lastStatic = modifier;
            break;
          case 129 /* AccessorKeyword */:
            if (flags & 128 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor");
            } else if (flags & 64 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly");
            } else if (flags & 2 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare");
            } else if (node.kind !== 171 /* PropertyDeclaration */) {
              return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration);
            }
            flags |= 128 /* Accessor */;
            break;
          case 148 /* ReadonlyKeyword */:
            if (flags & 64 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly");
            } else if (node.kind !== 171 /* PropertyDeclaration */ && node.kind !== 170 /* PropertySignature */ && node.kind !== 180 /* IndexSignature */ && node.kind !== 168 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
            } else if (flags & 128 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor");
            }
            flags |= 64 /* Readonly */;
            break;
          case 95 /* ExportKeyword */:
            if (compilerOptions.verbatimModuleSyntax && !(node.flags & 16777216 /* Ambient */) && node.kind !== 264 /* TypeAliasDeclaration */ && node.kind !== 263 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later
            node.kind !== 266 /* ModuleDeclaration */ && node.parent.kind === 311 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) {
              return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
            }
            if (flags & 1 /* Export */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export");
            } else if (flags & 2 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
            } else if (flags & 256 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
            } else if (flags & 512 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
            } else if (isClassLike(node.parent)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
            } else if (node.kind === 168 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
            }
            flags |= 1 /* Export */;
            break;
          case 90 /* DefaultKeyword */:
            const container = node.parent.kind === 311 /* SourceFile */ ? node.parent : node.parent.parent;
            if (container.kind === 266 /* ModuleDeclaration */ && !isAmbientModule(container)) {
              return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
            } else if (!(flags & 1 /* Export */)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default");
            } else if (sawExportBeforeDecorators) {
              return grammarErrorOnNode(firstDecorator, Diagnostics.Decorators_are_not_valid_here);
            }
            flags |= 1024 /* Default */;
            break;
          case 138 /* DeclareKeyword */:
            if (flags & 2 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare");
            } else if (flags & 512 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (flags & 16384 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override");
            } else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
            } else if (node.kind === 168 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
            } else if (node.parent.flags & 16777216 /* Ambient */ && node.parent.kind === 267 /* ModuleBlock */) {
              return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
            } else if (isPrivateIdentifierClassElementDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
            } else if (flags & 128 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor");
            }
            flags |= 2 /* Ambient */;
            lastDeclare = modifier;
            break;
          case 128 /* AbstractKeyword */:
            if (flags & 256 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract");
            }
            if (node.kind !== 262 /* ClassDeclaration */ && node.kind !== 184 /* ConstructorType */) {
              if (node.kind !== 173 /* MethodDeclaration */ && node.kind !== 171 /* PropertyDeclaration */ && node.kind !== 176 /* GetAccessor */ && node.kind !== 177 /* SetAccessor */) {
                return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
              }
              if (!(node.parent.kind === 262 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 256 /* Abstract */))) {
                const message = node.kind === 171 /* PropertyDeclaration */ ? Diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class : Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class;
                return grammarErrorOnNode(modifier, message);
              }
              if (flags & 32 /* Static */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
              }
              if (flags & 8 /* Private */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
              }
              if (flags & 512 /* Async */ && lastAsync) {
                return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
              }
              if (flags & 16384 /* Override */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override");
              }
              if (flags & 128 /* Accessor */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor");
              }
            }
            if (isNamedDeclaration(node) && node.name.kind === 81 /* PrivateIdentifier */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
            }
            flags |= 256 /* Abstract */;
            break;
          case 134 /* AsyncKeyword */:
            if (flags & 512 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async");
            } else if (flags & 2 /* Ambient */ || node.parent.flags & 16777216 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (node.kind === 168 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
            }
            if (flags & 256 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
            }
            flags |= 512 /* Async */;
            lastAsync = modifier;
            break;
          case 103 /* InKeyword */:
          case 147 /* OutKeyword */:
            const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 32768 /* In */ : 65536 /* Out */;
            const inOutText = modifier.kind === 103 /* InKeyword */ ? "in" : "out";
            if (node.kind !== 167 /* TypeParameter */ || !(isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText);
            }
            if (flags & inOutFlag) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText);
            }
            if (inOutFlag & 32768 /* In */ && flags & 65536 /* Out */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out");
            }
            flags |= inOutFlag;
            break;
        }
      }
    }
    if (node.kind === 175 /* Constructor */) {
      if (flags & 32 /* Static */) {
        return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
      }
      if (flags & 16384 /* Override */) {
        return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override");
      }
      if (flags & 512 /* Async */) {
        return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
      }
      return false;
    } else if ((node.kind === 271 /* ImportDeclaration */ || node.kind === 270 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
      return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
    } else if (node.kind === 168 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
    } else if (node.kind === 168 /* Parameter */ && flags & 16476 /* ParameterPropertyModifier */ && node.dotDotDotToken) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
    }
    if (flags & 512 /* Async */) {
      return checkGrammarAsyncModifier(node, lastAsync);
    }
    return false;
  }
  function reportObviousModifierErrors(node) {
    if (!node.modifiers)
      return false;
    const modifier = findFirstIllegalModifier(node);
    return modifier && grammarErrorOnFirstToken(modifier, Diagnostics.Modifiers_cannot_appear_here);
  }
  function findFirstModifierExcept(node, allowedModifier) {
    const modifier = find(node.modifiers, isModifier);
    return modifier && modifier.kind !== allowedModifier ? modifier : void 0;
  }
  function findFirstIllegalModifier(node) {
    switch (node.kind) {
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
      case 175 /* Constructor */:
      case 171 /* PropertyDeclaration */:
      case 170 /* PropertySignature */:
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
      case 180 /* IndexSignature */:
      case 266 /* ModuleDeclaration */:
      case 271 /* ImportDeclaration */:
      case 270 /* ImportEqualsDeclaration */:
      case 277 /* ExportDeclaration */:
      case 276 /* ExportAssignment */:
      case 217 /* FunctionExpression */:
      case 218 /* ArrowFunction */:
      case 168 /* Parameter */:
      case 167 /* TypeParameter */:
        return void 0;
      case 174 /* ClassStaticBlockDeclaration */:
      case 302 /* PropertyAssignment */:
      case 303 /* ShorthandPropertyAssignment */:
      case 269 /* NamespaceExportDeclaration */:
      case 281 /* MissingDeclaration */:
        return find(node.modifiers, isModifier);
      default:
        if (node.parent.kind === 267 /* ModuleBlock */ || node.parent.kind === 311 /* SourceFile */) {
          return void 0;
        }
        switch (node.kind) {
          case 261 /* FunctionDeclaration */:
            return findFirstModifierExcept(node, 134 /* AsyncKeyword */);
          case 262 /* ClassDeclaration */:
          case 184 /* ConstructorType */:
            return findFirstModifierExcept(node, 128 /* AbstractKeyword */);
          case 230 /* ClassExpression */:
          case 263 /* InterfaceDeclaration */:
          case 242 /* VariableStatement */:
          case 264 /* TypeAliasDeclaration */:
            return find(node.modifiers, isModifier);
          case 265 /* EnumDeclaration */:
            return findFirstModifierExcept(node, 87 /* ConstKeyword */);
          default:
            Debug.assertNever(node);
        }
    }
  }
  function reportObviousDecoratorErrors(node) {
    const decorator = findFirstIllegalDecorator(node);
    return decorator && grammarErrorOnFirstToken(decorator, Diagnostics.Decorators_are_not_valid_here);
  }
  function findFirstIllegalDecorator(node) {
    return canHaveIllegalDecorators(node) ? find(node.modifiers, isDecorator) : void 0;
  }
  function checkGrammarAsyncModifier(node, asyncModifier) {
    switch (node.kind) {
      case 173 /* MethodDeclaration */:
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
      case 218 /* ArrowFunction */:
        return false;
    }
    return grammarErrorOnNode(asyncModifier, Diagnostics._0_modifier_cannot_be_used_here, "async");
  }
  function checkGrammarForDisallowedTrailingComma(list, diag2 = Diagnostics.Trailing_comma_not_allowed) {
    if (list && list.hasTrailingComma) {
      return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag2);
    }
    return false;
  }
  function checkGrammarTypeParameterList(typeParameters, file) {
    if (typeParameters && typeParameters.length === 0) {
      const start2 = typeParameters.pos - "<".length;
      const end = skipTrivia(file.text, typeParameters.end) + ">".length;
      return grammarErrorAtPos(file, start2, end - start2, Diagnostics.Type_parameter_list_cannot_be_empty);
    }
    return false;
  }
  function checkGrammarParameterList(parameters) {
    let seenOptionalParameter = false;
    const parameterCount = parameters.length;
    for (let i = 0; i < parameterCount; i++) {
      const parameter = parameters[i];
      if (parameter.dotDotDotToken) {
        if (i !== parameterCount - 1) {
          return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
        }
        if (!(parameter.flags & 16777216 /* Ambient */)) {
          checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
        }
        if (parameter.questionToken) {
          return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_rest_parameter_cannot_be_optional);
        }
        if (parameter.initializer) {
          return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer);
        }
      } else if (isOptionalParameter(parameter)) {
        seenOptionalParameter = true;
        if (parameter.questionToken && parameter.initializer) {
          return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
        }
      } else if (seenOptionalParameter && !parameter.initializer) {
        return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
      }
    }
  }
  function getNonSimpleParameters(parameters) {
    return filter(parameters, (parameter) => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter));
  }
  function checkGrammarForUseStrictSimpleParameterList(node) {
    if (languageVersion >= 3 /* ES2016 */) {
      const useStrictDirective = node.body && isBlock(node.body) && findUseStrictPrologue(node.body.statements);
      if (useStrictDirective) {
        const nonSimpleParameters = getNonSimpleParameters(node.parameters);
        if (length(nonSimpleParameters)) {
          forEach(nonSimpleParameters, (parameter) => {
            addRelatedInfo(
              error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive),
              createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here)
            );
          });
          const diagnostics2 = nonSimpleParameters.map((parameter, index) => index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here));
          addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2);
          return true;
        }
      }
    }
    return false;
  }
  function checkGrammarFunctionLikeDeclaration(node) {
    const file = getSourceFileOfNode(node);
    return checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node);
  }
  function checkGrammarClassLikeDeclaration(node) {
    const file = getSourceFileOfNode(node);
    return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
  }
  function checkGrammarArrowFunction(node, file) {
    if (!isArrowFunction(node)) {
      return false;
    }
    if (node.typeParameters && !(length(node.typeParameters) > 1 || node.typeParameters.hasTrailingComma || node.typeParameters[0].constraint)) {
      if (file && fileExtensionIsOneOf(file.fileName, [".mts" /* Mts */, ".cts" /* Cts */])) {
        grammarErrorOnNode(node.typeParameters[0], Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint);
      }
    }
    const { equalsGreaterThanToken } = node;
    const startLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
    const endLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
    return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow);
  }
  function checkGrammarIndexSignatureParameters(node) {
    const parameter = node.parameters[0];
    if (node.parameters.length !== 1) {
      if (parameter) {
        return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_must_have_exactly_one_parameter);
      } else {
        return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_exactly_one_parameter);
      }
    }
    checkGrammarForDisallowedTrailingComma(node.parameters, Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
    if (parameter.dotDotDotToken) {
      return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
    }
    if (hasEffectiveModifiers(parameter)) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
    }
    if (parameter.questionToken) {
      return grammarErrorOnNode(parameter.questionToken, Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
    }
    if (parameter.initializer) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
    }
    if (!parameter.type) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
    }
    const type = getTypeFromTypeNode(parameter.type);
    if (someType(type, (t) => !!(t.flags & 8576 /* StringOrNumberLiteralOrUnique */)) || isGenericType(type)) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead);
    }
    if (!everyType(type, isValidIndexKeyType)) {
      return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type);
    }
    if (!node.type) {
      return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_a_type_annotation);
    }
    return false;
  }
  function checkGrammarIndexSignature(node) {
    return checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node);
  }
  function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
    if (typeArguments && typeArguments.length === 0) {
      const sourceFile = getSourceFileOfNode(node);
      const start2 = typeArguments.pos - "<".length;
      const end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
      return grammarErrorAtPos(sourceFile, start2, end - start2, Diagnostics.Type_argument_list_cannot_be_empty);
    }
    return false;
  }
  function checkGrammarTypeArguments(node, typeArguments) {
    return checkGrammarForDisallowedTrailingComma(typeArguments) || checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
  }
  function checkGrammarTaggedTemplateChain(node) {
    if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
      return grammarErrorOnNode(node.template, Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
    }
    return false;
  }
  function checkGrammarHeritageClause(node) {
    const types = node.types;
    if (checkGrammarForDisallowedTrailingComma(types)) {
      return true;
    }
    if (types && types.length === 0) {
      const listType = tokenToString(node.token);
      return grammarErrorAtPos(node, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType);
    }
    return some(types, checkGrammarExpressionWithTypeArguments);
  }
  function checkGrammarExpressionWithTypeArguments(node) {
    if (isExpressionWithTypeArguments(node) && isImportKeyword(node.expression) && node.typeArguments) {
      return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
    }
    return checkGrammarTypeArguments(node, node.typeArguments);
  }
  function checkGrammarClassDeclarationHeritageClauses(node) {
    let seenExtendsClause = false;
    let seenImplementsClause = false;
    if (!checkGrammarModifiers(node) && node.heritageClauses) {
      for (const heritageClause of node.heritageClauses) {
        if (heritageClause.token === 96 /* ExtendsKeyword */) {
          if (seenExtendsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen);
          }
          if (seenImplementsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_must_precede_implements_clause);
          }
          if (heritageClause.types.length > 1) {
            return grammarErrorOnFirstToken(heritageClause.types[1], Diagnostics.Classes_can_only_extend_a_single_class);
          }
          seenExtendsClause = true;
        } else {
          Debug.assert(heritageClause.token === 119 /* ImplementsKeyword */);
          if (seenImplementsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.implements_clause_already_seen);
          }
          seenImplementsClause = true;
        }
        checkGrammarHeritageClause(heritageClause);
      }
    }
  }
  function checkGrammarInterfaceDeclaration(node) {
    let seenExtendsClause = false;
    if (node.heritageClauses) {
      for (const heritageClause of node.heritageClauses) {
        if (heritageClause.token === 96 /* ExtendsKeyword */) {
          if (seenExtendsClause) {
            return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen);
          }
          seenExtendsClause = true;
        } else {
          Debug.assert(heritageClause.token === 119 /* ImplementsKeyword */);
          return grammarErrorOnFirstToken(heritageClause, Diagnostics.Interface_declaration_cannot_have_implements_clause);
        }
        checkGrammarHeritageClause(heritageClause);
      }
    }
    return false;
  }
  function checkGrammarComputedPropertyName(node) {
    if (node.kind !== 166 /* ComputedPropertyName */) {
      return false;
    }
    const computedPropertyName = node;
    if (computedPropertyName.expression.kind === 225 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 28 /* CommaToken */) {
      return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
    }
    return false;
  }
  function checkGrammarForGenerator(node) {
    if (node.asteriskToken) {
      Debug.assert(
        node.kind === 261 /* FunctionDeclaration */ || node.kind === 217 /* FunctionExpression */ || node.kind === 173 /* MethodDeclaration */
      );
      if (node.flags & 16777216 /* Ambient */) {
        return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
      }
      if (!node.body) {
        return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
      }
    }
  }
  function checkGrammarForInvalidQuestionMark(questionToken, message) {
    return !!questionToken && grammarErrorOnNode(questionToken, message);
  }
  function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
    return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
  }
  function checkGrammarObjectLiteralExpression(node, inDestructuring) {
    const seen = /* @__PURE__ */ new Map();
    for (const prop of node.properties) {
      if (prop.kind === 304 /* SpreadAssignment */) {
        if (inDestructuring) {
          const expression = skipParentheses(prop.expression);
          if (isArrayLiteralExpression(expression) || isObjectLiteralExpression(expression)) {
            return grammarErrorOnNode(prop.expression, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
          }
        }
        continue;
      }
      const name = prop.name;
      if (name.kind === 166 /* ComputedPropertyName */) {
        checkGrammarComputedPropertyName(name);
      }
      if (prop.kind === 303 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
        grammarErrorOnNode(prop.equalsToken, Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern);
      }
      if (name.kind === 81 /* PrivateIdentifier */) {
        grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
      }
      if (canHaveModifiers(prop) && prop.modifiers) {
        for (const mod of prop.modifiers) {
          if (isModifier(mod) && (mod.kind !== 134 /* AsyncKeyword */ || prop.kind !== 173 /* MethodDeclaration */)) {
            grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod));
          }
        }
      } else if (canHaveIllegalModifiers(prop) && prop.modifiers) {
        for (const mod of prop.modifiers) {
          if (isModifier(mod)) {
            grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod));
          }
        }
      }
      let currentKind;
      switch (prop.kind) {
        case 303 /* ShorthandPropertyAssignment */:
        case 302 /* PropertyAssignment */:
          checkGrammarForInvalidExclamationToken(prop.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
          checkGrammarForInvalidQuestionMark(prop.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional);
          if (name.kind === 9 /* NumericLiteral */) {
            checkGrammarNumericLiteral(name);
          }
          currentKind = 4 /* PropertyAssignment */;
          break;
        case 173 /* MethodDeclaration */:
          currentKind = 8 /* Method */;
          break;
        case 176 /* GetAccessor */:
          currentKind = 1 /* GetAccessor */;
          break;
        case 177 /* SetAccessor */:
          currentKind = 2 /* SetAccessor */;
          break;
        default:
          Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
      }
      if (!inDestructuring) {
        const effectiveName = getEffectivePropertyNameForPropertyNameNode(name);
        if (effectiveName === void 0) {
          continue;
        }
        const existingKind = seen.get(effectiveName);
        if (!existingKind) {
          seen.set(effectiveName, currentKind);
        } else {
          if (currentKind & 8 /* Method */ && existingKind & 8 /* Method */) {
            grammarErrorOnNode(name, Diagnostics.Duplicate_identifier_0, getTextOfNode(name));
          } else if (currentKind & 4 /* PropertyAssignment */ && existingKind & 4 /* PropertyAssignment */) {
            grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name, getTextOfNode(name));
          } else if (currentKind & 3 /* GetOrSetAccessor */ && existingKind & 3 /* GetOrSetAccessor */) {
            if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
              seen.set(effectiveName, currentKind | existingKind);
            } else {
              return grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
            }
          } else {
            return grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
          }
        }
      }
    }
  }
  function checkGrammarJsxElement(node) {
    checkGrammarJsxName(node.tagName);
    checkGrammarTypeArguments(node, node.typeArguments);
    const seen = /* @__PURE__ */ new Map();
    for (const attr of node.attributes.properties) {
      if (attr.kind === 292 /* JsxSpreadAttribute */) {
        continue;
      }
      const { name, initializer } = attr;
      const escapedText = getEscapedTextOfJsxAttributeName(name);
      if (!seen.get(escapedText)) {
        seen.set(escapedText, true);
      } else {
        return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
      }
      if (initializer && initializer.kind === 293 /* JsxExpression */ && !initializer.expression) {
        return grammarErrorOnNode(initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
      }
    }
  }
  function checkGrammarJsxName(node) {
    if (isPropertyAccessExpression(node) && isJsxNamespacedName(node.expression)) {
      return grammarErrorOnNode(node.expression, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names);
    }
    if (isJsxNamespacedName(node) && getJSXTransformEnabled(compilerOptions) && !isIntrinsicJsxName(node.namespace.escapedText)) {
      return grammarErrorOnNode(node, Diagnostics.React_components_cannot_include_JSX_namespace_names);
    }
  }
  function checkGrammarJsxExpression(node) {
    if (node.expression && isCommaSequence(node.expression)) {
      return grammarErrorOnNode(node.expression, Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
    }
  }
  function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
    if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
      return true;
    }
    if (forInOrOfStatement.kind === 249 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
      if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) {
        const sourceFile = getSourceFileOfNode(forInOrOfStatement);
        if (isInTopLevelContext(forInOrOfStatement)) {
          if (!hasParseDiagnostics(sourceFile)) {
            if (!isEffectiveExternalModule(sourceFile, compilerOptions)) {
              diagnostics.add(createDiagnosticForNode(
                forInOrOfStatement.awaitModifier,
                Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module
              ));
            }
            switch (moduleKind) {
              case 100 /* Node16 */:
              case 199 /* NodeNext */:
                if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) {
                  diagnostics.add(
                    createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)
                  );
                  break;
                }
              case 7 /* ES2022 */:
              case 99 /* ESNext */:
              case 4 /* System */:
                if (languageVersion >= 4 /* ES2017 */) {
                  break;
                }
              default:
                diagnostics.add(
                  createDiagnosticForNode(
                    forInOrOfStatement.awaitModifier,
                    Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher
                  )
                );
                break;
            }
          }
        } else {
          if (!hasParseDiagnostics(sourceFile)) {
            const diagnostic = createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
            const func = getContainingFunction(forInOrOfStatement);
            if (func && func.kind !== 175 /* Constructor */) {
              Debug.assert((getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
              const relatedInfo = createDiagnosticForNode(func, Diagnostics.Did_you_mean_to_mark_this_function_as_async);
              addRelatedInfo(diagnostic, relatedInfo);
            }
            diagnostics.add(diagnostic);
            return true;
          }
        }
        return false;
      }
    }
    if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 32768 /* AwaitContext */) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") {
      grammarErrorOnNode(forInOrOfStatement.initializer, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async);
      return false;
    }
    if (forInOrOfStatement.initializer.kind === 260 /* VariableDeclarationList */) {
      const variableList = forInOrOfStatement.initializer;
      if (!checkGrammarVariableDeclarationList(variableList)) {
        const declarations = variableList.declarations;
        if (!declarations.length) {
          return false;
        }
        if (declarations.length > 1) {
          const diagnostic = forInOrOfStatement.kind === 248 /* ForInStatement */ ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
          return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
        }
        const firstDeclaration = declarations[0];
        if (firstDeclaration.initializer) {
          const diagnostic = forInOrOfStatement.kind === 248 /* ForInStatement */ ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
          return grammarErrorOnNode(firstDeclaration.name, diagnostic);
        }
        if (firstDeclaration.type) {
          const diagnostic = forInOrOfStatement.kind === 248 /* ForInStatement */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
          return grammarErrorOnNode(firstDeclaration, diagnostic);
        }
      }
    }
    return false;
  }
  function checkGrammarAccessor(accessor) {
    if (!(accessor.flags & 16777216 /* Ambient */) && accessor.parent.kind !== 186 /* TypeLiteral */ && accessor.parent.kind !== 263 /* InterfaceDeclaration */) {
      if (languageVersion < 1 /* ES5 */) {
        return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
      }
      if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(accessor.name)) {
        return grammarErrorOnNode(accessor.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (accessor.body === void 0 && !hasSyntacticModifier(accessor, 256 /* Abstract */)) {
        return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, Diagnostics._0_expected, "{");
      }
    }
    if (accessor.body) {
      if (hasSyntacticModifier(accessor, 256 /* Abstract */)) {
        return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
      }
      if (accessor.parent.kind === 186 /* TypeLiteral */ || accessor.parent.kind === 263 /* InterfaceDeclaration */) {
        return grammarErrorOnNode(accessor.body, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
      }
    }
    if (accessor.typeParameters) {
      return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters);
    }
    if (!doesAccessorHaveCorrectParameterCount(accessor)) {
      return grammarErrorOnNode(
        accessor.name,
        accessor.kind === 176 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter
      );
    }
    if (accessor.kind === 177 /* SetAccessor */) {
      if (accessor.type) {
        return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
      }
      const parameter = Debug.checkDefined(getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
      if (parameter.dotDotDotToken) {
        return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter);
      }
      if (parameter.questionToken) {
        return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
      }
      if (parameter.initializer) {
        return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
      }
    }
    return false;
  }
  function doesAccessorHaveCorrectParameterCount(accessor) {
    return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 176 /* GetAccessor */ ? 0 : 1);
  }
  function getAccessorThisParameter(accessor) {
    if (accessor.parameters.length === (accessor.kind === 176 /* GetAccessor */ ? 1 : 2)) {
      return getThisParameter(accessor);
    }
  }
  function checkGrammarTypeOperatorNode(node) {
    if (node.operator === 158 /* UniqueKeyword */) {
      if (node.type.kind !== 155 /* SymbolKeyword */) {
        return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(155 /* SymbolKeyword */));
      }
      let parent2 = walkUpParenthesizedTypes(node.parent);
      if (isInJSFile(parent2) && isJSDocTypeExpression(parent2)) {
        const host2 = getJSDocHost(parent2);
        if (host2) {
          parent2 = getSingleVariableOfVariableStatement(host2) || host2;
        }
      }
      switch (parent2.kind) {
        case 259 /* VariableDeclaration */:
          const decl = parent2;
          if (decl.name.kind !== 80 /* Identifier */) {
            return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
          }
          if (!isVariableDeclarationInVariableStatement(decl)) {
            return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
          }
          if (!(decl.parent.flags & 2 /* Const */)) {
            return grammarErrorOnNode(parent2.name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
          }
          break;
        case 171 /* PropertyDeclaration */:
          if (!isStatic(parent2) || !hasEffectiveReadonlyModifier(parent2)) {
            return grammarErrorOnNode(parent2.name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
          }
          break;
        case 170 /* PropertySignature */:
          if (!hasSyntacticModifier(parent2, 64 /* Readonly */)) {
            return grammarErrorOnNode(parent2.name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
          }
          break;
        default:
          return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_not_allowed_here);
      }
    } else if (node.operator === 148 /* ReadonlyKeyword */) {
      if (node.type.kind !== 187 /* ArrayType */ && node.type.kind !== 188 /* TupleType */) {
        return grammarErrorOnFirstToken(node, Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, tokenToString(155 /* SymbolKeyword */));
      }
    }
  }
  function checkGrammarForInvalidDynamicName(node, message) {
    if (isNonBindableDynamicName(node)) {
      return grammarErrorOnNode(node, message);
    }
  }
  function checkGrammarMethod(node) {
    if (checkGrammarFunctionLikeDeclaration(node)) {
      return true;
    }
    if (node.kind === 173 /* MethodDeclaration */) {
      if (node.parent.kind === 209 /* ObjectLiteralExpression */) {
        if (node.modifiers && !(node.modifiers.length === 1 && first(node.modifiers).kind === 134 /* AsyncKeyword */)) {
          return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here);
        } else if (checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) {
          return true;
        } else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
          return true;
        } else if (node.body === void 0) {
          return grammarErrorAtPos(node, node.end - 1, ";".length, Diagnostics._0_expected, "{");
        }
      }
      if (checkGrammarForGenerator(node)) {
        return true;
      }
    }
    if (isClassLike(node.parent)) {
      if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(node.name)) {
        return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (node.flags & 16777216 /* Ambient */) {
        return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
      } else if (node.kind === 173 /* MethodDeclaration */ && !node.body) {
        return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
      }
    } else if (node.parent.kind === 263 /* InterfaceDeclaration */) {
      return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
    } else if (node.parent.kind === 186 /* TypeLiteral */) {
      return checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);
    }
  }
  function checkGrammarBreakOrContinueStatement(node) {
    let current = node;
    while (current) {
      if (isFunctionLikeOrClassStaticBlockDeclaration(current)) {
        return grammarErrorOnNode(node, Diagnostics.Jump_target_cannot_cross_function_boundary);
      }
      switch (current.kind) {
        case 255 /* LabeledStatement */:
          if (node.label && current.label.escapedText === node.label.escapedText) {
            const isMisplacedContinueLabel = node.kind === 250 /* ContinueStatement */ && !isIterationStatement(
              current.statement,
              /*lookInLabeledStatements*/
              true
            );
            if (isMisplacedContinueLabel) {
              return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
            }
            return false;
          }
          break;
        case 254 /* SwitchStatement */:
          if (node.kind === 251 /* BreakStatement */ && !node.label) {
            return false;
          }
          break;
        default:
          if (isIterationStatement(
            current,
            /*lookInLabeledStatements*/
            false
          ) && !node.label) {
            return false;
          }
          break;
      }
      current = current.parent;
    }
    if (node.label) {
      const message = node.kind === 251 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
      return grammarErrorOnNode(node, message);
    } else {
      const message = node.kind === 251 /* BreakStatement */ ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
      return grammarErrorOnNode(node, message);
    }
  }
  function checkGrammarBindingElement(node) {
    if (node.dotDotDotToken) {
      const elements = node.parent.elements;
      if (node !== last(elements)) {
        return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      }
      checkGrammarForDisallowedTrailingComma(elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
      if (node.propertyName) {
        return grammarErrorOnNode(node.name, Diagnostics.A_rest_element_cannot_have_a_property_name);
      }
    }
    if (node.dotDotDotToken && node.initializer) {
      return grammarErrorAtPos(node, node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer);
    }
  }
  function isStringOrNumberLiteralExpression(expr) {
    return isStringOrNumericLiteralLike(expr) || expr.kind === 223 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 9 /* NumericLiteral */;
  }
  function isBigIntLiteralExpression(expr) {
    return expr.kind === 10 /* BigIntLiteral */ || expr.kind === 223 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 10 /* BigIntLiteral */;
  }
  function isSimpleLiteralEnumReference(expr) {
    if ((isPropertyAccessExpression(expr) || isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression)) && isEntityNameExpression(expr.expression)) {
      return !!(checkExpressionCached(expr).flags & 1056 /* EnumLike */);
    }
  }
  function checkAmbientInitializer(node) {
    const initializer = node.initializer;
    if (initializer) {
      const isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) || isSimpleLiteralEnumReference(initializer) || initializer.kind === 112 /* TrueKeyword */ || initializer.kind === 97 /* FalseKeyword */ || isBigIntLiteralExpression(initializer));
      const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node);
      if (isConstOrReadonly && !node.type) {
        if (isInvalidInitializer) {
          return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
        }
      } else {
        return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
      }
    }
  }
  function checkGrammarVariableDeclaration(node) {
    if (node.parent.parent.kind !== 248 /* ForInStatement */ && node.parent.parent.kind !== 249 /* ForOfStatement */) {
      if (node.flags & 16777216 /* Ambient */) {
        checkAmbientInitializer(node);
      } else if (!node.initializer) {
        if (isBindingPattern(node.name) && !isBindingPattern(node.parent)) {
          return grammarErrorOnNode(node, Diagnostics.A_destructuring_declaration_must_have_an_initializer);
        }
        if (isVarConst(node)) {
          return grammarErrorOnNode(node, Diagnostics.const_declarations_must_be_initialized);
        }
      }
    }
    if (node.exclamationToken && (node.parent.parent.kind !== 242 /* VariableStatement */ || !node.type || node.initializer || node.flags & 16777216 /* Ambient */)) {
      const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
      return grammarErrorOnNode(node.exclamationToken, message);
    }
    if ((moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */) && moduleKind !== 4 /* System */ && !(node.parent.parent.flags & 16777216 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 1 /* Export */)) {
      checkESModuleMarker(node.name);
    }
    const checkLetConstNames = isLet(node) || isVarConst(node);
    return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
  }
  function checkESModuleMarker(name) {
    if (name.kind === 80 /* Identifier */) {
      if (idText(name) === "__esModule") {
        return grammarErrorOnNodeSkippedOn("noEmit", name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
      }
    } else {
      const elements = name.elements;
      for (const element of elements) {
        if (!isOmittedExpression(element)) {
          return checkESModuleMarker(element.name);
        }
      }
    }
    return false;
  }
  function checkGrammarNameInLetOrConstDeclarations(name) {
    if (name.kind === 80 /* Identifier */) {
      if (name.escapedText === "let") {
        return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
      }
    } else {
      const elements = name.elements;
      for (const element of elements) {
        if (!isOmittedExpression(element)) {
          checkGrammarNameInLetOrConstDeclarations(element.name);
        }
      }
    }
    return false;
  }
  function checkGrammarVariableDeclarationList(declarationList) {
    const declarations = declarationList.declarations;
    if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
      return true;
    }
    if (!declarationList.declarations.length) {
      return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty);
    }
    return false;
  }
  function allowLetAndConstDeclarations(parent2) {
    switch (parent2.kind) {
      case 244 /* IfStatement */:
      case 245 /* DoStatement */:
      case 246 /* WhileStatement */:
      case 253 /* WithStatement */:
      case 247 /* ForStatement */:
      case 248 /* ForInStatement */:
      case 249 /* ForOfStatement */:
        return false;
      case 255 /* LabeledStatement */:
        return allowLetAndConstDeclarations(parent2.parent);
    }
    return true;
  }
  function checkGrammarForDisallowedLetOrConstStatement(node) {
    if (!allowLetAndConstDeclarations(node.parent)) {
      if (isLet(node.declarationList)) {
        return grammarErrorOnNode(node, Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
      } else if (isVarConst(node.declarationList)) {
        return grammarErrorOnNode(node, Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
      }
    }
  }
  function checkGrammarMetaProperty(node) {
    const escapedText = node.name.escapedText;
    switch (node.keywordToken) {
      case 105 /* NewKeyword */:
        if (escapedText !== "target") {
          return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "target");
        }
        break;
      case 102 /* ImportKeyword */:
        if (escapedText !== "meta") {
          return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "meta");
        }
        break;
    }
  }
  function hasParseDiagnostics(sourceFile) {
    return sourceFile.parseDiagnostics.length > 0;
  }
  function grammarErrorOnFirstToken(node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const span = getSpanOfTokenAtPosition(sourceFile, node.pos);
      diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, ...args));
      return true;
    }
    return false;
  }
  function grammarErrorAtPos(nodeForSourceFile, start2, length2, message, ...args) {
    const sourceFile = getSourceFileOfNode(nodeForSourceFile);
    if (!hasParseDiagnostics(sourceFile)) {
      diagnostics.add(createFileDiagnostic(sourceFile, start2, length2, message, ...args));
      return true;
    }
    return false;
  }
  function grammarErrorOnNodeSkippedOn(key, node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      errorSkippedOn(key, node, message, ...args);
      return true;
    }
    return false;
  }
  function grammarErrorOnNode(node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      diagnostics.add(createDiagnosticForNode(node, message, ...args));
      return true;
    }
    return false;
  }
  function checkGrammarConstructorTypeParameters(node) {
    const jsdocTypeParameters = isInJSFile(node) ? getJSDocTypeParameterDeclarations(node) : void 0;
    const range = node.typeParameters || jsdocTypeParameters && firstOrUndefined(jsdocTypeParameters);
    if (range) {
      const pos = range.pos === range.end ? range.pos : skipTrivia(getSourceFileOfNode(node).text, range.pos);
      return grammarErrorAtPos(node, pos, range.end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
    }
  }
  function checkGrammarConstructorTypeAnnotation(node) {
    const type = node.type || getEffectiveReturnTypeNode(node);
    if (type) {
      return grammarErrorOnNode(type, Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
    }
  }
  function checkGrammarProperty(node) {
    if (isComputedPropertyName(node.name) && isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 103 /* InKeyword */) {
      return grammarErrorOnNode(node.parent.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods);
    }
    if (isClassLike(node.parent)) {
      if (isStringLiteral(node.name) && node.name.text === "constructor") {
        return grammarErrorOnNode(node.name, Diagnostics.Classes_may_not_have_a_field_named_constructor);
      }
      if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) {
        return true;
      }
      if (languageVersion < 2 /* ES2015 */ && isPrivateIdentifier(node.name)) {
        return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (languageVersion < 2 /* ES2015 */ && isAutoAccessorPropertyDeclaration(node)) {
        return grammarErrorOnNode(node.name, Diagnostics.Properties_with_the_accessor_modifier_are_only_available_when_targeting_ECMAScript_2015_and_higher);
      }
      if (isAutoAccessorPropertyDeclaration(node) && checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_accessor_property_cannot_be_declared_optional)) {
        return true;
      }
    } else if (node.parent.kind === 263 /* InterfaceDeclaration */) {
      if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
        return true;
      }
      Debug.assertNode(node, isPropertySignature);
      if (node.initializer) {
        return grammarErrorOnNode(node.initializer, Diagnostics.An_interface_property_cannot_have_an_initializer);
      }
    } else if (isTypeLiteralNode(node.parent)) {
      if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
        return true;
      }
      Debug.assertNode(node, isPropertySignature);
      if (node.initializer) {
        return grammarErrorOnNode(node.initializer, Diagnostics.A_type_literal_property_cannot_have_an_initializer);
      }
    }
    if (node.flags & 16777216 /* Ambient */) {
      checkAmbientInitializer(node);
    }
    if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & 16777216 /* Ambient */ || isStatic(node) || hasAbstractModifier(node))) {
      const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
      return grammarErrorOnNode(node.exclamationToken, message);
    }
  }
  function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
    if (node.kind === 263 /* InterfaceDeclaration */ || node.kind === 264 /* TypeAliasDeclaration */ || node.kind === 271 /* ImportDeclaration */ || node.kind === 270 /* ImportEqualsDeclaration */ || node.kind === 277 /* ExportDeclaration */ || node.kind === 276 /* ExportAssignment */ || node.kind === 269 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 1024 /* Default */)) {
      return false;
    }
    return grammarErrorOnFirstToken(node, Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
  }
  function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
    for (const decl of file.statements) {
      if (isDeclaration(decl) || decl.kind === 242 /* VariableStatement */) {
        if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
          return true;
        }
      }
    }
    return false;
  }
  function checkGrammarSourceFile(node) {
    return !!(node.flags & 16777216 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
  }
  function checkGrammarStatementInAmbientContext(node) {
    if (node.flags & 16777216 /* Ambient */) {
      const links = getNodeLinks(node);
      if (!links.hasReportedStatementInAmbientContext && (isFunctionLike(node.parent) || isAccessor(node.parent))) {
        return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
      }
      if (node.parent.kind === 240 /* Block */ || node.parent.kind === 267 /* ModuleBlock */ || node.parent.kind === 311 /* SourceFile */) {
        const links2 = getNodeLinks(node.parent);
        if (!links2.hasReportedStatementInAmbientContext) {
          return links2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
        }
      } else {
      }
    }
    return false;
  }
  function checkGrammarNumericLiteral(node) {
    const isFractional = getTextOfNode(node).indexOf(".") !== -1;
    const isScientific = node.numericLiteralFlags & 16 /* Scientific */;
    if (isFractional || isScientific) {
      return;
    }
    const value = +node.text;
    if (value <= 2 ** 53 - 1) {
      return;
    }
    addErrorOrSuggestion(
      /*isError*/
      false,
      createDiagnosticForNode(node, Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers)
    );
  }
  function checkGrammarBigIntLiteral(node) {
    const literalType = isLiteralTypeNode(node.parent) || isPrefixUnaryExpression(node.parent) && isLiteralTypeNode(node.parent.parent);
    if (!literalType) {
      if (languageVersion < 7 /* ES2020 */) {
        if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
          return true;
        }
      }
    }
    return false;
  }
  function grammarErrorAfterFirstToken(node, message, ...args) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const span = getSpanOfTokenAtPosition(sourceFile, node.pos);
      diagnostics.add(createFileDiagnostic(
        sourceFile,
        textSpanEnd(span),
        /*length*/
        0,
        message,
        ...args
      ));
      return true;
    }
    return false;
  }
  function getAmbientModules() {
    if (!ambientModulesCache) {
      ambientModulesCache = [];
      globals.forEach((global2, sym) => {
        if (ambientModuleSymbolRegex.test(sym)) {
          ambientModulesCache.push(global2);
        }
      });
    }
    return ambientModulesCache;
  }
  function checkGrammarImportClause(node) {
    var _a;
    if (node.isTypeOnly && node.name && node.namedBindings) {
      return grammarErrorOnNode(node, Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
    }
    if (node.isTypeOnly && ((_a = node.namedBindings) == null ? void 0 : _a.kind) === 274 /* NamedImports */) {
      return checkGrammarNamedImportsOrExports(node.namedBindings);
    }
    return false;
  }
  function checkGrammarNamedImportsOrExports(namedBindings) {
    return !!forEach(namedBindings.elements, (specifier) => {
      if (specifier.isTypeOnly) {
        return grammarErrorOnFirstToken(
          specifier,
          specifier.kind === 275 /* ImportSpecifier */ ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement
        );
      }
    });
  }
  function checkGrammarImportCallExpression(node) {
    if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) {
      return grammarErrorOnNode(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
    }
    if (moduleKind === 5 /* ES2015 */) {
      return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node16_or_nodenext);
    }
    if (node.typeArguments) {
      return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
    }
    const nodeArguments = node.arguments;
    if (moduleKind !== 99 /* ESNext */ && moduleKind !== 199 /* NodeNext */ && moduleKind !== 100 /* Node16 */) {
      checkGrammarForDisallowedTrailingComma(nodeArguments);
      if (nodeArguments.length > 1) {
        const assertionArgument = nodeArguments[1];
        return grammarErrorOnNode(assertionArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_or_nodenext);
      }
    }
    if (nodeArguments.length === 0 || nodeArguments.length > 2) {
      return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments);
    }
    const spreadElement = find(nodeArguments, isSpreadElement);
    if (spreadElement) {
      return grammarErrorOnNode(spreadElement, Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element);
    }
    return false;
  }
  function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
    const sourceObjectFlags = getObjectFlags(source);
    if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
      return find(unionTarget.types, (target) => {
        if (target.flags & 524288 /* Object */) {
          const overlapObjFlags = sourceObjectFlags & getObjectFlags(target);
          if (overlapObjFlags & 4 /* Reference */) {
            return source.target === target.target;
          }
          if (overlapObjFlags & 16 /* Anonymous */) {
            return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
          }
        }
        return false;
      });
    }
  }
  function findBestTypeForObjectLiteral(source, unionTarget) {
    if (getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) {
      return find(unionTarget.types, (t) => !isArrayLikeType(t));
    }
  }
  function findBestTypeForInvokable(source, unionTarget) {
    let signatureKind = 0 /* Call */;
    const hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
    if (hasSignatures) {
      return find(unionTarget.types, (t) => getSignaturesOfType(t, signatureKind).length > 0);
    }
  }
  function findMostOverlappyType(source, unionTarget) {
    let bestMatch;
    if (!(source.flags & (402784252 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) {
      let matchingCount = 0;
      for (const target of unionTarget.types) {
        if (!(target.flags & (402784252 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) {
          const overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
          if (overlap.flags & 4194304 /* Index */) {
            return target;
          } else if (isUnitType(overlap) || overlap.flags & 1048576 /* Union */) {
            const len = overlap.flags & 1048576 /* Union */ ? countWhere(overlap.types, isUnitType) : 1;
            if (len >= matchingCount) {
              bestMatch = target;
              matchingCount = len;
            }
          }
        }
      }
    }
    return bestMatch;
  }
  function filterPrimitivesIfContainsNonPrimitive(type) {
    if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
      const result = filterType(type, (t) => !(t.flags & 402784252 /* Primitive */));
      if (!(result.flags & 131072 /* Never */)) {
        return result;
      }
    }
    return type;
  }
  function findMatchingDiscriminantType(source, target, isRelatedTo) {
    if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
      const match = getMatchingUnionConstituentForType(target, source);
      if (match) {
        return match;
      }
      const sourceProperties = getPropertiesOfType(source);
      if (sourceProperties) {
        const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
        if (sourcePropertiesFiltered) {
          const discriminated = discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, (p) => [() => getTypeOfSymbol(p), p.escapedName]), isRelatedTo);
          if (discriminated !== target) {
            return discriminated;
          }
        }
      }
    }
    return void 0;
  }
  function getEffectivePropertyNameForPropertyNameNode(node) {
    const name = getPropertyNameForPropertyNameNode(node);
    return name ? name : isComputedPropertyName(node) && isEntityNameExpression(node.expression) ? tryGetNameFromEntityNameExpression(node.expression) : void 0;
  }
}
function isNotAccessor(declaration) {
  return !isAccessor(declaration);
}
function isNotOverload(declaration) {
  return declaration.kind !== 261 /* FunctionDeclaration */ && declaration.kind !== 173 /* MethodDeclaration */ || !!declaration.body;
}
function isDeclarationNameOrImportPropertyName(name) {
  switch (name.parent.kind) {
    case 275 /* ImportSpecifier */:
    case 280 /* ExportSpecifier */:
      return isIdentifier(name);
    default:
      return isDeclarationName(name);
  }
}
var JsxNames;
((JsxNames2) => {
  JsxNames2.JSX = "JSX";
  JsxNames2.IntrinsicElements = "IntrinsicElements";
  JsxNames2.ElementClass = "ElementClass";
  JsxNames2.ElementAttributesPropertyNameContainer = "ElementAttributesProperty";
  JsxNames2.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
  JsxNames2.Element = "Element";
  JsxNames2.ElementType = "ElementType";
  JsxNames2.IntrinsicAttributes = "IntrinsicAttributes";
  JsxNames2.IntrinsicClassAttributes = "IntrinsicClassAttributes";
  JsxNames2.LibraryManagedAttributes = "LibraryManagedAttributes";
})(JsxNames || (JsxNames = {}));
function getIterationTypesKeyFromIterationTypeKind(typeKind) {
  switch (typeKind) {
    case 0 /* Yield */:
      return "yieldType";
    case 1 /* Return */:
      return "returnType";
    case 2 /* Next */:
      return "nextType";
  }
}
function signatureHasRestParameter(s) {
  return !!(s.flags & 1 /* HasRestParameter */);
}
function signatureHasLiteralTypes(s) {
  return !!(s.flags & 2 /* HasLiteralTypes */);
}
function createBasicNodeBuilderModuleSpecifierResolutionHost(host) {
  return {
    getCommonSourceDirectory: !!host.getCommonSourceDirectory ? () => host.getCommonSourceDirectory() : () => "",
    getCurrentDirectory: () => host.getCurrentDirectory(),
    getSymlinkCache: maybeBind(host, host.getSymlinkCache),
    getPackageJsonInfoCache: () => {
      var _a;
      return (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host);
    },
    useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames),
    redirectTargetsMap: host.redirectTargetsMap,
    getProjectReferenceRedirect: (fileName) => host.getProjectReferenceRedirect(fileName),
    isSourceOfProjectReferenceRedirect: (fileName) => host.isSourceOfProjectReferenceRedirect(fileName),
    fileExists: (fileName) => host.fileExists(fileName),
    getFileIncludeReasons: () => host.getFileIncludeReasons(),
    readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0
  };
}
var SymbolTrackerImpl = class {
  constructor(context, tracker, moduleResolverHost) {
    this.moduleResolverHost = void 0;
    this.inner = void 0;
    this.disableTrackSymbol = false;
    var _a;
    while (tracker instanceof SymbolTrackerImpl) {
      tracker = tracker.inner;
    }
    this.inner = tracker;
    this.moduleResolverHost = moduleResolverHost;
    this.context = context;
    this.canTrackSymbol = !!((_a = this.inner) == null ? void 0 : _a.trackSymbol);
  }
  trackSymbol(symbol, enclosingDeclaration, meaning) {
    var _a;
    if (((_a = this.inner) == null ? void 0 : _a.trackSymbol) && !this.disableTrackSymbol) {
      if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) {
        this.onDiagnosticReported();
        return true;
      }
    }
    return false;
  }
  reportInaccessibleThisError() {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportInaccessibleThisError) {
      this.onDiagnosticReported();
      this.inner.reportInaccessibleThisError();
    }
  }
  reportPrivateInBaseOfClassExpression(propertyName) {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportPrivateInBaseOfClassExpression) {
      this.onDiagnosticReported();
      this.inner.reportPrivateInBaseOfClassExpression(propertyName);
    }
  }
  reportInaccessibleUniqueSymbolError() {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportInaccessibleUniqueSymbolError) {
      this.onDiagnosticReported();
      this.inner.reportInaccessibleUniqueSymbolError();
    }
  }
  reportCyclicStructureError() {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportCyclicStructureError) {
      this.onDiagnosticReported();
      this.inner.reportCyclicStructureError();
    }
  }
  reportLikelyUnsafeImportRequiredError(specifier) {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportLikelyUnsafeImportRequiredError) {
      this.onDiagnosticReported();
      this.inner.reportLikelyUnsafeImportRequiredError(specifier);
    }
  }
  reportTruncationError() {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportTruncationError) {
      this.onDiagnosticReported();
      this.inner.reportTruncationError();
    }
  }
  trackReferencedAmbientModule(decl, symbol) {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.trackReferencedAmbientModule) {
      this.onDiagnosticReported();
      this.inner.trackReferencedAmbientModule(decl, symbol);
    }
  }
  trackExternalModuleSymbolOfImportTypeNode(symbol) {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.trackExternalModuleSymbolOfImportTypeNode) {
      this.onDiagnosticReported();
      this.inner.trackExternalModuleSymbolOfImportTypeNode(symbol);
    }
  }
  reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol) {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportNonlocalAugmentation) {
      this.onDiagnosticReported();
      this.inner.reportNonlocalAugmentation(containingFile, parentSymbol, augmentingSymbol);
    }
  }
  reportNonSerializableProperty(propertyName) {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportNonSerializableProperty) {
      this.onDiagnosticReported();
      this.inner.reportNonSerializableProperty(propertyName);
    }
  }
  reportImportTypeNodeResolutionModeOverride() {
    var _a;
    if ((_a = this.inner) == null ? void 0 : _a.reportImportTypeNodeResolutionModeOverride) {
      this.onDiagnosticReported();
      this.inner.reportImportTypeNodeResolutionModeOverride();
    }
  }
  onDiagnosticReported() {
    this.context.reportedDiagnostic = true;
  }
};

// src/compiler/visitorPublic.ts
function visitNode(node, visitor, test, lift) {
  if (node === void 0) {
    return node;
  }
  const visited = visitor(node);
  let visitedNode;
  if (visited === void 0) {
    return void 0;
  } else if (isArray(visited)) {
    visitedNode = (lift || extractSingleNode)(visited);
  } else {
    visitedNode = visited;
  }
  Debug.assertNode(visitedNode, test);
  return visitedNode;
}
function visitNodes2(nodes, visitor, test, start2, count) {
  if (nodes === void 0) {
    return nodes;
  }
  const length2 = nodes.length;
  if (start2 === void 0 || start2 < 0) {
    start2 = 0;
  }
  if (count === void 0 || count > length2 - start2) {
    count = length2 - start2;
  }
  let hasTrailingComma;
  let pos = -1;
  let end = -1;
  if (start2 > 0 || count < length2) {
    hasTrailingComma = nodes.hasTrailingComma && start2 + count === length2;
  } else {
    pos = nodes.pos;
    end = nodes.end;
    hasTrailingComma = nodes.hasTrailingComma;
  }
  const updated = visitArrayWorker(nodes, visitor, test, start2, count);
  if (updated !== nodes) {
    const updatedArray = factory.createNodeArray(updated, hasTrailingComma);
    setTextRangePosEnd(updatedArray, pos, end);
    return updatedArray;
  }
  return nodes;
}
function visitArray(nodes, visitor, test, start2, count) {
  if (nodes === void 0) {
    return nodes;
  }
  const length2 = nodes.length;
  if (start2 === void 0 || start2 < 0) {
    start2 = 0;
  }
  if (count === void 0 || count > length2 - start2) {
    count = length2 - start2;
  }
  return visitArrayWorker(nodes, visitor, test, start2, count);
}
function visitArrayWorker(nodes, visitor, test, start2, count) {
  let updated;
  const length2 = nodes.length;
  if (start2 > 0 || count < length2) {
    updated = [];
  }
  for (let i = 0; i < count; i++) {
    const node = nodes[i + start2];
    const visited = node !== void 0 ? visitor ? visitor(node) : node : void 0;
    if (updated !== void 0 || visited === void 0 || visited !== node) {
      if (updated === void 0) {
        updated = nodes.slice(0, i);
        Debug.assertEachNode(updated, test);
      }
      if (visited) {
        if (isArray(visited)) {
          for (const visitedNode of visited) {
            Debug.assertNode(visitedNode, test);
            updated.push(visitedNode);
          }
        } else {
          Debug.assertNode(visited, test);
          updated.push(visited);
        }
      }
    }
  }
  if (updated) {
    return updated;
  }
  Debug.assertEachNode(nodes, test);
  return nodes;
}
function visitLexicalEnvironment(statements, visitor, context, start2, ensureUseStrict, nodesVisitor = visitNodes2) {
  context.startLexicalEnvironment();
  statements = nodesVisitor(statements, visitor, isStatement, start2);
  if (ensureUseStrict)
    statements = context.factory.ensureUseStrict(statements);
  return factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
}
function visitParameterList(nodes, visitor, context, nodesVisitor = visitNodes2) {
  let updated;
  context.startLexicalEnvironment();
  if (nodes) {
    context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
    updated = nodesVisitor(nodes, visitor, isParameter);
    if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
      updated = addDefaultValueAssignmentsIfNeeded(updated, context);
    }
    context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
  }
  context.suspendLexicalEnvironment();
  return updated;
}
function addDefaultValueAssignmentsIfNeeded(parameters, context) {
  let result;
  for (let i = 0; i < parameters.length; i++) {
    const parameter = parameters[i];
    const updated = addDefaultValueAssignmentIfNeeded(parameter, context);
    if (result || updated !== parameter) {
      if (!result)
        result = parameters.slice(0, i);
      result[i] = updated;
    }
  }
  if (result) {
    return setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters);
  }
  return parameters;
}
function addDefaultValueAssignmentIfNeeded(parameter, context) {
  return parameter.dotDotDotToken ? parameter : isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : parameter;
}
function addDefaultValueAssignmentForBindingPattern(parameter, context) {
  const { factory: factory2 } = context;
  context.addInitializationStatement(
    factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      factory2.createVariableDeclarationList([
        factory2.createVariableDeclaration(
          parameter.name,
          /*exclamationToken*/
          void 0,
          parameter.type,
          parameter.initializer ? factory2.createConditionalExpression(
            factory2.createStrictEquality(
              factory2.getGeneratedNameForNode(parameter),
              factory2.createVoidZero()
            ),
            /*questionToken*/
            void 0,
            parameter.initializer,
            /*colonToken*/
            void 0,
            factory2.getGeneratedNameForNode(parameter)
          ) : factory2.getGeneratedNameForNode(parameter)
        )
      ])
    )
  );
  return factory2.updateParameterDeclaration(
    parameter,
    parameter.modifiers,
    parameter.dotDotDotToken,
    factory2.getGeneratedNameForNode(parameter),
    parameter.questionToken,
    parameter.type,
    /*initializer*/
    void 0
  );
}
function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
  const factory2 = context.factory;
  context.addInitializationStatement(
    factory2.createIfStatement(
      factory2.createTypeCheck(factory2.cloneNode(name), "undefined"),
      setEmitFlags(
        setTextRange(
          factory2.createBlock([
            factory2.createExpressionStatement(
              setEmitFlags(
                setTextRange(
                  factory2.createAssignment(
                    setEmitFlags(factory2.cloneNode(name), 96 /* NoSourceMap */),
                    setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */)
                  ),
                  parameter
                ),
                3072 /* NoComments */
              )
            )
          ]),
          parameter
        ),
        1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */
      )
    )
  );
  return factory2.updateParameterDeclaration(
    parameter,
    parameter.modifiers,
    parameter.dotDotDotToken,
    parameter.name,
    parameter.questionToken,
    parameter.type,
    /*initializer*/
    void 0
  );
}
function visitFunctionBody(node, visitor, context, nodeVisitor = visitNode) {
  context.resumeLexicalEnvironment();
  const updated = nodeVisitor(node, visitor, isConciseBody);
  const declarations = context.endLexicalEnvironment();
  if (some(declarations)) {
    if (!updated) {
      return context.factory.createBlock(declarations);
    }
    const block = context.factory.converters.convertToFunctionBlock(updated);
    const statements = factory.mergeLexicalEnvironment(block.statements, declarations);
    return context.factory.updateBlock(block, statements);
  }
  return updated;
}
function visitIterationBody(body, visitor, context, nodeVisitor = visitNode) {
  context.startBlockScope();
  const updated = nodeVisitor(body, visitor, isStatement, context.factory.liftToBlock);
  Debug.assert(updated);
  const declarations = context.endBlockScope();
  if (some(declarations)) {
    if (isBlock(updated)) {
      declarations.push(...updated.statements);
      return context.factory.updateBlock(updated, declarations);
    }
    declarations.push(updated);
    return context.factory.createBlock(declarations);
  }
  return updated;
}
function visitCommaListElements(elements, visitor, discardVisitor = visitor) {
  if (discardVisitor === visitor || elements.length <= 1) {
    return visitNodes2(elements, visitor, isExpression);
  }
  let i = 0;
  const length2 = elements.length;
  return visitNodes2(elements, (node) => {
    const discarded = i < length2 - 1;
    i++;
    return discarded ? discardVisitor(node) : visitor(node);
  }, isExpression);
}
function visitEachChild(node, visitor, context, nodesVisitor = visitNodes2, tokenVisitor, nodeVisitor = visitNode) {
  if (node === void 0) {
    return void 0;
  }
  const fn = visitEachChildTable[node.kind];
  return fn === void 0 ? node : fn(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor);
}
var visitEachChildTable = {
  [165 /* QualifiedName */]: function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateQualifiedName(
      node,
      Debug.checkDefined(nodeVisitor(node.left, visitor, isEntityName)),
      Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier))
    );
  },
  [166 /* ComputedPropertyName */]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateComputedPropertyName(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // Signature elements
  [167 /* TypeParameter */]: function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeParameterDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      nodeVisitor(node.constraint, visitor, isTypeNode),
      nodeVisitor(node.default, visitor, isTypeNode)
    );
  },
  [168 /* Parameter */]: function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateParameterDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)),
      tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken,
      nodeVisitor(node.type, visitor, isTypeNode),
      nodeVisitor(node.initializer, visitor, isExpression)
    );
  },
  [169 /* Decorator */]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateDecorator(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // Type elements
  [170 /* PropertySignature */]: function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updatePropertySignature(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken,
      nodeVisitor(node.type, visitor, isTypeNode)
    );
  },
  [171 /* PropertyDeclaration */]: function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updatePropertyDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration
      tokenVisitor ? nodeVisitor(node.questionToken ?? node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : node.questionToken ?? node.exclamationToken,
      nodeVisitor(node.type, visitor, isTypeNode),
      nodeVisitor(node.initializer, visitor, isExpression)
    );
  },
  [172 /* MethodSignature */]: function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateMethodSignature(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken,
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.parameters, visitor, isParameter),
      nodeVisitor(node.type, visitor, isTypeNode)
    );
  },
  [173 /* MethodDeclaration */]: function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateMethodDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken,
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      nodeVisitor(node.type, visitor, isTypeNode),
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [175 /* Constructor */]: function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateConstructorDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [176 /* GetAccessor */]: function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateGetAccessorDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      nodeVisitor(node.type, visitor, isTypeNode),
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [177 /* SetAccessor */]: function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSetAccessorDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [174 /* ClassStaticBlockDeclaration */]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    context.startLexicalEnvironment();
    context.suspendLexicalEnvironment();
    return context.factory.updateClassStaticBlockDeclaration(
      node,
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [178 /* CallSignature */]: function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateCallSignature(
      node,
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.parameters, visitor, isParameter),
      nodeVisitor(node.type, visitor, isTypeNode)
    );
  },
  [179 /* ConstructSignature */]: function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateConstructSignature(
      node,
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.parameters, visitor, isParameter),
      nodeVisitor(node.type, visitor, isTypeNode)
    );
  },
  [180 /* IndexSignature */]: function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateIndexSignature(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      nodesVisitor(node.parameters, visitor, isParameter),
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  // Types
  [181 /* TypePredicate */]: function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypePredicateNode(
      node,
      nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword),
      Debug.checkDefined(nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode)),
      nodeVisitor(node.type, visitor, isTypeNode)
    );
  },
  [182 /* TypeReference */]: function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeReferenceNode(
      node,
      Debug.checkDefined(nodeVisitor(node.typeName, visitor, isEntityName)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode)
    );
  },
  [183 /* FunctionType */]: function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateFunctionTypeNode(
      node,
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.parameters, visitor, isParameter),
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [184 /* ConstructorType */]: function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateConstructorTypeNode(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.parameters, visitor, isParameter),
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [185 /* TypeQuery */]: function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeQueryNode(
      node,
      Debug.checkDefined(nodeVisitor(node.exprName, visitor, isEntityName)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode)
    );
  },
  [186 /* TypeLiteral */]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeLiteralNode(
      node,
      nodesVisitor(node.members, visitor, isTypeElement)
    );
  },
  [187 /* ArrayType */]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateArrayTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode))
    );
  },
  [188 /* TupleType */]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateTupleTypeNode(
      node,
      nodesVisitor(node.elements, visitor, isTypeNode)
    );
  },
  [189 /* OptionalType */]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateOptionalTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [190 /* RestType */]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateRestTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [191 /* UnionType */]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateUnionTypeNode(
      node,
      nodesVisitor(node.types, visitor, isTypeNode)
    );
  },
  [192 /* IntersectionType */]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateIntersectionTypeNode(
      node,
      nodesVisitor(node.types, visitor, isTypeNode)
    );
  },
  [193 /* ConditionalType */]: function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateConditionalTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.checkType, visitor, isTypeNode)),
      Debug.checkDefined(nodeVisitor(node.extendsType, visitor, isTypeNode)),
      Debug.checkDefined(nodeVisitor(node.trueType, visitor, isTypeNode)),
      Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode))
    );
  },
  [194 /* InferType */]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateInferTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration))
    );
  },
  [204 /* ImportType */]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)),
      nodeVisitor(node.assertions, visitor, isImportTypeAssertionContainer),
      nodeVisitor(node.qualifier, visitor, isEntityName),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      node.isTypeOf
    );
  },
  [301 /* ImportTypeAssertionContainer */]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportTypeAssertionContainer(
      node,
      Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)),
      node.multiLine
    );
  },
  [201 /* NamedTupleMember */]: function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateNamedTupleMember(
      node,
      tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [195 /* ParenthesizedType */]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateParenthesizedType(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [197 /* TypeOperator */]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeOperatorNode(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [198 /* IndexedAccessType */]: function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateIndexedAccessTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.objectType, visitor, isTypeNode)),
      Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode))
    );
  },
  [199 /* MappedType */]: function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateMappedTypeNode(
      node,
      tokenVisitor ? nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken) : node.readonlyToken,
      Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)),
      nodeVisitor(node.nameType, visitor, isTypeNode),
      tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken) : node.questionToken,
      nodeVisitor(node.type, visitor, isTypeNode),
      nodesVisitor(node.members, visitor, isTypeElement)
    );
  },
  [200 /* LiteralType */]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateLiteralTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral))
    );
  },
  [202 /* TemplateLiteralType */]: function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTemplateLiteralType(
      node,
      Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)),
      nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan)
    );
  },
  [203 /* TemplateLiteralTypeSpan */]: function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTemplateLiteralTypeSpan(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)),
      Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))
    );
  },
  // Binding patterns
  [205 /* ObjectBindingPattern */]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateObjectBindingPattern(
      node,
      nodesVisitor(node.elements, visitor, isBindingElement)
    );
  },
  [206 /* ArrayBindingPattern */]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateArrayBindingPattern(
      node,
      nodesVisitor(node.elements, visitor, isArrayBindingElement)
    );
  },
  [207 /* BindingElement */]: function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateBindingElement(
      node,
      tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken,
      nodeVisitor(node.propertyName, visitor, isPropertyName),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)),
      nodeVisitor(node.initializer, visitor, isExpression)
    );
  },
  // Expression
  [208 /* ArrayLiteralExpression */]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateArrayLiteralExpression(
      node,
      nodesVisitor(node.elements, visitor, isExpression)
    );
  },
  [209 /* ObjectLiteralExpression */]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateObjectLiteralExpression(
      node,
      nodesVisitor(node.properties, visitor, isObjectLiteralElementLike)
    );
  },
  [210 /* PropertyAccessExpression */]: function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return isPropertyAccessChain(node) ? context.factory.updatePropertyAccessChain(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))
    ) : context.factory.updatePropertyAccessExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))
    );
  },
  [211 /* ElementAccessExpression */]: function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return isElementAccessChain(node) ? context.factory.updateElementAccessChain(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken,
      Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))
    ) : context.factory.updateElementAccessExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))
    );
  },
  [212 /* CallExpression */]: function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return isCallChain(node) ? context.factory.updateCallChain(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken,
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      nodesVisitor(node.arguments, visitor, isExpression)
    ) : context.factory.updateCallExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      nodesVisitor(node.arguments, visitor, isExpression)
    );
  },
  [213 /* NewExpression */]: function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNewExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      nodesVisitor(node.arguments, visitor, isExpression)
    );
  },
  [214 /* TaggedTemplateExpression */]: function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTaggedTemplateExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.tag, visitor, isExpression)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral))
    );
  },
  [215 /* TypeAssertionExpression */]: function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeAssertion(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)),
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [216 /* ParenthesizedExpression */]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateParenthesizedExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [217 /* FunctionExpression */]: function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateFunctionExpression(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
      nodeVisitor(node.name, visitor, isIdentifier),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      nodeVisitor(node.type, visitor, isTypeNode),
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [218 /* ArrowFunction */]: function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateArrowFunction(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      nodeVisitor(node.type, visitor, isTypeNode),
      tokenVisitor ? Debug.checkDefined(nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken)) : node.equalsGreaterThanToken,
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [219 /* DeleteExpression */]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateDeleteExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [220 /* TypeOfExpression */]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeOfExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [221 /* VoidExpression */]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateVoidExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [222 /* AwaitExpression */]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateAwaitExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [223 /* PrefixUnaryExpression */]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePrefixUnaryExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))
    );
  },
  [224 /* PostfixUnaryExpression */]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePostfixUnaryExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))
    );
  },
  [225 /* BinaryExpression */]: function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateBinaryExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.left, visitor, isExpression)),
      tokenVisitor ? Debug.checkDefined(nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken)) : node.operatorToken,
      Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression))
    );
  },
  [226 /* ConditionalExpression */]: function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateConditionalExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.condition, visitor, isExpression)),
      tokenVisitor ? Debug.checkDefined(nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken)) : node.questionToken,
      Debug.checkDefined(nodeVisitor(node.whenTrue, visitor, isExpression)),
      tokenVisitor ? Debug.checkDefined(nodeVisitor(node.colonToken, tokenVisitor, isColonToken)) : node.colonToken,
      Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression))
    );
  },
  [227 /* TemplateExpression */]: function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTemplateExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)),
      nodesVisitor(node.templateSpans, visitor, isTemplateSpan)
    );
  },
  [228 /* YieldExpression */]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateYieldExpression(
      node,
      tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
      nodeVisitor(node.expression, visitor, isExpression)
    );
  },
  [229 /* SpreadElement */]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSpreadElement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [230 /* ClassExpression */]: function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateClassExpression(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      nodeVisitor(node.name, visitor, isIdentifier),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.heritageClauses, visitor, isHeritageClause),
      nodesVisitor(node.members, visitor, isClassElement)
    );
  },
  [232 /* ExpressionWithTypeArguments */]: function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExpressionWithTypeArguments(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode)
    );
  },
  [233 /* AsExpression */]: function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateAsExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [237 /* SatisfiesExpression */]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSatisfiesExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [234 /* NonNullExpression */]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return isOptionalChain(node) ? context.factory.updateNonNullChain(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    ) : context.factory.updateNonNullExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [235 /* MetaProperty */]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateMetaProperty(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  // Misc
  [238 /* TemplateSpan */]: function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTemplateSpan(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))
    );
  },
  // Element
  [240 /* Block */]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateBlock(
      node,
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [242 /* VariableStatement */]: function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateVariableStatement(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList))
    );
  },
  [243 /* ExpressionStatement */]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExpressionStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [244 /* IfStatement */]: function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateIfStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.thenStatement, visitor, isStatement, context.factory.liftToBlock)),
      nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock)
    );
  },
  [245 /* DoStatement */]: function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateDoStatement(
      node,
      visitIterationBody(node.statement, visitor, context, nodeVisitor),
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [246 /* WhileStatement */]: function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateWhileStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      visitIterationBody(node.statement, visitor, context, nodeVisitor)
    );
  },
  [247 /* ForStatement */]: function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateForStatement(
      node,
      nodeVisitor(node.initializer, visitor, isForInitializer),
      nodeVisitor(node.condition, visitor, isExpression),
      nodeVisitor(node.incrementor, visitor, isExpression),
      visitIterationBody(node.statement, visitor, context, nodeVisitor)
    );
  },
  [248 /* ForInStatement */]: function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateForInStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)),
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      visitIterationBody(node.statement, visitor, context, nodeVisitor)
    );
  },
  [249 /* ForOfStatement */]: function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateForOfStatement(
      node,
      tokenVisitor ? nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword) : node.awaitModifier,
      Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)),
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      visitIterationBody(node.statement, visitor, context, nodeVisitor)
    );
  },
  [250 /* ContinueStatement */]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateContinueStatement(
      node,
      nodeVisitor(node.label, visitor, isIdentifier)
    );
  },
  [251 /* BreakStatement */]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateBreakStatement(
      node,
      nodeVisitor(node.label, visitor, isIdentifier)
    );
  },
  [252 /* ReturnStatement */]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateReturnStatement(
      node,
      nodeVisitor(node.expression, visitor, isExpression)
    );
  },
  [253 /* WithStatement */]: function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateWithStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))
    );
  },
  [254 /* SwitchStatement */]: function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSwitchStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock))
    );
  },
  [255 /* LabeledStatement */]: function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateLabeledStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.label, visitor, isIdentifier)),
      Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))
    );
  },
  [256 /* ThrowStatement */]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateThrowStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [257 /* TryStatement */]: function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTryStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.tryBlock, visitor, isBlock)),
      nodeVisitor(node.catchClause, visitor, isCatchClause),
      nodeVisitor(node.finallyBlock, visitor, isBlock)
    );
  },
  [259 /* VariableDeclaration */]: function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateVariableDeclaration(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)),
      tokenVisitor ? nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken) : node.exclamationToken,
      nodeVisitor(node.type, visitor, isTypeNode),
      nodeVisitor(node.initializer, visitor, isExpression)
    );
  },
  [260 /* VariableDeclarationList */]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateVariableDeclarationList(
      node,
      nodesVisitor(node.declarations, visitor, isVariableDeclaration)
    );
  },
  [261 /* FunctionDeclaration */]: function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) {
    return context.factory.updateFunctionDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifier),
      tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken,
      nodeVisitor(node.name, visitor, isIdentifier),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      visitParameterList(node.parameters, visitor, context, nodesVisitor),
      nodeVisitor(node.type, visitor, isTypeNode),
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [262 /* ClassDeclaration */]: function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateClassDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      nodeVisitor(node.name, visitor, isIdentifier),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.heritageClauses, visitor, isHeritageClause),
      nodesVisitor(node.members, visitor, isClassElement)
    );
  },
  [263 /* InterfaceDeclaration */]: function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateInterfaceDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      nodesVisitor(node.heritageClauses, visitor, isHeritageClause),
      nodesVisitor(node.members, visitor, isTypeElement)
    );
  },
  [264 /* TypeAliasDeclaration */]: function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeAliasDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration),
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [265 /* EnumDeclaration */]: function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateEnumDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      nodesVisitor(node.members, visitor, isEnumMember)
    );
  },
  [266 /* ModuleDeclaration */]: function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateModuleDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleName)),
      nodeVisitor(node.body, visitor, isModuleBody)
    );
  },
  [267 /* ModuleBlock */]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateModuleBlock(
      node,
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [268 /* CaseBlock */]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateCaseBlock(
      node,
      nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause)
    );
  },
  [269 /* NamespaceExportDeclaration */]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamespaceExportDeclaration(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [270 /* ImportEqualsDeclaration */]: function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportEqualsDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      node.isTypeOnly,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference))
    );
  },
  [271 /* ImportDeclaration */]: function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      nodeVisitor(node.importClause, visitor, isImportClause),
      Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)),
      nodeVisitor(node.assertClause, visitor, isAssertClause)
    );
  },
  [299 /* AssertClause */]: function visitEachChildOfAssertClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateAssertClause(
      node,
      nodesVisitor(node.elements, visitor, isAssertEntry),
      node.multiLine
    );
  },
  [300 /* AssertEntry */]: function visitEachChildOfAssertEntry(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateAssertEntry(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isAssertionKey)),
      Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression))
    );
  },
  [272 /* ImportClause */]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportClause(
      node,
      node.isTypeOnly,
      nodeVisitor(node.name, visitor, isIdentifier),
      nodeVisitor(node.namedBindings, visitor, isNamedImportBindings)
    );
  },
  [273 /* NamespaceImport */]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamespaceImport(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [279 /* NamespaceExport */]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamespaceExport(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [274 /* NamedImports */]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamedImports(
      node,
      nodesVisitor(node.elements, visitor, isImportSpecifier)
    );
  },
  [275 /* ImportSpecifier */]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportSpecifier(
      node,
      node.isTypeOnly,
      nodeVisitor(node.propertyName, visitor, isIdentifier),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [276 /* ExportAssignment */]: function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExportAssignment(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [277 /* ExportDeclaration */]: function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExportDeclaration(
      node,
      nodesVisitor(node.modifiers, visitor, isModifierLike),
      node.isTypeOnly,
      nodeVisitor(node.exportClause, visitor, isNamedExportBindings),
      nodeVisitor(node.moduleSpecifier, visitor, isExpression),
      nodeVisitor(node.assertClause, visitor, isAssertClause)
    );
  },
  [278 /* NamedExports */]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamedExports(
      node,
      nodesVisitor(node.elements, visitor, isExportSpecifier)
    );
  },
  [280 /* ExportSpecifier */]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExportSpecifier(
      node,
      node.isTypeOnly,
      nodeVisitor(node.propertyName, visitor, isIdentifier),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  // Module references
  [282 /* ExternalModuleReference */]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExternalModuleReference(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // JSX
  [283 /* JsxElement */]: function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxElement(
      node,
      Debug.checkDefined(nodeVisitor(node.openingElement, visitor, isJsxOpeningElement)),
      nodesVisitor(node.children, visitor, isJsxChild),
      Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement))
    );
  },
  [284 /* JsxSelfClosingElement */]: function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxSelfClosingElement(
      node,
      Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))
    );
  },
  [285 /* JsxOpeningElement */]: function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxOpeningElement(
      node,
      Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))
    );
  },
  [286 /* JsxClosingElement */]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxClosingElement(
      node,
      Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression))
    );
  },
  [294 /* JsxNamespacedName */]: function forEachChildInJsxNamespacedName2(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxNamespacedName(
      node,
      Debug.checkDefined(nodeVisitor(node.namespace, visitor, isIdentifier)),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [287 /* JsxFragment */]: function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxFragment(
      node,
      Debug.checkDefined(nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment)),
      nodesVisitor(node.children, visitor, isJsxChild),
      Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment))
    );
  },
  [290 /* JsxAttribute */]: function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxAttribute(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isJsxAttributeName)),
      nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression)
    );
  },
  [291 /* JsxAttributes */]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxAttributes(
      node,
      nodesVisitor(node.properties, visitor, isJsxAttributeLike)
    );
  },
  [292 /* JsxSpreadAttribute */]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxSpreadAttribute(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [293 /* JsxExpression */]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxExpression(
      node,
      nodeVisitor(node.expression, visitor, isExpression)
    );
  },
  // Clauses
  [295 /* CaseClause */]: function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateCaseClause(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)),
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [296 /* DefaultClause */]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateDefaultClause(
      node,
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [297 /* HeritageClause */]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateHeritageClause(
      node,
      nodesVisitor(node.types, visitor, isExpressionWithTypeArguments)
    );
  },
  [298 /* CatchClause */]: function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateCatchClause(
      node,
      nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration),
      Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock))
    );
  },
  // Property assignments
  [302 /* PropertyAssignment */]: function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePropertyAssignment(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression))
    );
  },
  [303 /* ShorthandPropertyAssignment */]: function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateShorthandPropertyAssignment(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)),
      nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression)
    );
  },
  [304 /* SpreadAssignment */]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSpreadAssignment(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // Enum
  [305 /* EnumMember */]: function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateEnumMember(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)),
      nodeVisitor(node.initializer, visitor, isExpression)
    );
  },
  // Top-level nodes
  [311 /* SourceFile */]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateSourceFile(
      node,
      visitLexicalEnvironment(node.statements, visitor, context)
    );
  },
  // Transformation nodes
  [359 /* PartiallyEmittedExpression */]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePartiallyEmittedExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [360 /* CommaListExpression */]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateCommaListExpression(
      node,
      nodesVisitor(node.elements, visitor, isExpression)
    );
  }
};
function extractSingleNode(nodes) {
  Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
  return singleOrUndefined(nodes);
}

// src/compiler/sourcemap.ts
function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
  var { enter, exit } = generatorOptions.extendedDiagnostics ? createTimer("Source Map", "beforeSourcemap", "afterSourcemap") : nullTimer;
  var rawSources = [];
  var sources = [];
  var sourceToSourceIndexMap = /* @__PURE__ */ new Map();
  var sourcesContent;
  var names = [];
  var nameToNameIndexMap;
  var mappingCharCodes = [];
  var mappings = "";
  var lastGeneratedLine = 0;
  var lastGeneratedCharacter = 0;
  var lastSourceIndex = 0;
  var lastSourceLine = 0;
  var lastSourceCharacter = 0;
  var lastNameIndex = 0;
  var hasLast = false;
  var pendingGeneratedLine = 0;
  var pendingGeneratedCharacter = 0;
  var pendingSourceIndex = 0;
  var pendingSourceLine = 0;
  var pendingSourceCharacter = 0;
  var pendingNameIndex = 0;
  var hasPending = false;
  var hasPendingSource = false;
  var hasPendingName = false;
  return {
    getSources: () => rawSources,
    addSource,
    setSourceContent,
    addName,
    addMapping,
    appendSourceMap,
    toJSON,
    toString: () => JSON.stringify(toJSON())
  };
  function addSource(fileName) {
    enter();
    const source = getRelativePathToDirectoryOrUrl(
      sourcesDirectoryPath,
      fileName,
      host.getCurrentDirectory(),
      host.getCanonicalFileName,
      /*isAbsolutePathAnUrl*/
      true
    );
    let sourceIndex = sourceToSourceIndexMap.get(source);
    if (sourceIndex === void 0) {
      sourceIndex = sources.length;
      sources.push(source);
      rawSources.push(fileName);
      sourceToSourceIndexMap.set(source, sourceIndex);
    }
    exit();
    return sourceIndex;
  }
  function setSourceContent(sourceIndex, content) {
    enter();
    if (content !== null) {
      if (!sourcesContent)
        sourcesContent = [];
      while (sourcesContent.length < sourceIndex) {
        sourcesContent.push(null);
      }
      sourcesContent[sourceIndex] = content;
    }
    exit();
  }
  function addName(name) {
    enter();
    if (!nameToNameIndexMap)
      nameToNameIndexMap = /* @__PURE__ */ new Map();
    let nameIndex = nameToNameIndexMap.get(name);
    if (nameIndex === void 0) {
      nameIndex = names.length;
      names.push(name);
      nameToNameIndexMap.set(name, nameIndex);
    }
    exit();
    return nameIndex;
  }
  function isNewGeneratedPosition(generatedLine, generatedCharacter) {
    return !hasPending || pendingGeneratedLine !== generatedLine || pendingGeneratedCharacter !== generatedCharacter;
  }
  function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
    return sourceIndex !== void 0 && sourceLine !== void 0 && sourceCharacter !== void 0 && pendingSourceIndex === sourceIndex && (pendingSourceLine > sourceLine || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
  }
  function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
    Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
    Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
    Debug.assert(sourceIndex === void 0 || sourceIndex >= 0, "sourceIndex cannot be negative");
    Debug.assert(sourceLine === void 0 || sourceLine >= 0, "sourceLine cannot be negative");
    Debug.assert(sourceCharacter === void 0 || sourceCharacter >= 0, "sourceCharacter cannot be negative");
    enter();
    if (isNewGeneratedPosition(generatedLine, generatedCharacter) || isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
      commitPendingMapping();
      pendingGeneratedLine = generatedLine;
      pendingGeneratedCharacter = generatedCharacter;
      hasPendingSource = false;
      hasPendingName = false;
      hasPending = true;
    }
    if (sourceIndex !== void 0 && sourceLine !== void 0 && sourceCharacter !== void 0) {
      pendingSourceIndex = sourceIndex;
      pendingSourceLine = sourceLine;
      pendingSourceCharacter = sourceCharacter;
      hasPendingSource = true;
      if (nameIndex !== void 0) {
        pendingNameIndex = nameIndex;
        hasPendingName = true;
      }
    }
    exit();
  }
  function appendSourceMap(generatedLine, generatedCharacter, map2, sourceMapPath, start2, end) {
    Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
    Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
    enter();
    const sourceIndexToNewSourceIndexMap = [];
    let nameIndexToNewNameIndexMap;
    const mappingIterator = decodeMappings(map2.mappings);
    for (const raw of mappingIterator) {
      if (end && (raw.generatedLine > end.line || raw.generatedLine === end.line && raw.generatedCharacter > end.character)) {
        break;
      }
      if (start2 && (raw.generatedLine < start2.line || start2.line === raw.generatedLine && raw.generatedCharacter < start2.character)) {
        continue;
      }
      let newSourceIndex;
      let newSourceLine;
      let newSourceCharacter;
      let newNameIndex;
      if (raw.sourceIndex !== void 0) {
        newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
        if (newSourceIndex === void 0) {
          const rawPath = map2.sources[raw.sourceIndex];
          const relativePath = map2.sourceRoot ? combinePaths(map2.sourceRoot, rawPath) : rawPath;
          const combinedPath = combinePaths(getDirectoryPath(sourceMapPath), relativePath);
          sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
          if (map2.sourcesContent && typeof map2.sourcesContent[raw.sourceIndex] === "string") {
            setSourceContent(newSourceIndex, map2.sourcesContent[raw.sourceIndex]);
          }
        }
        newSourceLine = raw.sourceLine;
        newSourceCharacter = raw.sourceCharacter;
        if (map2.names && raw.nameIndex !== void 0) {
          if (!nameIndexToNewNameIndexMap)
            nameIndexToNewNameIndexMap = [];
          newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
          if (newNameIndex === void 0) {
            nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map2.names[raw.nameIndex]);
          }
        }
      }
      const rawGeneratedLine = raw.generatedLine - (start2 ? start2.line : 0);
      const newGeneratedLine = rawGeneratedLine + generatedLine;
      const rawGeneratedCharacter = start2 && start2.line === raw.generatedLine ? raw.generatedCharacter - start2.character : raw.generatedCharacter;
      const newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
      addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
    }
    exit();
  }
  function shouldCommitMapping() {
    return !hasLast || lastGeneratedLine !== pendingGeneratedLine || lastGeneratedCharacter !== pendingGeneratedCharacter || lastSourceIndex !== pendingSourceIndex || lastSourceLine !== pendingSourceLine || lastSourceCharacter !== pendingSourceCharacter || lastNameIndex !== pendingNameIndex;
  }
  function appendMappingCharCode(charCode) {
    mappingCharCodes.push(charCode);
    if (mappingCharCodes.length >= 1024) {
      flushMappingBuffer();
    }
  }
  function commitPendingMapping() {
    if (!hasPending || !shouldCommitMapping()) {
      return;
    }
    enter();
    if (lastGeneratedLine < pendingGeneratedLine) {
      do {
        appendMappingCharCode(59 /* semicolon */);
        lastGeneratedLine++;
      } while (lastGeneratedLine < pendingGeneratedLine);
      lastGeneratedCharacter = 0;
    } else {
      Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
      if (hasLast) {
        appendMappingCharCode(44 /* comma */);
      }
    }
    appendBase64VLQ(pendingGeneratedCharacter - lastGeneratedCharacter);
    lastGeneratedCharacter = pendingGeneratedCharacter;
    if (hasPendingSource) {
      appendBase64VLQ(pendingSourceIndex - lastSourceIndex);
      lastSourceIndex = pendingSourceIndex;
      appendBase64VLQ(pendingSourceLine - lastSourceLine);
      lastSourceLine = pendingSourceLine;
      appendBase64VLQ(pendingSourceCharacter - lastSourceCharacter);
      lastSourceCharacter = pendingSourceCharacter;
      if (hasPendingName) {
        appendBase64VLQ(pendingNameIndex - lastNameIndex);
        lastNameIndex = pendingNameIndex;
      }
    }
    hasLast = true;
    exit();
  }
  function flushMappingBuffer() {
    if (mappingCharCodes.length > 0) {
      mappings += String.fromCharCode.apply(void 0, mappingCharCodes);
      mappingCharCodes.length = 0;
    }
  }
  function toJSON() {
    commitPendingMapping();
    flushMappingBuffer();
    return {
      version: 3,
      file,
      sourceRoot,
      sources,
      names,
      mappings,
      sourcesContent
    };
  }
  function appendBase64VLQ(inValue) {
    if (inValue < 0) {
      inValue = (-inValue << 1) + 1;
    } else {
      inValue = inValue << 1;
    }
    do {
      let currentDigit = inValue & 31;
      inValue = inValue >> 5;
      if (inValue > 0) {
        currentDigit = currentDigit | 32;
      }
      appendMappingCharCode(base64FormatEncode(currentDigit));
    } while (inValue > 0);
  }
}
var sourceMapCommentRegExpDontCareLineStart = /\/\/[@#] source[M]appingURL=(.+)\r?\n?$/;
var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/;
var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
function getLineInfo(text, lineStarts) {
  return {
    getLineCount: () => lineStarts.length,
    getLineText: (line) => text.substring(lineStarts[line], lineStarts[line + 1])
  };
}
function tryGetSourceMappingURL(lineInfo) {
  for (let index = lineInfo.getLineCount() - 1; index >= 0; index--) {
    const line = lineInfo.getLineText(index);
    const comment = sourceMapCommentRegExp.exec(line);
    if (comment) {
      return trimStringEnd(comment[1]);
    } else if (!line.match(whitespaceOrMapCommentRegExp)) {
      break;
    }
  }
}
function isStringOrNull(x) {
  return typeof x === "string" || x === null;
}
function isRawSourceMap(x) {
  return x !== null && typeof x === "object" && x.version === 3 && typeof x.file === "string" && typeof x.mappings === "string" && isArray(x.sources) && every(x.sources, isString) && (x.sourceRoot === void 0 || x.sourceRoot === null || typeof x.sourceRoot === "string") && (x.sourcesContent === void 0 || x.sourcesContent === null || isArray(x.sourcesContent) && every(x.sourcesContent, isStringOrNull)) && (x.names === void 0 || x.names === null || isArray(x.names) && every(x.names, isString));
}
function tryParseRawSourceMap(text) {
  try {
    const parsed = JSON.parse(text);
    if (isRawSourceMap(parsed)) {
      return parsed;
    }
  } catch {
  }
  return void 0;
}
function decodeMappings(mappings) {
  let done = false;
  let pos = 0;
  let generatedLine = 0;
  let generatedCharacter = 0;
  let sourceIndex = 0;
  let sourceLine = 0;
  let sourceCharacter = 0;
  let nameIndex = 0;
  let error;
  return {
    get pos() {
      return pos;
    },
    get error() {
      return error;
    },
    get state() {
      return captureMapping(
        /*hasSource*/
        true,
        /*hasName*/
        true
      );
    },
    next() {
      while (!done && pos < mappings.length) {
        const ch = mappings.charCodeAt(pos);
        if (ch === 59 /* semicolon */) {
          generatedLine++;
          generatedCharacter = 0;
          pos++;
          continue;
        }
        if (ch === 44 /* comma */) {
          pos++;
          continue;
        }
        let hasSource = false;
        let hasName = false;
        generatedCharacter += base64VLQFormatDecode();
        if (hasReportedError())
          return stopIterating();
        if (generatedCharacter < 0)
          return setErrorAndStopIterating("Invalid generatedCharacter found");
        if (!isSourceMappingSegmentEnd()) {
          hasSource = true;
          sourceIndex += base64VLQFormatDecode();
          if (hasReportedError())
            return stopIterating();
          if (sourceIndex < 0)
            return setErrorAndStopIterating("Invalid sourceIndex found");
          if (isSourceMappingSegmentEnd())
            return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
          sourceLine += base64VLQFormatDecode();
          if (hasReportedError())
            return stopIterating();
          if (sourceLine < 0)
            return setErrorAndStopIterating("Invalid sourceLine found");
          if (isSourceMappingSegmentEnd())
            return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
          sourceCharacter += base64VLQFormatDecode();
          if (hasReportedError())
            return stopIterating();
          if (sourceCharacter < 0)
            return setErrorAndStopIterating("Invalid sourceCharacter found");
          if (!isSourceMappingSegmentEnd()) {
            hasName = true;
            nameIndex += base64VLQFormatDecode();
            if (hasReportedError())
              return stopIterating();
            if (nameIndex < 0)
              return setErrorAndStopIterating("Invalid nameIndex found");
            if (!isSourceMappingSegmentEnd())
              return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
          }
        }
        return { value: captureMapping(hasSource, hasName), done };
      }
      return stopIterating();
    },
    [Symbol.iterator]() {
      return this;
    }
  };
  function captureMapping(hasSource, hasName) {
    return {
      generatedLine,
      generatedCharacter,
      sourceIndex: hasSource ? sourceIndex : void 0,
      sourceLine: hasSource ? sourceLine : void 0,
      sourceCharacter: hasSource ? sourceCharacter : void 0,
      nameIndex: hasName ? nameIndex : void 0
    };
  }
  function stopIterating() {
    done = true;
    return { value: void 0, done: true };
  }
  function setError(message) {
    if (error === void 0) {
      error = message;
    }
  }
  function setErrorAndStopIterating(message) {
    setError(message);
    return stopIterating();
  }
  function hasReportedError() {
    return error !== void 0;
  }
  function isSourceMappingSegmentEnd() {
    return pos === mappings.length || mappings.charCodeAt(pos) === 44 /* comma */ || mappings.charCodeAt(pos) === 59 /* semicolon */;
  }
  function base64VLQFormatDecode() {
    let moreDigits = true;
    let shiftCount = 0;
    let value = 0;
    for (; moreDigits; pos++) {
      if (pos >= mappings.length)
        return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
      const currentByte = base64FormatDecode(mappings.charCodeAt(pos));
      if (currentByte === -1)
        return setError("Invalid character in VLQ"), -1;
      moreDigits = (currentByte & 32) !== 0;
      value = value | (currentByte & 31) << shiftCount;
      shiftCount += 5;
    }
    if ((value & 1) === 0) {
      value = value >> 1;
    } else {
      value = value >> 1;
      value = -value;
    }
    return value;
  }
}
function sameMapping(left, right) {
  return left === right || left.generatedLine === right.generatedLine && left.generatedCharacter === right.generatedCharacter && left.sourceIndex === right.sourceIndex && left.sourceLine === right.sourceLine && left.sourceCharacter === right.sourceCharacter && left.nameIndex === right.nameIndex;
}
function isSourceMapping(mapping) {
  return mapping.sourceIndex !== void 0 && mapping.sourceLine !== void 0 && mapping.sourceCharacter !== void 0;
}
function base64FormatEncode(value) {
  return value >= 0 && value < 26 ? 65 /* A */ + value : value >= 26 && value < 52 ? 97 /* a */ + value - 26 : value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : value === 62 ? 43 /* plus */ : value === 63 ? 47 /* slash */ : Debug.fail(`${value}: not a base64 value`);
}
function base64FormatDecode(ch) {
  return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 : ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 : ch === 43 /* plus */ ? 62 : ch === 47 /* slash */ ? 63 : -1;
}
function isSourceMappedPosition(value) {
  return value.sourceIndex !== void 0 && value.sourcePosition !== void 0;
}
function sameMappedPosition(left, right) {
  return left.generatedPosition === right.generatedPosition && left.sourceIndex === right.sourceIndex && left.sourcePosition === right.sourcePosition;
}
function compareSourcePositions(left, right) {
  Debug.assert(left.sourceIndex === right.sourceIndex);
  return compareValues(left.sourcePosition, right.sourcePosition);
}
function compareGeneratedPositions(left, right) {
  return compareValues(left.generatedPosition, right.generatedPosition);
}
function getSourcePositionOfMapping(value) {
  return value.sourcePosition;
}
function getGeneratedPositionOfMapping(value) {
  return value.generatedPosition;
}
function createDocumentPositionMapper(host, map2, mapPath) {
  const mapDirectory = getDirectoryPath(mapPath);
  const sourceRoot = map2.sourceRoot ? getNormalizedAbsolutePath(map2.sourceRoot, mapDirectory) : mapDirectory;
  const generatedAbsoluteFilePath = getNormalizedAbsolutePath(map2.file, mapDirectory);
  const generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
  const sourceFileAbsolutePaths = map2.sources.map((source) => getNormalizedAbsolutePath(source, sourceRoot));
  const sourceToSourceIndexMap = new Map(sourceFileAbsolutePaths.map((source, i) => [host.getCanonicalFileName(source), i]));
  let decodedMappings;
  let generatedMappings;
  let sourceMappings;
  return {
    getSourcePosition,
    getGeneratedPosition
  };
  function processMapping(mapping) {
    const generatedPosition = generatedFile !== void 0 ? getPositionOfLineAndCharacter(
      generatedFile,
      mapping.generatedLine,
      mapping.generatedCharacter,
      /*allowEdits*/
      true
    ) : -1;
    let source;
    let sourcePosition;
    if (isSourceMapping(mapping)) {
      const sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
      source = map2.sources[mapping.sourceIndex];
      sourcePosition = sourceFile !== void 0 ? getPositionOfLineAndCharacter(
        sourceFile,
        mapping.sourceLine,
        mapping.sourceCharacter,
        /*allowEdits*/
        true
      ) : -1;
    }
    return {
      generatedPosition,
      source,
      sourceIndex: mapping.sourceIndex,
      sourcePosition,
      nameIndex: mapping.nameIndex
    };
  }
  function getDecodedMappings() {
    if (decodedMappings === void 0) {
      const decoder = decodeMappings(map2.mappings);
      const mappings = arrayFrom(decoder, processMapping);
      if (decoder.error !== void 0) {
        if (host.log) {
          host.log(`Encountered error while decoding sourcemap: ${decoder.error}`);
        }
        decodedMappings = emptyArray;
      } else {
        decodedMappings = mappings;
      }
    }
    return decodedMappings;
  }
  function getSourceMappings(sourceIndex) {
    if (sourceMappings === void 0) {
      const lists = [];
      for (const mapping of getDecodedMappings()) {
        if (!isSourceMappedPosition(mapping))
          continue;
        let list = lists[mapping.sourceIndex];
        if (!list)
          lists[mapping.sourceIndex] = list = [];
        list.push(mapping);
      }
      sourceMappings = lists.map((list) => sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition));
    }
    return sourceMappings[sourceIndex];
  }
  function getGeneratedMappings() {
    if (generatedMappings === void 0) {
      const list = [];
      for (const mapping of getDecodedMappings()) {
        list.push(mapping);
      }
      generatedMappings = sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
    }
    return generatedMappings;
  }
  function getGeneratedPosition(loc) {
    const sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
    if (sourceIndex === void 0)
      return loc;
    const sourceMappings2 = getSourceMappings(sourceIndex);
    if (!some(sourceMappings2))
      return loc;
    let targetIndex = binarySearchKey(sourceMappings2, loc.pos, getSourcePositionOfMapping, compareValues);
    if (targetIndex < 0) {
      targetIndex = ~targetIndex;
    }
    const mapping = sourceMappings2[targetIndex];
    if (mapping === void 0 || mapping.sourceIndex !== sourceIndex) {
      return loc;
    }
    return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition };
  }
  function getSourcePosition(loc) {
    const generatedMappings2 = getGeneratedMappings();
    if (!some(generatedMappings2))
      return loc;
    let targetIndex = binarySearchKey(generatedMappings2, loc.pos, getGeneratedPositionOfMapping, compareValues);
    if (targetIndex < 0) {
      targetIndex = ~targetIndex;
    }
    const mapping = generatedMappings2[targetIndex];
    if (mapping === void 0 || !isSourceMappedPosition(mapping)) {
      return loc;
    }
    return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition };
  }
}
var identitySourceMapConsumer = {
  getSourcePosition: identity,
  getGeneratedPosition: identity
};

// src/compiler/transformers/utilities.ts
function getOriginalNodeId(node) {
  node = getOriginalNode(node);
  return node ? getNodeId(node) : 0;
}
function containsDefaultReference(node) {
  if (!node)
    return false;
  if (!isNamedImports(node))
    return false;
  return some(node.elements, isNamedDefaultReference);
}
function isNamedDefaultReference(e) {
  return e.propertyName !== void 0 && e.propertyName.escapedText === "default" /* Default */;
}
function chainBundle(context, transformSourceFile) {
  return transformSourceFileOrBundle;
  function transformSourceFileOrBundle(node) {
    return node.kind === 311 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
  }
  function transformBundle(node) {
    return context.factory.createBundle(map(node.sourceFiles, transformSourceFile), node.prepends);
  }
}
function getExportNeedsImportStarHelper(node) {
  return !!getNamespaceDeclarationNode(node);
}
function getImportNeedsImportStarHelper(node) {
  if (!!getNamespaceDeclarationNode(node)) {
    return true;
  }
  const bindings = node.importClause && node.importClause.namedBindings;
  if (!bindings) {
    return false;
  }
  if (!isNamedImports(bindings))
    return false;
  let defaultRefCount = 0;
  for (const binding of bindings.elements) {
    if (isNamedDefaultReference(binding)) {
      defaultRefCount++;
    }
  }
  return defaultRefCount > 0 && defaultRefCount !== bindings.elements.length || !!(bindings.elements.length - defaultRefCount) && isDefaultImport(node);
}
function getImportNeedsImportDefaultHelper(node) {
  return !getImportNeedsImportStarHelper(node) && (isDefaultImport(node) || !!node.importClause && isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings));
}
function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) {
  const externalImports = [];
  const exportSpecifiers = createMultiMap();
  const exportedBindings = [];
  const uniqueExports = /* @__PURE__ */ new Map();
  let exportedNames;
  let hasExportDefault = false;
  let exportEquals;
  let hasExportStarsToExportValues = false;
  let hasImportStar = false;
  let hasImportDefault = false;
  for (const node of sourceFile.statements) {
    switch (node.kind) {
      case 271 /* ImportDeclaration */:
        externalImports.push(node);
        if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
          hasImportStar = true;
        }
        if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
          hasImportDefault = true;
        }
        break;
      case 270 /* ImportEqualsDeclaration */:
        if (node.moduleReference.kind === 282 /* ExternalModuleReference */) {
          externalImports.push(node);
        }
        break;
      case 277 /* ExportDeclaration */:
        if (node.moduleSpecifier) {
          if (!node.exportClause) {
            externalImports.push(node);
            hasExportStarsToExportValues = true;
          } else {
            externalImports.push(node);
            if (isNamedExports(node.exportClause)) {
              addExportedNamesForExportDeclaration(node);
            } else {
              const name = node.exportClause.name;
              if (!uniqueExports.get(idText(name))) {
                multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
                uniqueExports.set(idText(name), true);
                exportedNames = append(exportedNames, name);
              }
              hasImportStar = true;
            }
          }
        } else {
          addExportedNamesForExportDeclaration(node);
        }
        break;
      case 276 /* ExportAssignment */:
        if (node.isExportEquals && !exportEquals) {
          exportEquals = node;
        }
        break;
      case 242 /* VariableStatement */:
        if (hasSyntacticModifier(node, 1 /* Export */)) {
          for (const decl of node.declarationList.declarations) {
            exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings);
          }
        }
        break;
      case 261 /* FunctionDeclaration */:
        if (hasSyntacticModifier(node, 1 /* Export */)) {
          if (hasSyntacticModifier(node, 1024 /* Default */)) {
            if (!hasExportDefault) {
              multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
              hasExportDefault = true;
            }
          } else {
            const name = node.name;
            if (!uniqueExports.get(idText(name))) {
              multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
              uniqueExports.set(idText(name), true);
              exportedNames = append(exportedNames, name);
            }
          }
        }
        break;
      case 262 /* ClassDeclaration */:
        if (hasSyntacticModifier(node, 1 /* Export */)) {
          if (hasSyntacticModifier(node, 1024 /* Default */)) {
            if (!hasExportDefault) {
              multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
              hasExportDefault = true;
            }
          } else {
            const name = node.name;
            if (name && !uniqueExports.get(idText(name))) {
              multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
              uniqueExports.set(idText(name), true);
              exportedNames = append(exportedNames, name);
            }
          }
        }
        break;
    }
  }
  const externalHelpersImportDeclaration = createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
  if (externalHelpersImportDeclaration) {
    externalImports.unshift(externalHelpersImportDeclaration);
  }
  return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, externalHelpersImportDeclaration };
  function addExportedNamesForExportDeclaration(node) {
    for (const specifier of cast(node.exportClause, isNamedExports).elements) {
      if (!uniqueExports.get(idText(specifier.name))) {
        const name = specifier.propertyName || specifier.name;
        if (!node.moduleSpecifier) {
          exportSpecifiers.add(idText(name), specifier);
        }
        const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name);
        if (decl) {
          multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
        }
        uniqueExports.set(idText(specifier.name), true);
        exportedNames = append(exportedNames, specifier.name);
      }
    }
  }
}
function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) {
  if (isBindingPattern(decl.name)) {
    for (const element of decl.name.elements) {
      if (!isOmittedExpression(element)) {
        exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings);
      }
    }
  } else if (!isGeneratedIdentifier(decl.name)) {
    const text = idText(decl.name);
    if (!uniqueExports.get(text)) {
      uniqueExports.set(text, true);
      exportedNames = append(exportedNames, decl.name);
      if (isLocalName(decl.name)) {
        multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name);
      }
    }
  }
  return exportedNames;
}
function multiMapSparseArrayAdd(map2, key, value) {
  let values = map2[key];
  if (values) {
    values.push(value);
  } else {
    map2[key] = values = [value];
  }
  return values;
}
function isSimpleCopiableExpression(expression) {
  return isStringLiteralLike(expression) || expression.kind === 9 /* NumericLiteral */ || isKeyword(expression.kind) || isIdentifier(expression);
}
function isSimpleInlineableExpression(expression) {
  return !isIdentifier(expression) && isSimpleCopiableExpression(expression);
}
function isCompoundAssignment(kind) {
  return kind >= 65 /* FirstCompoundAssignment */ && kind <= 79 /* LastCompoundAssignment */;
}
function getNonAssignmentOperatorForCompoundAssignment(kind) {
  switch (kind) {
    case 65 /* PlusEqualsToken */:
      return 40 /* PlusToken */;
    case 66 /* MinusEqualsToken */:
      return 41 /* MinusToken */;
    case 67 /* AsteriskEqualsToken */:
      return 42 /* AsteriskToken */;
    case 68 /* AsteriskAsteriskEqualsToken */:
      return 43 /* AsteriskAsteriskToken */;
    case 69 /* SlashEqualsToken */:
      return 44 /* SlashToken */;
    case 70 /* PercentEqualsToken */:
      return 45 /* PercentToken */;
    case 71 /* LessThanLessThanEqualsToken */:
      return 48 /* LessThanLessThanToken */;
    case 72 /* GreaterThanGreaterThanEqualsToken */:
      return 49 /* GreaterThanGreaterThanToken */;
    case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      return 50 /* GreaterThanGreaterThanGreaterThanToken */;
    case 74 /* AmpersandEqualsToken */:
      return 51 /* AmpersandToken */;
    case 75 /* BarEqualsToken */:
      return 52 /* BarToken */;
    case 79 /* CaretEqualsToken */:
      return 53 /* CaretToken */;
    case 76 /* BarBarEqualsToken */:
      return 57 /* BarBarToken */;
    case 77 /* AmpersandAmpersandEqualsToken */:
      return 56 /* AmpersandAmpersandToken */;
    case 78 /* QuestionQuestionEqualsToken */:
      return 61 /* QuestionQuestionToken */;
  }
}
function getSuperCallFromStatement(statement) {
  if (!isExpressionStatement(statement)) {
    return void 0;
  }
  const expression = skipParentheses(statement.expression);
  return isSuperCall(expression) ? expression : void 0;
}
function findSuperStatementIndex(statements, indexAfterLastPrologueStatement) {
  for (let i = indexAfterLastPrologueStatement; i < statements.length; i += 1) {
    const statement = statements[i];
    if (getSuperCallFromStatement(statement)) {
      return i;
    }
  }
  return -1;
}
function getProperties(node, requireInitializer, isStatic2) {
  return filter(node.members, (m) => isInitializedOrStaticProperty(m, requireInitializer, isStatic2));
}
function isStaticPropertyDeclarationOrClassStaticBlockDeclaration(element) {
  return isStaticPropertyDeclaration(element) || isClassStaticBlockDeclaration(element);
}
function getStaticPropertiesAndClassStaticBlock(node) {
  return filter(node.members, isStaticPropertyDeclarationOrClassStaticBlockDeclaration);
}
function isInitializedOrStaticProperty(member, requireInitializer, isStatic2) {
  return isPropertyDeclaration(member) && (!!member.initializer || !requireInitializer) && hasStaticModifier(member) === isStatic2;
}
function isStaticPropertyDeclaration(member) {
  return isPropertyDeclaration(member) && hasStaticModifier(member);
}
function isInitializedProperty(member) {
  return member.kind === 171 /* PropertyDeclaration */ && member.initializer !== void 0;
}
function isNonStaticMethodOrAccessorWithPrivateName(member) {
  return !isStatic(member) && (isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member)) && isPrivateIdentifier(member.name);
}
function getDecoratorsOfParameters(node) {
  let decorators;
  if (node) {
    const parameters = node.parameters;
    const firstParameterIsThis = parameters.length > 0 && parameterIsThisKeyword(parameters[0]);
    const firstParameterOffset = firstParameterIsThis ? 1 : 0;
    const numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
    for (let i = 0; i < numParameters; i++) {
      const parameter = parameters[i + firstParameterOffset];
      if (decorators || hasDecorators(parameter)) {
        if (!decorators) {
          decorators = new Array(numParameters);
        }
        decorators[i] = getDecorators(parameter);
      }
    }
  }
  return decorators;
}
function getAllDecoratorsOfClass(node) {
  const decorators = getDecorators(node);
  const parameters = getDecoratorsOfParameters(getFirstConstructorWithBody(node));
  if (!some(decorators) && !some(parameters)) {
    return void 0;
  }
  return {
    decorators,
    parameters
  };
}
function getAllDecoratorsOfClassElement(member, parent2, useLegacyDecorators) {
  switch (member.kind) {
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
      if (!useLegacyDecorators) {
        return getAllDecoratorsOfMethod(member);
      }
      return getAllDecoratorsOfAccessors(member, parent2);
    case 173 /* MethodDeclaration */:
      return getAllDecoratorsOfMethod(member);
    case 171 /* PropertyDeclaration */:
      return getAllDecoratorsOfProperty(member);
    default:
      return void 0;
  }
}
function getAllDecoratorsOfAccessors(accessor, parent2) {
  if (!accessor.body) {
    return void 0;
  }
  const { firstAccessor, secondAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(parent2.members, accessor);
  const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0;
  if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
    return void 0;
  }
  const decorators = getDecorators(firstAccessorWithDecorators);
  const parameters = getDecoratorsOfParameters(setAccessor);
  if (!some(decorators) && !some(parameters)) {
    return void 0;
  }
  return {
    decorators,
    parameters,
    getDecorators: getAccessor && getDecorators(getAccessor),
    setDecorators: setAccessor && getDecorators(setAccessor)
  };
}
function getAllDecoratorsOfMethod(method) {
  if (!method.body) {
    return void 0;
  }
  const decorators = getDecorators(method);
  const parameters = getDecoratorsOfParameters(method);
  if (!some(decorators) && !some(parameters)) {
    return void 0;
  }
  return { decorators, parameters };
}
function getAllDecoratorsOfProperty(property) {
  const decorators = getDecorators(property);
  if (!some(decorators)) {
    return void 0;
  }
  return { decorators };
}
function walkUpLexicalEnvironments(env, cb) {
  while (env) {
    const result = cb(env);
    if (result !== void 0)
      return result;
    env = env.previous;
  }
}
function newPrivateEnvironment(data) {
  return { data };
}
function getPrivateIdentifier(privateEnv, name) {
  var _a, _b;
  return isGeneratedPrivateIdentifier(name) ? (_a = privateEnv == null ? void 0 : privateEnv.generatedIdentifiers) == null ? void 0 : _a.get(getNodeForGeneratedName(name)) : (_b = privateEnv == null ? void 0 : privateEnv.identifiers) == null ? void 0 : _b.get(name.escapedText);
}
function setPrivateIdentifier(privateEnv, name, entry) {
  if (isGeneratedPrivateIdentifier(name)) {
    privateEnv.generatedIdentifiers ?? (privateEnv.generatedIdentifiers = /* @__PURE__ */ new Map());
    privateEnv.generatedIdentifiers.set(getNodeForGeneratedName(name), entry);
  } else {
    privateEnv.identifiers ?? (privateEnv.identifiers = /* @__PURE__ */ new Map());
    privateEnv.identifiers.set(name.escapedText, entry);
  }
}
function accessPrivateIdentifier(env, name) {
  return walkUpLexicalEnvironments(env, (env2) => getPrivateIdentifier(env2.privateEnv, name));
}

// src/compiler/transformers/destructuring.ts
var FlattenLevel = /* @__PURE__ */ ((FlattenLevel2) => {
  FlattenLevel2[FlattenLevel2["All"] = 0] = "All";
  FlattenLevel2[FlattenLevel2["ObjectRest"] = 1] = "ObjectRest";
  return FlattenLevel2;
})(FlattenLevel || {});
function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
  let location = node;
  let value;
  if (isDestructuringAssignment(node)) {
    value = node.right;
    while (isEmptyArrayLiteral(node.left) || isEmptyObjectLiteral(node.left)) {
      if (isDestructuringAssignment(value)) {
        location = node = value;
        value = node.right;
      } else {
        return Debug.checkDefined(visitNode(value, visitor, isExpression));
      }
    }
  }
  let expressions;
  const flattenContext = {
    context,
    level,
    downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
    hoistTempVariables: true,
    emitExpression,
    emitBindingOrAssignment,
    createArrayBindingOrAssignmentPattern: (elements) => makeArrayAssignmentPattern(context.factory, elements),
    createObjectBindingOrAssignmentPattern: (elements) => makeObjectAssignmentPattern(context.factory, elements),
    createArrayBindingOrAssignmentElement: makeAssignmentElement,
    visitor
  };
  if (value) {
    value = visitNode(value, visitor, isExpression);
    Debug.assert(value);
    if (isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
      value = ensureIdentifier(
        flattenContext,
        value,
        /*reuseIdentifierExpressions*/
        false,
        location
      );
    } else if (needsValue) {
      value = ensureIdentifier(
        flattenContext,
        value,
        /*reuseIdentifierExpressions*/
        true,
        location
      );
    } else if (nodeIsSynthesized(node)) {
      location = value;
    }
  }
  flattenBindingOrAssignmentElement(
    flattenContext,
    node,
    value,
    location,
    /*skipInitializer*/
    isDestructuringAssignment(node)
  );
  if (value && needsValue) {
    if (!some(expressions)) {
      return value;
    }
    expressions.push(value);
  }
  return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression();
  function emitExpression(expression) {
    expressions = append(expressions, expression);
  }
  function emitBindingOrAssignment(target, value2, location2, original) {
    Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression);
    const expression = createAssignmentCallback ? createAssignmentCallback(target, value2, location2) : setTextRange(
      context.factory.createAssignment(Debug.checkDefined(visitNode(target, visitor, isExpression)), value2),
      location2
    );
    expression.original = original;
    emitExpression(expression);
  }
}
function bindingOrAssignmentElementAssignsToName(element, escapedName) {
  const target = getTargetOfBindingOrAssignmentElement(element);
  if (isBindingOrAssignmentPattern(target)) {
    return bindingOrAssignmentPatternAssignsToName(target, escapedName);
  } else if (isIdentifier(target)) {
    return target.escapedText === escapedName;
  }
  return false;
}
function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
  const elements = getElementsOfBindingOrAssignmentPattern(pattern);
  for (const element of elements) {
    if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
      return true;
    }
  }
  return false;
}
function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
  const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element);
  if (propertyName && isComputedPropertyName(propertyName) && !isLiteralExpression(propertyName.expression)) {
    return true;
  }
  const target = getTargetOfBindingOrAssignmentElement(element);
  return !!target && isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
}
function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
  return !!forEach(getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
}
function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables = false, skipInitializer) {
  let pendingExpressions;
  const pendingDeclarations = [];
  const declarations = [];
  const flattenContext = {
    context,
    level,
    downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
    hoistTempVariables,
    emitExpression,
    emitBindingOrAssignment,
    createArrayBindingOrAssignmentPattern: (elements) => makeArrayBindingPattern(context.factory, elements),
    createObjectBindingOrAssignmentPattern: (elements) => makeObjectBindingPattern(context.factory, elements),
    createArrayBindingOrAssignmentElement: (name) => makeBindingElement(context.factory, name),
    visitor
  };
  if (isVariableDeclaration(node)) {
    let initializer = getInitializerOfBindingOrAssignmentElement(node);
    if (initializer && (isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
      initializer = ensureIdentifier(
        flattenContext,
        Debug.checkDefined(visitNode(initializer, flattenContext.visitor, isExpression)),
        /*reuseIdentifierExpressions*/
        false,
        initializer
      );
      node = context.factory.updateVariableDeclaration(
        node,
        node.name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        initializer
      );
    }
  }
  flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
  if (pendingExpressions) {
    const temp = context.factory.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    if (hoistTempVariables) {
      const value = context.factory.inlineExpressions(pendingExpressions);
      pendingExpressions = void 0;
      emitBindingOrAssignment(
        temp,
        value,
        /*location*/
        void 0,
        /*original*/
        void 0
      );
    } else {
      context.hoistVariableDeclaration(temp);
      const pendingDeclaration = last(pendingDeclarations);
      pendingDeclaration.pendingExpressions = append(
        pendingDeclaration.pendingExpressions,
        context.factory.createAssignment(temp, pendingDeclaration.value)
      );
      addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
      pendingDeclaration.value = temp;
    }
  }
  for (const { pendingExpressions: pendingExpressions2, name, value, location, original } of pendingDeclarations) {
    const variable = context.factory.createVariableDeclaration(
      name,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      pendingExpressions2 ? context.factory.inlineExpressions(append(pendingExpressions2, value)) : value
    );
    variable.original = original;
    setTextRange(variable, location);
    declarations.push(variable);
  }
  return declarations;
  function emitExpression(value) {
    pendingExpressions = append(pendingExpressions, value);
  }
  function emitBindingOrAssignment(target, value, location, original) {
    Debug.assertNode(target, isBindingName);
    if (pendingExpressions) {
      value = context.factory.inlineExpressions(append(pendingExpressions, value));
      pendingExpressions = void 0;
    }
    pendingDeclarations.push({ pendingExpressions, name: target, value, location, original });
  }
}
function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
  const bindingTarget = getTargetOfBindingOrAssignmentElement(element);
  if (!skipInitializer) {
    const initializer = visitNode(getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, isExpression);
    if (initializer) {
      if (value) {
        value = createDefaultValueCheck(flattenContext, value, initializer, location);
        if (!isSimpleInlineableExpression(initializer) && isBindingOrAssignmentPattern(bindingTarget)) {
          value = ensureIdentifier(
            flattenContext,
            value,
            /*reuseIdentifierExpressions*/
            true,
            location
          );
        }
      } else {
        value = initializer;
      }
    } else if (!value) {
      value = flattenContext.context.factory.createVoidZero();
    }
  }
  if (isObjectBindingOrAssignmentPattern(bindingTarget)) {
    flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
  } else if (isArrayBindingOrAssignmentPattern(bindingTarget)) {
    flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
  } else {
    flattenContext.emitBindingOrAssignment(
      bindingTarget,
      value,
      location,
      /*original*/
      element
    );
  }
}
function flattenObjectBindingOrAssignmentPattern(flattenContext, parent2, pattern, value, location) {
  const elements = getElementsOfBindingOrAssignmentPattern(pattern);
  const numElements = elements.length;
  if (numElements !== 1) {
    const reuseIdentifierExpressions = !isDeclarationBindingElement(parent2) || numElements !== 0;
    value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
  }
  let bindingElements;
  let computedTempVariables;
  for (let i = 0; i < numElements; i++) {
    const element = elements[i];
    if (!getRestIndicatorOfBindingOrAssignmentElement(element)) {
      const propertyName = getPropertyNameOfBindingOrAssignmentElement(element);
      if (flattenContext.level >= 1 /* ObjectRest */ && !(element.transformFlags & (32768 /* ContainsRestOrSpread */ | 65536 /* ContainsObjectRestOrSpread */)) && !(getTargetOfBindingOrAssignmentElement(element).transformFlags & (32768 /* ContainsRestOrSpread */ | 65536 /* ContainsObjectRestOrSpread */)) && !isComputedPropertyName(propertyName)) {
        bindingElements = append(bindingElements, visitNode(element, flattenContext.visitor, isBindingOrAssignmentElement));
      } else {
        if (bindingElements) {
          flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
          bindingElements = void 0;
        }
        const rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
        if (isComputedPropertyName(propertyName)) {
          computedTempVariables = append(computedTempVariables, rhsValue.argumentExpression);
        }
        flattenBindingOrAssignmentElement(
          flattenContext,
          element,
          rhsValue,
          /*location*/
          element
        );
      }
    } else if (i === numElements - 1) {
      if (bindingElements) {
        flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
        bindingElements = void 0;
      }
      const rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern);
      flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
    }
  }
  if (bindingElements) {
    flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
  }
}
function flattenArrayBindingOrAssignmentPattern(flattenContext, parent2, pattern, value, location) {
  const elements = getElementsOfBindingOrAssignmentPattern(pattern);
  const numElements = elements.length;
  if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
    value = ensureIdentifier(
      flattenContext,
      setTextRange(
        flattenContext.context.getEmitHelperFactory().createReadHelper(
          value,
          numElements > 0 && getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) ? void 0 : numElements
        ),
        location
      ),
      /*reuseIdentifierExpressions*/
      false,
      location
    );
  } else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) || every(elements, isOmittedExpression)) {
    const reuseIdentifierExpressions = !isDeclarationBindingElement(parent2) || numElements !== 0;
    value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
  }
  let bindingElements;
  let restContainingElements;
  for (let i = 0; i < numElements; i++) {
    const element = elements[i];
    if (flattenContext.level >= 1 /* ObjectRest */) {
      if (element.transformFlags & 65536 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) {
        flattenContext.hasTransformedPriorElement = true;
        const temp = flattenContext.context.factory.createTempVariable(
          /*recordTempVariable*/
          void 0
        );
        if (flattenContext.hoistTempVariables) {
          flattenContext.context.hoistVariableDeclaration(temp);
        }
        restContainingElements = append(restContainingElements, [temp, element]);
        bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
      } else {
        bindingElements = append(bindingElements, element);
      }
    } else if (isOmittedExpression(element)) {
      continue;
    } else if (!getRestIndicatorOfBindingOrAssignmentElement(element)) {
      const rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i);
      flattenBindingOrAssignmentElement(
        flattenContext,
        element,
        rhsValue,
        /*location*/
        element
      );
    } else if (i === numElements - 1) {
      const rhsValue = flattenContext.context.factory.createArraySliceCall(value, i);
      flattenBindingOrAssignmentElement(
        flattenContext,
        element,
        rhsValue,
        /*location*/
        element
      );
    }
  }
  if (bindingElements) {
    flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
  }
  if (restContainingElements) {
    for (const [id, element] of restContainingElements) {
      flattenBindingOrAssignmentElement(flattenContext, element, id, element);
    }
  }
}
function isSimpleBindingOrAssignmentElement(element) {
  const target = getTargetOfBindingOrAssignmentElement(element);
  if (!target || isOmittedExpression(target))
    return true;
  const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element);
  if (propertyName && !isPropertyNameLiteral(propertyName))
    return false;
  const initializer = getInitializerOfBindingOrAssignmentElement(element);
  if (initializer && !isSimpleInlineableExpression(initializer))
    return false;
  if (isBindingOrAssignmentPattern(target))
    return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement);
  return isIdentifier(target);
}
function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
  value = ensureIdentifier(
    flattenContext,
    value,
    /*reuseIdentifierExpressions*/
    true,
    location
  );
  return flattenContext.context.factory.createConditionalExpression(
    flattenContext.context.factory.createTypeCheck(value, "undefined"),
    /*questionToken*/
    void 0,
    defaultValue,
    /*colonToken*/
    void 0,
    value
  );
}
function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
  const { factory: factory2 } = flattenContext.context;
  if (isComputedPropertyName(propertyName)) {
    const argumentExpression = ensureIdentifier(
      flattenContext,
      Debug.checkDefined(visitNode(propertyName.expression, flattenContext.visitor, isExpression)),
      /*reuseIdentifierExpressions*/
      false,
      /*location*/
      propertyName
    );
    return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
  } else if (isStringOrNumericLiteralLike(propertyName)) {
    const argumentExpression = factory2.cloneNode(propertyName);
    return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
  } else {
    const name = flattenContext.context.factory.createIdentifier(idText(propertyName));
    return flattenContext.context.factory.createPropertyAccessExpression(value, name);
  }
}
function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
  if (isIdentifier(value) && reuseIdentifierExpressions) {
    return value;
  } else {
    const temp = flattenContext.context.factory.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    if (flattenContext.hoistTempVariables) {
      flattenContext.context.hoistVariableDeclaration(temp);
      flattenContext.emitExpression(setTextRange(flattenContext.context.factory.createAssignment(temp, value), location));
    } else {
      flattenContext.emitBindingOrAssignment(
        temp,
        value,
        location,
        /*original*/
        void 0
      );
    }
    return temp;
  }
}
function makeArrayBindingPattern(factory2, elements) {
  Debug.assertEachNode(elements, isArrayBindingElement);
  return factory2.createArrayBindingPattern(elements);
}
function makeArrayAssignmentPattern(factory2, elements) {
  Debug.assertEachNode(elements, isArrayBindingOrAssignmentElement);
  return factory2.createArrayLiteralExpression(map(elements, factory2.converters.convertToArrayAssignmentElement));
}
function makeObjectBindingPattern(factory2, elements) {
  Debug.assertEachNode(elements, isBindingElement);
  return factory2.createObjectBindingPattern(elements);
}
function makeObjectAssignmentPattern(factory2, elements) {
  Debug.assertEachNode(elements, isObjectBindingOrAssignmentElement);
  return factory2.createObjectLiteralExpression(map(elements, factory2.converters.convertToObjectAssignmentElement));
}
function makeBindingElement(factory2, name) {
  return factory2.createBindingElement(
    /*dotDotDotToken*/
    void 0,
    /*propertyName*/
    void 0,
    name
  );
}
function makeAssignmentElement(name) {
  return name;
}

// src/compiler/transformers/taggedTemplate.ts
var ProcessLevel = /* @__PURE__ */ ((ProcessLevel2) => {
  ProcessLevel2[ProcessLevel2["LiftRestriction"] = 0] = "LiftRestriction";
  ProcessLevel2[ProcessLevel2["All"] = 1] = "All";
  return ProcessLevel2;
})(ProcessLevel || {});
function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
  const tag = visitNode(node.tag, visitor, isExpression);
  Debug.assert(tag);
  const templateArguments = [void 0];
  const cookedStrings = [];
  const rawStrings = [];
  const template = node.template;
  if (level === 0 /* LiftRestriction */ && !hasInvalidEscape(template)) {
    return visitEachChild(node, visitor, context);
  }
  const { factory: factory2 } = context;
  if (isNoSubstitutionTemplateLiteral(template)) {
    cookedStrings.push(createTemplateCooked(factory2, template));
    rawStrings.push(getRawLiteral(factory2, template, currentSourceFile));
  } else {
    cookedStrings.push(createTemplateCooked(factory2, template.head));
    rawStrings.push(getRawLiteral(factory2, template.head, currentSourceFile));
    for (const templateSpan of template.templateSpans) {
      cookedStrings.push(createTemplateCooked(factory2, templateSpan.literal));
      rawStrings.push(getRawLiteral(factory2, templateSpan.literal, currentSourceFile));
      templateArguments.push(Debug.checkDefined(visitNode(templateSpan.expression, visitor, isExpression)));
    }
  }
  const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(
    factory2.createArrayLiteralExpression(cookedStrings),
    factory2.createArrayLiteralExpression(rawStrings)
  );
  if (isExternalModule(currentSourceFile)) {
    const tempVar = factory2.createUniqueName("templateObject");
    recordTaggedTemplateString(tempVar);
    templateArguments[0] = factory2.createLogicalOr(
      tempVar,
      factory2.createAssignment(
        tempVar,
        helperCall
      )
    );
  } else {
    templateArguments[0] = helperCall;
  }
  return factory2.createCallExpression(
    tag,
    /*typeArguments*/
    void 0,
    templateArguments
  );
}
function createTemplateCooked(factory2, template) {
  return template.templateFlags & 26656 /* IsInvalid */ ? factory2.createVoidZero() : factory2.createStringLiteral(template.text);
}
function getRawLiteral(factory2, node, currentSourceFile) {
  let text = node.rawText;
  if (text === void 0) {
    Debug.assertIsDefined(
      currentSourceFile,
      "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform."
    );
    text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
    const isLast = node.kind === 15 /* NoSubstitutionTemplateLiteral */ || node.kind === 18 /* TemplateTail */;
    text = text.substring(1, text.length - (isLast ? 1 : 2));
  }
  text = text.replace(/\r\n?/g, "\n");
  return setTextRange(factory2.createStringLiteral(text), node);
}

// src/compiler/transformers/ts.ts
var USE_NEW_TYPE_METADATA_FORMAT = false;
function transformTypeScript(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    startLexicalEnvironment,
    resumeLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const moduleKind = getEmitModuleKind(compilerOptions);
  const legacyDecorators = !!compilerOptions.experimentalDecorators;
  const typeSerializer = compilerOptions.emitDecoratorMetadata ? createRuntimeTypeSerializer(context) : void 0;
  const previousOnEmitNode = context.onEmitNode;
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  context.enableSubstitution(210 /* PropertyAccessExpression */);
  context.enableSubstitution(211 /* ElementAccessExpression */);
  let currentSourceFile;
  let currentNamespace;
  let currentNamespaceContainerName;
  let currentLexicalScope;
  let currentScopeFirstDeclarationsOfName;
  let currentClassHasParameterProperties;
  let enabledSubstitutions;
  let applicableSubstitutions;
  return transformSourceFileOrBundle;
  function transformSourceFileOrBundle(node) {
    if (node.kind === 312 /* Bundle */) {
      return transformBundle(node);
    }
    return transformSourceFile(node);
  }
  function transformBundle(node) {
    return factory2.createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, (prepend) => {
      if (prepend.kind === 314 /* InputFiles */) {
        return createUnparsedSourceFile(prepend, "js");
      }
      return prepend;
    }));
  }
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    currentSourceFile = node;
    const visited = saveStateAndInvoke(node, visitSourceFile);
    addEmitHelpers(visited, context.readEmitHelpers());
    currentSourceFile = void 0;
    return visited;
  }
  function saveStateAndInvoke(node, f) {
    const savedCurrentScope = currentLexicalScope;
    const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
    const savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
    onBeforeVisitNode(node);
    const visited = f(node);
    if (currentLexicalScope !== savedCurrentScope) {
      currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
    }
    currentLexicalScope = savedCurrentScope;
    currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
    return visited;
  }
  function onBeforeVisitNode(node) {
    switch (node.kind) {
      case 311 /* SourceFile */:
      case 268 /* CaseBlock */:
      case 267 /* ModuleBlock */:
      case 240 /* Block */:
        currentLexicalScope = node;
        currentScopeFirstDeclarationsOfName = void 0;
        break;
      case 262 /* ClassDeclaration */:
      case 261 /* FunctionDeclaration */:
        if (hasSyntacticModifier(node, 2 /* Ambient */)) {
          break;
        }
        if (node.name) {
          recordEmittedDeclarationInScope(node);
        } else {
          Debug.assert(node.kind === 262 /* ClassDeclaration */ || hasSyntacticModifier(node, 1024 /* Default */));
        }
        break;
    }
  }
  function visitor(node) {
    return saveStateAndInvoke(node, visitorWorker);
  }
  function visitorWorker(node) {
    if (node.transformFlags & 1 /* ContainsTypeScript */) {
      return visitTypeScript(node);
    }
    return node;
  }
  function sourceElementVisitor(node) {
    return saveStateAndInvoke(node, sourceElementVisitorWorker);
  }
  function sourceElementVisitorWorker(node) {
    switch (node.kind) {
      case 271 /* ImportDeclaration */:
      case 270 /* ImportEqualsDeclaration */:
      case 276 /* ExportAssignment */:
      case 277 /* ExportDeclaration */:
        return visitElidableStatement(node);
      default:
        return visitorWorker(node);
    }
  }
  function visitElidableStatement(node) {
    const parsed = getParseTreeNode(node);
    if (parsed !== node) {
      if (node.transformFlags & 1 /* ContainsTypeScript */) {
        return visitEachChild(node, visitor, context);
      }
      return node;
    }
    switch (node.kind) {
      case 271 /* ImportDeclaration */:
        return visitImportDeclaration(node);
      case 270 /* ImportEqualsDeclaration */:
        return visitImportEqualsDeclaration(node);
      case 276 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 277 /* ExportDeclaration */:
        return visitExportDeclaration(node);
      default:
        Debug.fail("Unhandled ellided statement");
    }
  }
  function namespaceElementVisitor(node) {
    return saveStateAndInvoke(node, namespaceElementVisitorWorker);
  }
  function namespaceElementVisitorWorker(node) {
    if (node.kind === 277 /* ExportDeclaration */ || node.kind === 271 /* ImportDeclaration */ || node.kind === 272 /* ImportClause */ || node.kind === 270 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 282 /* ExternalModuleReference */) {
      return void 0;
    } else if (node.transformFlags & 1 /* ContainsTypeScript */ || hasSyntacticModifier(node, 1 /* Export */)) {
      return visitTypeScript(node);
    }
    return node;
  }
  function getClassElementVisitor(parent2) {
    return (node) => saveStateAndInvoke(node, (n) => classElementVisitorWorker(n, parent2));
  }
  function classElementVisitorWorker(node, parent2) {
    switch (node.kind) {
      case 175 /* Constructor */:
        return visitConstructor(node);
      case 171 /* PropertyDeclaration */:
        return visitPropertyDeclaration(node, parent2);
      case 176 /* GetAccessor */:
        return visitGetAccessor(node, parent2);
      case 177 /* SetAccessor */:
        return visitSetAccessor(node, parent2);
      case 173 /* MethodDeclaration */:
        return visitMethodDeclaration(node, parent2);
      case 174 /* ClassStaticBlockDeclaration */:
        return visitEachChild(node, visitor, context);
      case 239 /* SemicolonClassElement */:
        return node;
      case 180 /* IndexSignature */:
        return;
      default:
        return Debug.failBadSyntaxKind(node);
    }
  }
  function getObjectLiteralElementVisitor(parent2) {
    return (node) => saveStateAndInvoke(node, (n) => objectLiteralElementVisitorWorker(n, parent2));
  }
  function objectLiteralElementVisitorWorker(node, parent2) {
    switch (node.kind) {
      case 302 /* PropertyAssignment */:
      case 303 /* ShorthandPropertyAssignment */:
      case 304 /* SpreadAssignment */:
        return visitor(node);
      case 176 /* GetAccessor */:
        return visitGetAccessor(node, parent2);
      case 177 /* SetAccessor */:
        return visitSetAccessor(node, parent2);
      case 173 /* MethodDeclaration */:
        return visitMethodDeclaration(node, parent2);
      default:
        return Debug.failBadSyntaxKind(node);
    }
  }
  function decoratorElidingVisitor(node) {
    return isDecorator(node) ? void 0 : visitor(node);
  }
  function modifierElidingVisitor(node) {
    return isModifier(node) ? void 0 : visitor(node);
  }
  function modifierVisitor(node) {
    if (isDecorator(node))
      return void 0;
    if (modifierToFlag(node.kind) & 117086 /* TypeScriptModifier */) {
      return void 0;
    } else if (currentNamespace && node.kind === 95 /* ExportKeyword */) {
      return void 0;
    }
    return node;
  }
  function visitTypeScript(node) {
    if (isStatement(node) && hasSyntacticModifier(node, 2 /* Ambient */)) {
      return factory2.createNotEmittedStatement(node);
    }
    switch (node.kind) {
      case 95 /* ExportKeyword */:
      case 90 /* DefaultKeyword */:
        return currentNamespace ? void 0 : node;
      case 125 /* PublicKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
      case 128 /* AbstractKeyword */:
      case 163 /* OverrideKeyword */:
      case 87 /* ConstKeyword */:
      case 138 /* DeclareKeyword */:
      case 148 /* ReadonlyKeyword */:
      case 103 /* InKeyword */:
      case 147 /* OutKeyword */:
      case 187 /* ArrayType */:
      case 188 /* TupleType */:
      case 189 /* OptionalType */:
      case 190 /* RestType */:
      case 186 /* TypeLiteral */:
      case 181 /* TypePredicate */:
      case 167 /* TypeParameter */:
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 136 /* BooleanKeyword */:
      case 154 /* StringKeyword */:
      case 150 /* NumberKeyword */:
      case 146 /* NeverKeyword */:
      case 116 /* VoidKeyword */:
      case 155 /* SymbolKeyword */:
      case 184 /* ConstructorType */:
      case 183 /* FunctionType */:
      case 185 /* TypeQuery */:
      case 182 /* TypeReference */:
      case 191 /* UnionType */:
      case 192 /* IntersectionType */:
      case 193 /* ConditionalType */:
      case 195 /* ParenthesizedType */:
      case 196 /* ThisType */:
      case 197 /* TypeOperator */:
      case 198 /* IndexedAccessType */:
      case 199 /* MappedType */:
      case 200 /* LiteralType */:
      case 180 /* IndexSignature */:
        return void 0;
      case 264 /* TypeAliasDeclaration */:
        return factory2.createNotEmittedStatement(node);
      case 269 /* NamespaceExportDeclaration */:
        return void 0;
      case 263 /* InterfaceDeclaration */:
        return factory2.createNotEmittedStatement(node);
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 230 /* ClassExpression */:
        return visitClassExpression(node);
      case 297 /* HeritageClause */:
        return visitHeritageClause(node);
      case 232 /* ExpressionWithTypeArguments */:
        return visitExpressionWithTypeArguments(node);
      case 209 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 175 /* Constructor */:
      case 171 /* PropertyDeclaration */:
      case 173 /* MethodDeclaration */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
      case 174 /* ClassStaticBlockDeclaration */:
        return Debug.fail("Class and object literal elements must be visited with their respective visitors");
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 217 /* FunctionExpression */:
        return visitFunctionExpression(node);
      case 218 /* ArrowFunction */:
        return visitArrowFunction(node);
      case 168 /* Parameter */:
        return visitParameter(node);
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node);
      case 215 /* TypeAssertionExpression */:
      case 233 /* AsExpression */:
        return visitAssertionExpression(node);
      case 237 /* SatisfiesExpression */:
        return visitSatisfiesExpression(node);
      case 212 /* CallExpression */:
        return visitCallExpression(node);
      case 213 /* NewExpression */:
        return visitNewExpression(node);
      case 214 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 234 /* NonNullExpression */:
        return visitNonNullExpression(node);
      case 265 /* EnumDeclaration */:
        return visitEnumDeclaration(node);
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 259 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 266 /* ModuleDeclaration */:
        return visitModuleDeclaration(node);
      case 270 /* ImportEqualsDeclaration */:
        return visitImportEqualsDeclaration(node);
      case 284 /* JsxSelfClosingElement */:
        return visitJsxSelfClosingElement(node);
      case 285 /* JsxOpeningElement */:
        return visitJsxJsxOpeningElement(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitSourceFile(node) {
    const alwaysStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") && !(isExternalModule(node) && moduleKind >= 5 /* ES2015 */) && !isJsonSourceFile(node);
    return factory2.updateSourceFile(
      node,
      visitLexicalEnvironment(
        node.statements,
        sourceElementVisitor,
        context,
        /*start*/
        0,
        alwaysStrict
      )
    );
  }
  function visitObjectLiteralExpression(node) {
    return factory2.updateObjectLiteralExpression(
      node,
      visitNodes2(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElementLike)
    );
  }
  function getClassFacts(node) {
    let facts = 0 /* None */;
    if (some(getProperties(
      node,
      /*requireInitializer*/
      true,
      /*isStatic*/
      true
    )))
      facts |= 1 /* HasStaticInitializedProperties */;
    const extendsClauseElement = getEffectiveBaseTypeNode(node);
    if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */)
      facts |= 64 /* IsDerivedClass */;
    if (classOrConstructorParameterIsDecorated(legacyDecorators, node))
      facts |= 2 /* HasClassOrConstructorParameterDecorators */;
    if (childIsDecorated(legacyDecorators, node))
      facts |= 4 /* HasMemberDecorators */;
    if (isExportOfNamespace(node))
      facts |= 8 /* IsExportOfNamespace */;
    else if (isDefaultExternalModuleExport(node))
      facts |= 32 /* IsDefaultExternalExport */;
    else if (isNamedExternalModuleExport(node))
      facts |= 16 /* IsNamedExternalExport */;
    return facts;
  }
  function hasTypeScriptClassSyntax(node) {
    return !!(node.transformFlags & 8192 /* ContainsTypeScriptClassSyntax */);
  }
  function isClassLikeDeclarationWithTypeScriptSyntax(node) {
    return hasDecorators(node) || some(node.typeParameters) || some(node.heritageClauses, hasTypeScriptClassSyntax) || some(node.members, hasTypeScriptClassSyntax);
  }
  function visitClassDeclaration(node) {
    const facts = getClassFacts(node);
    const promoteToIIFE = languageVersion <= 1 /* ES5 */ && !!(facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */);
    if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !classOrConstructorParameterIsDecorated(legacyDecorators, node) && !isExportOfNamespace(node)) {
      return factory2.updateClassDeclaration(
        node,
        visitNodes2(node.modifiers, modifierVisitor, isModifier),
        node.name,
        /*typeParameters*/
        void 0,
        visitNodes2(node.heritageClauses, visitor, isHeritageClause),
        visitNodes2(node.members, getClassElementVisitor(node), isClassElement)
      );
    }
    if (promoteToIIFE) {
      context.startLexicalEnvironment();
    }
    const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */;
    let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike);
    if (facts & 2 /* HasClassOrConstructorParameterDecorators */) {
      modifiers = injectClassTypeMetadata(modifiers, node);
    }
    const needsName = moveModifiers && !node.name || facts & 4 /* HasMemberDecorators */ || facts & 1 /* HasStaticInitializedProperties */;
    const name = needsName ? node.name ?? factory2.getGeneratedNameForNode(node) : node.name;
    const classDeclaration = factory2.updateClassDeclaration(
      node,
      modifiers,
      name,
      /*typeParameters*/
      void 0,
      visitNodes2(node.heritageClauses, visitor, isHeritageClause),
      transformClassMembers(node)
    );
    let emitFlags = getEmitFlags(node);
    if (facts & 1 /* HasStaticInitializedProperties */) {
      emitFlags |= 64 /* NoTrailingSourceMap */;
    }
    setEmitFlags(classDeclaration, emitFlags);
    let statement;
    if (promoteToIIFE) {
      const statements = [classDeclaration];
      const closingBraceLocation = createTokenRange(skipTrivia(currentSourceFile.text, node.members.end), 20 /* CloseBraceToken */);
      const localName = factory2.getInternalName(node);
      const outer = factory2.createPartiallyEmittedExpression(localName);
      setTextRangeEnd(outer, closingBraceLocation.end);
      setEmitFlags(outer, 3072 /* NoComments */);
      const returnStatement = factory2.createReturnStatement(outer);
      setTextRangePos(returnStatement, closingBraceLocation.pos);
      setEmitFlags(returnStatement, 3072 /* NoComments */ | 768 /* NoTokenSourceMaps */);
      statements.push(returnStatement);
      insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
      const iife = factory2.createImmediatelyInvokedArrowFunction(statements);
      setInternalEmitFlags(iife, 1 /* TypeScriptClassWrapper */);
      const modifiers2 = facts & 16 /* IsNamedExternalExport */ ? factory2.createModifiersFromModifierFlags(1 /* Export */) : void 0;
      const varStatement = factory2.createVariableStatement(
        modifiers2,
        factory2.createVariableDeclarationList([
          factory2.createVariableDeclaration(
            factory2.getLocalName(
              node,
              /*allowComments*/
              false,
              /*allowSourceMaps*/
              false
            ),
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            iife
          )
        ], 1 /* Let */)
      );
      setOriginalNode(varStatement, node);
      setCommentRange(varStatement, node);
      setSourceMapRange(varStatement, moveRangePastDecorators(node));
      startOnNewLine(varStatement);
      statement = varStatement;
    } else {
      statement = classDeclaration;
    }
    if (moveModifiers) {
      if (facts & 8 /* IsExportOfNamespace */) {
        return [
          statement,
          createExportMemberAssignmentStatement(node)
        ];
      }
      if (facts & 32 /* IsDefaultExternalExport */) {
        return [
          statement,
          factory2.createExportDefault(factory2.getLocalName(
            node,
            /*allowComments*/
            false,
            /*allowSourceMaps*/
            true
          ))
        ];
      }
      if (facts & 16 /* IsNamedExternalExport */ && !promoteToIIFE) {
        return [
          statement,
          factory2.createExternalModuleExport(factory2.getLocalName(
            node,
            /*allowComments*/
            false,
            /*allowSourceMaps*/
            true
          ))
        ];
      }
    }
    return statement;
  }
  function visitClassExpression(node) {
    let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike);
    if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) {
      modifiers = injectClassTypeMetadata(modifiers, node);
    }
    return factory2.updateClassExpression(
      node,
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      visitNodes2(node.heritageClauses, visitor, isHeritageClause),
      transformClassMembers(node)
    );
  }
  function transformClassMembers(node) {
    const members = visitNodes2(node.members, getClassElementVisitor(node), isClassElement);
    let newMembers;
    const constructor = getFirstConstructorWithBody(node);
    const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p) => isParameterPropertyDeclaration(p, constructor));
    if (parametersWithPropertyAssignments) {
      for (const parameter of parametersWithPropertyAssignments) {
        const parameterProperty = factory2.createPropertyDeclaration(
          /*modifiers*/
          void 0,
          parameter.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        );
        setOriginalNode(parameterProperty, parameter);
        newMembers = append(newMembers, parameterProperty);
      }
    }
    if (newMembers) {
      newMembers = addRange(newMembers, members);
      return setTextRange(
        factory2.createNodeArray(newMembers),
        /*location*/
        node.members
      );
    }
    return members;
  }
  function injectClassTypeMetadata(modifiers, node) {
    const metadata = getTypeMetadata(node, node);
    if (some(metadata)) {
      const modifiersArray = [];
      addRange(modifiersArray, takeWhile(modifiers, isExportOrDefaultModifier));
      addRange(modifiersArray, filter(modifiers, isDecorator));
      addRange(modifiersArray, metadata);
      addRange(modifiersArray, filter(skipWhile(modifiers, isExportOrDefaultModifier), isModifier));
      modifiers = setTextRange(factory2.createNodeArray(modifiersArray), modifiers);
    }
    return modifiers;
  }
  function injectClassElementTypeMetadata(modifiers, node, container) {
    if (isClassLike(container) && classElementOrClassElementParameterIsDecorated(legacyDecorators, node, container)) {
      const metadata = getTypeMetadata(node, container);
      if (some(metadata)) {
        const modifiersArray = [];
        addRange(modifiersArray, filter(modifiers, isDecorator));
        addRange(modifiersArray, metadata);
        addRange(modifiersArray, filter(modifiers, isModifier));
        modifiers = setTextRange(factory2.createNodeArray(modifiersArray), modifiers);
      }
    }
    return modifiers;
  }
  function getTypeMetadata(node, container) {
    if (!legacyDecorators)
      return void 0;
    return USE_NEW_TYPE_METADATA_FORMAT ? getNewTypeMetadata(node, container) : getOldTypeMetadata(node, container);
  }
  function getOldTypeMetadata(node, container) {
    if (typeSerializer) {
      let decorators;
      if (shouldAddTypeMetadata(node)) {
        const typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node));
        decorators = append(decorators, factory2.createDecorator(typeMetadata));
      }
      if (shouldAddParamTypesMetadata(node)) {
        const paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container));
        decorators = append(decorators, factory2.createDecorator(paramTypesMetadata));
      }
      if (shouldAddReturnTypeMetadata(node)) {
        const returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node));
        decorators = append(decorators, factory2.createDecorator(returnTypeMetadata));
      }
      return decorators;
    }
  }
  function getNewTypeMetadata(node, container) {
    if (typeSerializer) {
      let properties;
      if (shouldAddTypeMetadata(node)) {
        const typeProperty = factory2.createPropertyAssignment("type", factory2.createArrowFunction(
          /*modifiers*/
          void 0,
          /*typeParameters*/
          void 0,
          [],
          /*type*/
          void 0,
          factory2.createToken(39 /* EqualsGreaterThanToken */),
          typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)
        ));
        properties = append(properties, typeProperty);
      }
      if (shouldAddParamTypesMetadata(node)) {
        const paramTypeProperty = factory2.createPropertyAssignment("paramTypes", factory2.createArrowFunction(
          /*modifiers*/
          void 0,
          /*typeParameters*/
          void 0,
          [],
          /*type*/
          void 0,
          factory2.createToken(39 /* EqualsGreaterThanToken */),
          typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container)
        ));
        properties = append(properties, paramTypeProperty);
      }
      if (shouldAddReturnTypeMetadata(node)) {
        const returnTypeProperty = factory2.createPropertyAssignment("returnType", factory2.createArrowFunction(
          /*modifiers*/
          void 0,
          /*typeParameters*/
          void 0,
          [],
          /*type*/
          void 0,
          factory2.createToken(39 /* EqualsGreaterThanToken */),
          typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)
        ));
        properties = append(properties, returnTypeProperty);
      }
      if (properties) {
        const typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory2.createObjectLiteralExpression(
          properties,
          /*multiLine*/
          true
        ));
        return [factory2.createDecorator(typeInfoMetadata)];
      }
    }
  }
  function shouldAddTypeMetadata(node) {
    const kind = node.kind;
    return kind === 173 /* MethodDeclaration */ || kind === 176 /* GetAccessor */ || kind === 177 /* SetAccessor */ || kind === 171 /* PropertyDeclaration */;
  }
  function shouldAddReturnTypeMetadata(node) {
    return node.kind === 173 /* MethodDeclaration */;
  }
  function shouldAddParamTypesMetadata(node) {
    switch (node.kind) {
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
        return getFirstConstructorWithBody(node) !== void 0;
      case 173 /* MethodDeclaration */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        return true;
    }
    return false;
  }
  function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
    const name = member.name;
    if (isPrivateIdentifier(name)) {
      return factory2.createIdentifier("");
    } else if (isComputedPropertyName(name)) {
      return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? factory2.getGeneratedNameForNode(name) : name.expression;
    } else if (isIdentifier(name)) {
      return factory2.createStringLiteral(idText(name));
    } else {
      return factory2.cloneNode(name);
    }
  }
  function visitPropertyNameOfClassElement(member) {
    const name = member.name;
    if (isComputedPropertyName(name) && (!hasStaticModifier(member) && currentClassHasParameterProperties || hasDecorators(member) && legacyDecorators)) {
      const expression = visitNode(name.expression, visitor, isExpression);
      Debug.assert(expression);
      const innerExpression = skipPartiallyEmittedExpressions(expression);
      if (!isSimpleInlineableExpression(innerExpression)) {
        const generatedName = factory2.getGeneratedNameForNode(name);
        hoistVariableDeclaration(generatedName);
        return factory2.updateComputedPropertyName(name, factory2.createAssignment(generatedName, expression));
      }
    }
    return Debug.checkDefined(visitNode(name, visitor, isPropertyName));
  }
  function visitHeritageClause(node) {
    if (node.token === 119 /* ImplementsKeyword */) {
      return void 0;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitExpressionWithTypeArguments(node) {
    return factory2.updateExpressionWithTypeArguments(
      node,
      Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression)),
      /*typeArguments*/
      void 0
    );
  }
  function shouldEmitFunctionLikeDeclaration(node) {
    return !nodeIsMissing(node.body);
  }
  function visitPropertyDeclaration(node, parent2) {
    const isAmbient = node.flags & 16777216 /* Ambient */ || hasSyntacticModifier(node, 256 /* Abstract */);
    if (isAmbient && !(legacyDecorators && hasDecorators(node))) {
      return void 0;
    }
    let modifiers = isClassLike(parent2) ? !isAmbient ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent2);
    if (isAmbient) {
      return factory2.updatePropertyDeclaration(
        node,
        concatenate(modifiers, factory2.createModifiersFromModifierFlags(2 /* Ambient */)),
        Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)),
        /*questionOrExclamationToken*/
        void 0,
        /*type*/
        void 0,
        /*initializer*/
        void 0
      );
    }
    return factory2.updatePropertyDeclaration(
      node,
      modifiers,
      visitPropertyNameOfClassElement(node),
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    );
  }
  function visitConstructor(node) {
    if (!shouldEmitFunctionLikeDeclaration(node)) {
      return void 0;
    }
    return factory2.updateConstructorDeclaration(
      node,
      /*modifiers*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      transformConstructorBody(node.body, node)
    );
  }
  function transformConstructorBody(body, constructor) {
    const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p) => isParameterPropertyDeclaration(p, constructor));
    if (!some(parametersWithPropertyAssignments)) {
      return visitFunctionBody(body, visitor, context);
    }
    let statements = [];
    resumeLexicalEnvironment();
    const prologueStatementCount = factory2.copyPrologue(
      body.statements,
      statements,
      /*ensureUseStrict*/
      false,
      visitor
    );
    const superStatementIndex = findSuperStatementIndex(body.statements, prologueStatementCount);
    if (superStatementIndex >= 0) {
      addRange(
        statements,
        visitNodes2(body.statements, visitor, isStatement, prologueStatementCount, superStatementIndex + 1 - prologueStatementCount)
      );
    }
    const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment);
    if (superStatementIndex >= 0) {
      addRange(statements, parameterPropertyAssignments);
    } else {
      statements = [
        ...statements.slice(0, prologueStatementCount),
        ...parameterPropertyAssignments,
        ...statements.slice(prologueStatementCount)
      ];
    }
    const start2 = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount;
    addRange(statements, visitNodes2(body.statements, visitor, isStatement, start2));
    statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment());
    const block = factory2.createBlock(
      setTextRange(factory2.createNodeArray(statements), body.statements),
      /*multiLine*/
      true
    );
    setTextRange(
      block,
      /*location*/
      body
    );
    setOriginalNode(block, body);
    return block;
  }
  function transformParameterWithPropertyAssignment(node) {
    const name = node.name;
    if (!isIdentifier(name)) {
      return void 0;
    }
    const propertyName = setParent(setTextRange(factory2.cloneNode(name), name), name.parent);
    setEmitFlags(propertyName, 3072 /* NoComments */ | 96 /* NoSourceMap */);
    const localName = setParent(setTextRange(factory2.cloneNode(name), name), name.parent);
    setEmitFlags(localName, 3072 /* NoComments */);
    return startOnNewLine(
      removeAllComments(
        setTextRange(
          setOriginalNode(
            factory2.createExpressionStatement(
              factory2.createAssignment(
                setTextRange(
                  factory2.createPropertyAccessExpression(
                    factory2.createThis(),
                    propertyName
                  ),
                  node.name
                ),
                localName
              )
            ),
            node
          ),
          moveRangePos(node, -1)
        )
      )
    );
  }
  function visitMethodDeclaration(node, parent2) {
    if (!(node.transformFlags & 1 /* ContainsTypeScript */)) {
      return node;
    }
    if (!shouldEmitFunctionLikeDeclaration(node)) {
      return void 0;
    }
    let modifiers = isClassLike(parent2) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent2);
    return factory2.updateMethodDeclaration(
      node,
      modifiers,
      node.asteriskToken,
      visitPropertyNameOfClassElement(node),
      /*questionToken*/
      void 0,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      visitFunctionBody(node.body, visitor, context)
    );
  }
  function shouldEmitAccessorDeclaration(node) {
    return !(nodeIsMissing(node.body) && hasSyntacticModifier(node, 256 /* Abstract */));
  }
  function visitGetAccessor(node, parent2) {
    if (!(node.transformFlags & 1 /* ContainsTypeScript */)) {
      return node;
    }
    if (!shouldEmitAccessorDeclaration(node)) {
      return void 0;
    }
    let modifiers = isClassLike(parent2) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent2);
    return factory2.updateGetAccessorDeclaration(
      node,
      modifiers,
      visitPropertyNameOfClassElement(node),
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])
    );
  }
  function visitSetAccessor(node, parent2) {
    if (!(node.transformFlags & 1 /* ContainsTypeScript */)) {
      return node;
    }
    if (!shouldEmitAccessorDeclaration(node)) {
      return void 0;
    }
    let modifiers = isClassLike(parent2) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent2);
    return factory2.updateSetAccessorDeclaration(
      node,
      modifiers,
      visitPropertyNameOfClassElement(node),
      visitParameterList(node.parameters, visitor, context),
      visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])
    );
  }
  function visitFunctionDeclaration(node) {
    if (!shouldEmitFunctionLikeDeclaration(node)) {
      return factory2.createNotEmittedStatement(node);
    }
    const updated = factory2.updateFunctionDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])
    );
    if (isExportOfNamespace(node)) {
      const statements = [updated];
      addExportMemberAssignment(statements, node);
      return statements;
    }
    return updated;
  }
  function visitFunctionExpression(node) {
    if (!shouldEmitFunctionLikeDeclaration(node)) {
      return factory2.createOmittedExpression();
    }
    const updated = factory2.updateFunctionExpression(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])
    );
    return updated;
  }
  function visitArrowFunction(node) {
    const updated = factory2.updateArrowFunction(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      node.equalsGreaterThanToken,
      visitFunctionBody(node.body, visitor, context)
    );
    return updated;
  }
  function visitParameter(node) {
    if (parameterIsThisKeyword(node)) {
      return void 0;
    }
    const updated = factory2.updateParameterDeclaration(
      node,
      visitNodes2(node.modifiers, (node2) => isDecorator(node2) ? visitor(node2) : void 0, isModifierLike),
      node.dotDotDotToken,
      Debug.checkDefined(visitNode(node.name, visitor, isBindingName)),
      /*questionToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    );
    if (updated !== node) {
      setCommentRange(updated, node);
      setTextRange(updated, moveRangePastModifiers(node));
      setSourceMapRange(updated, moveRangePastModifiers(node));
      setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */);
    }
    return updated;
  }
  function visitVariableStatement(node) {
    if (isExportOfNamespace(node)) {
      const variables = getInitializedVariables(node.declarationList);
      if (variables.length === 0) {
        return void 0;
      }
      return setTextRange(
        factory2.createExpressionStatement(
          factory2.inlineExpressions(
            map(variables, transformInitializedVariable)
          )
        ),
        node
      );
    } else {
      return visitEachChild(node, visitor, context);
    }
  }
  function transformInitializedVariable(node) {
    const name = node.name;
    if (isBindingPattern(name)) {
      return flattenDestructuringAssignment(
        node,
        visitor,
        context,
        0 /* All */,
        /*needsValue*/
        false,
        createNamespaceExportExpression
      );
    } else {
      return setTextRange(
        factory2.createAssignment(
          getNamespaceMemberNameWithSourceMapsAndWithoutComments(name),
          Debug.checkDefined(visitNode(node.initializer, visitor, isExpression))
        ),
        /*location*/
        node
      );
    }
  }
  function visitVariableDeclaration(node) {
    const updated = factory2.updateVariableDeclaration(
      node,
      Debug.checkDefined(visitNode(node.name, visitor, isBindingName)),
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    );
    if (node.type) {
      setTypeNode(updated.name, node.type);
    }
    return updated;
  }
  function visitParenthesizedExpression(node) {
    const innerExpression = skipOuterExpressions(node.expression, ~6 /* Assertions */);
    if (isAssertionExpression(innerExpression)) {
      const expression = visitNode(node.expression, visitor, isExpression);
      Debug.assert(expression);
      return factory2.createPartiallyEmittedExpression(expression, node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitAssertionExpression(node) {
    const expression = visitNode(node.expression, visitor, isExpression);
    Debug.assert(expression);
    return factory2.createPartiallyEmittedExpression(expression, node);
  }
  function visitNonNullExpression(node) {
    const expression = visitNode(node.expression, visitor, isLeftHandSideExpression);
    Debug.assert(expression);
    return factory2.createPartiallyEmittedExpression(expression, node);
  }
  function visitSatisfiesExpression(node) {
    const expression = visitNode(node.expression, visitor, isExpression);
    Debug.assert(expression);
    return factory2.createPartiallyEmittedExpression(expression, node);
  }
  function visitCallExpression(node) {
    return factory2.updateCallExpression(
      node,
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      /*typeArguments*/
      void 0,
      visitNodes2(node.arguments, visitor, isExpression)
    );
  }
  function visitNewExpression(node) {
    return factory2.updateNewExpression(
      node,
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      /*typeArguments*/
      void 0,
      visitNodes2(node.arguments, visitor, isExpression)
    );
  }
  function visitTaggedTemplateExpression(node) {
    return factory2.updateTaggedTemplateExpression(
      node,
      Debug.checkDefined(visitNode(node.tag, visitor, isExpression)),
      /*typeArguments*/
      void 0,
      Debug.checkDefined(visitNode(node.template, visitor, isTemplateLiteral))
    );
  }
  function visitJsxSelfClosingElement(node) {
    return factory2.updateJsxSelfClosingElement(
      node,
      Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)),
      /*typeArguments*/
      void 0,
      Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes))
    );
  }
  function visitJsxJsxOpeningElement(node) {
    return factory2.updateJsxOpeningElement(
      node,
      Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)),
      /*typeArguments*/
      void 0,
      Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes))
    );
  }
  function shouldEmitEnumDeclaration(node) {
    return !isEnumConst(node) || shouldPreserveConstEnums(compilerOptions);
  }
  function visitEnumDeclaration(node) {
    if (!shouldEmitEnumDeclaration(node)) {
      return factory2.createNotEmittedStatement(node);
    }
    const statements = [];
    let emitFlags = 4 /* AdviseOnEmitNode */;
    const varAdded = addVarForEnumOrModuleDeclaration(statements, node);
    if (varAdded) {
      if (moduleKind !== 4 /* System */ || currentLexicalScope !== currentSourceFile) {
        emitFlags |= 1024 /* NoLeadingComments */;
      }
    }
    const parameterName = getNamespaceParameterName(node);
    const containerName = getNamespaceContainerName(node);
    const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName(
      currentNamespaceContainerName,
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    ) : factory2.getDeclarationName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    );
    let moduleArg = factory2.createLogicalOr(
      exportName,
      factory2.createAssignment(
        exportName,
        factory2.createObjectLiteralExpression()
      )
    );
    if (isExportOfNamespace(node)) {
      const localName = factory2.getLocalName(
        node,
        /*allowComments*/
        false,
        /*allowSourceMaps*/
        true
      );
      moduleArg = factory2.createAssignment(localName, moduleArg);
    }
    const enumStatement = factory2.createExpressionStatement(
      factory2.createCallExpression(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          /*asteriskToken*/
          void 0,
          /*name*/
          void 0,
          /*typeParameters*/
          void 0,
          [factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            parameterName
          )],
          /*type*/
          void 0,
          transformEnumBody(node, containerName)
        ),
        /*typeArguments*/
        void 0,
        [moduleArg]
      )
    );
    setOriginalNode(enumStatement, node);
    if (varAdded) {
      setSyntheticLeadingComments(enumStatement, void 0);
      setSyntheticTrailingComments(enumStatement, void 0);
    }
    setTextRange(enumStatement, node);
    addEmitFlags(enumStatement, emitFlags);
    statements.push(enumStatement);
    return statements;
  }
  function transformEnumBody(node, localName) {
    const savedCurrentNamespaceLocalName = currentNamespaceContainerName;
    currentNamespaceContainerName = localName;
    const statements = [];
    startLexicalEnvironment();
    const members = map(node.members, transformEnumMember);
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    addRange(statements, members);
    currentNamespaceContainerName = savedCurrentNamespaceLocalName;
    return factory2.createBlock(
      setTextRange(
        factory2.createNodeArray(statements),
        /*location*/
        node.members
      ),
      /*multiLine*/
      true
    );
  }
  function transformEnumMember(member) {
    const name = getExpressionForPropertyName(
      member,
      /*generateNameForComputedPropertyName*/
      false
    );
    const valueExpression = transformEnumMemberDeclarationValue(member);
    const innerAssignment = factory2.createAssignment(
      factory2.createElementAccessExpression(
        currentNamespaceContainerName,
        name
      ),
      valueExpression
    );
    const outerAssignment = valueExpression.kind === 11 /* StringLiteral */ ? innerAssignment : factory2.createAssignment(
      factory2.createElementAccessExpression(
        currentNamespaceContainerName,
        innerAssignment
      ),
      name
    );
    return setTextRange(
      factory2.createExpressionStatement(
        setTextRange(
          outerAssignment,
          member
        )
      ),
      member
    );
  }
  function transformEnumMemberDeclarationValue(member) {
    const value = resolver.getConstantValue(member);
    if (value !== void 0) {
      return typeof value === "string" ? factory2.createStringLiteral(value) : factory2.createNumericLiteral(value);
    } else {
      enableSubstitutionForNonQualifiedEnumMembers();
      if (member.initializer) {
        return Debug.checkDefined(visitNode(member.initializer, visitor, isExpression));
      } else {
        return factory2.createVoidZero();
      }
    }
  }
  function shouldEmitModuleDeclaration(nodeIn) {
    const node = getParseTreeNode(nodeIn, isModuleDeclaration);
    if (!node) {
      return true;
    }
    return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions));
  }
  function recordEmittedDeclarationInScope(node) {
    if (!currentScopeFirstDeclarationsOfName) {
      currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map();
    }
    const name = declaredNameInScope(node);
    if (!currentScopeFirstDeclarationsOfName.has(name)) {
      currentScopeFirstDeclarationsOfName.set(name, node);
    }
  }
  function isFirstEmittedDeclarationInScope(node) {
    if (currentScopeFirstDeclarationsOfName) {
      const name = declaredNameInScope(node);
      return currentScopeFirstDeclarationsOfName.get(name) === node;
    }
    return true;
  }
  function declaredNameInScope(node) {
    Debug.assertNode(node.name, isIdentifier);
    return node.name.escapedText;
  }
  function addVarForEnumOrModuleDeclaration(statements, node) {
    const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    ));
    const varFlags = currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */;
    const statement = factory2.createVariableStatement(
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      factory2.createVariableDeclarationList([varDecl], varFlags)
    );
    setOriginalNode(varDecl, node);
    setSyntheticLeadingComments(varDecl, void 0);
    setSyntheticTrailingComments(varDecl, void 0);
    setOriginalNode(statement, node);
    recordEmittedDeclarationInScope(node);
    if (isFirstEmittedDeclarationInScope(node)) {
      if (node.kind === 265 /* EnumDeclaration */) {
        setSourceMapRange(statement.declarationList, node);
      } else {
        setSourceMapRange(statement, node);
      }
      setCommentRange(statement, node);
      addEmitFlags(statement, 2048 /* NoTrailingComments */);
      statements.push(statement);
      return true;
    }
    return false;
  }
  function visitModuleDeclaration(node) {
    if (!shouldEmitModuleDeclaration(node)) {
      return factory2.createNotEmittedStatement(node);
    }
    Debug.assertNode(node.name, isIdentifier, "A TypeScript namespace should have an Identifier name.");
    enableSubstitutionForNamespaceExports();
    const statements = [];
    let emitFlags = 4 /* AdviseOnEmitNode */;
    const varAdded = addVarForEnumOrModuleDeclaration(statements, node);
    if (varAdded) {
      if (moduleKind !== 4 /* System */ || currentLexicalScope !== currentSourceFile) {
        emitFlags |= 1024 /* NoLeadingComments */;
      }
    }
    const parameterName = getNamespaceParameterName(node);
    const containerName = getNamespaceContainerName(node);
    const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName(
      currentNamespaceContainerName,
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    ) : factory2.getDeclarationName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    );
    let moduleArg = factory2.createLogicalOr(
      exportName,
      factory2.createAssignment(
        exportName,
        factory2.createObjectLiteralExpression()
      )
    );
    if (isExportOfNamespace(node)) {
      const localName = factory2.getLocalName(
        node,
        /*allowComments*/
        false,
        /*allowSourceMaps*/
        true
      );
      moduleArg = factory2.createAssignment(localName, moduleArg);
    }
    const moduleStatement = factory2.createExpressionStatement(
      factory2.createCallExpression(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          /*asteriskToken*/
          void 0,
          /*name*/
          void 0,
          /*typeParameters*/
          void 0,
          [factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            parameterName
          )],
          /*type*/
          void 0,
          transformModuleBody(node, containerName)
        ),
        /*typeArguments*/
        void 0,
        [moduleArg]
      )
    );
    setOriginalNode(moduleStatement, node);
    if (varAdded) {
      setSyntheticLeadingComments(moduleStatement, void 0);
      setSyntheticTrailingComments(moduleStatement, void 0);
    }
    setTextRange(moduleStatement, node);
    addEmitFlags(moduleStatement, emitFlags);
    statements.push(moduleStatement);
    return statements;
  }
  function transformModuleBody(node, namespaceLocalName) {
    const savedCurrentNamespaceContainerName = currentNamespaceContainerName;
    const savedCurrentNamespace = currentNamespace;
    const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
    currentNamespaceContainerName = namespaceLocalName;
    currentNamespace = node;
    currentScopeFirstDeclarationsOfName = void 0;
    const statements = [];
    startLexicalEnvironment();
    let statementsLocation;
    let blockLocation;
    if (node.body) {
      if (node.body.kind === 267 /* ModuleBlock */) {
        saveStateAndInvoke(node.body, (body) => addRange(statements, visitNodes2(body.statements, namespaceElementVisitor, isStatement)));
        statementsLocation = node.body.statements;
        blockLocation = node.body;
      } else {
        const result = visitModuleDeclaration(node.body);
        if (result) {
          if (isArray(result)) {
            addRange(statements, result);
          } else {
            statements.push(result);
          }
        }
        const moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
        statementsLocation = moveRangePos(moduleBlock.statements, -1);
      }
    }
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    currentNamespaceContainerName = savedCurrentNamespaceContainerName;
    currentNamespace = savedCurrentNamespace;
    currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
    const block = factory2.createBlock(
      setTextRange(
        factory2.createNodeArray(statements),
        /*location*/
        statementsLocation
      ),
      /*multiLine*/
      true
    );
    setTextRange(block, blockLocation);
    if (!node.body || node.body.kind !== 267 /* ModuleBlock */) {
      setEmitFlags(block, getEmitFlags(block) | 3072 /* NoComments */);
    }
    return block;
  }
  function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
    if (moduleDeclaration.body.kind === 266 /* ModuleDeclaration */) {
      const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
      return recursiveInnerModule || moduleDeclaration.body;
    }
  }
  function visitImportDeclaration(node) {
    if (!node.importClause) {
      return node;
    }
    if (node.importClause.isTypeOnly) {
      return void 0;
    }
    const importClause = visitNode(node.importClause, visitImportClause, isImportClause);
    return importClause || compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */ ? factory2.updateImportDeclaration(
      node,
      /*modifiers*/
      void 0,
      importClause,
      node.moduleSpecifier,
      node.assertClause
    ) : void 0;
  }
  function visitImportClause(node) {
    Debug.assert(!node.isTypeOnly);
    const name = shouldEmitAliasDeclaration(node) ? node.name : void 0;
    const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings);
    return name || namedBindings ? factory2.updateImportClause(
      node,
      /*isTypeOnly*/
      false,
      name,
      namedBindings
    ) : void 0;
  }
  function visitNamedImportBindings(node) {
    if (node.kind === 273 /* NamespaceImport */) {
      return shouldEmitAliasDeclaration(node) ? node : void 0;
    } else {
      const allowEmpty = compilerOptions.verbatimModuleSyntax || compilerOptions.preserveValueImports && (compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */);
      const elements = visitNodes2(node.elements, visitImportSpecifier, isImportSpecifier);
      return allowEmpty || some(elements) ? factory2.updateNamedImports(node, elements) : void 0;
    }
  }
  function visitImportSpecifier(node) {
    return !node.isTypeOnly && shouldEmitAliasDeclaration(node) ? node : void 0;
  }
  function visitExportAssignment(node) {
    return compilerOptions.verbatimModuleSyntax || resolver.isValueAliasDeclaration(node) ? visitEachChild(node, visitor, context) : void 0;
  }
  function visitExportDeclaration(node) {
    if (node.isTypeOnly) {
      return void 0;
    }
    if (!node.exportClause || isNamespaceExport(node.exportClause)) {
      return node;
    }
    const allowEmpty = compilerOptions.verbatimModuleSyntax || !!node.moduleSpecifier && (compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */);
    const exportClause = visitNode(
      node.exportClause,
      (bindings) => visitNamedExportBindings(bindings, allowEmpty),
      isNamedExportBindings
    );
    return exportClause ? factory2.updateExportDeclaration(
      node,
      /*modifiers*/
      void 0,
      node.isTypeOnly,
      exportClause,
      node.moduleSpecifier,
      node.assertClause
    ) : void 0;
  }
  function visitNamedExports(node, allowEmpty) {
    const elements = visitNodes2(node.elements, visitExportSpecifier, isExportSpecifier);
    return allowEmpty || some(elements) ? factory2.updateNamedExports(node, elements) : void 0;
  }
  function visitNamespaceExports(node) {
    return factory2.updateNamespaceExport(node, Debug.checkDefined(visitNode(node.name, visitor, isIdentifier)));
  }
  function visitNamedExportBindings(node, allowEmpty) {
    return isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node, allowEmpty);
  }
  function visitExportSpecifier(node) {
    return !node.isTypeOnly && (compilerOptions.verbatimModuleSyntax || resolver.isValueAliasDeclaration(node)) ? node : void 0;
  }
  function shouldEmitImportEqualsDeclaration(node) {
    return shouldEmitAliasDeclaration(node) || !isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node);
  }
  function visitImportEqualsDeclaration(node) {
    if (node.isTypeOnly) {
      return void 0;
    }
    if (isExternalModuleImportEqualsDeclaration(node)) {
      const isReferenced = shouldEmitAliasDeclaration(node);
      if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
        return setOriginalNode(
          setTextRange(
            factory2.createImportDeclaration(
              /*modifiers*/
              void 0,
              /*importClause*/
              void 0,
              node.moduleReference.expression,
              /*assertClause*/
              void 0
            ),
            node
          ),
          node
        );
      }
      return isReferenced ? visitEachChild(node, visitor, context) : void 0;
    }
    if (!shouldEmitImportEqualsDeclaration(node)) {
      return void 0;
    }
    const moduleReference = createExpressionFromEntityName(factory2, node.moduleReference);
    setEmitFlags(moduleReference, 3072 /* NoComments */ | 4096 /* NoNestedComments */);
    if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
      return setOriginalNode(
        setTextRange(
          factory2.createVariableStatement(
            visitNodes2(node.modifiers, modifierVisitor, isModifier),
            factory2.createVariableDeclarationList([
              setOriginalNode(
                factory2.createVariableDeclaration(
                  node.name,
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  moduleReference
                ),
                node
              )
            ])
          ),
          node
        ),
        node
      );
    } else {
      return setOriginalNode(
        createNamespaceExport(
          node.name,
          moduleReference,
          node
        ),
        node
      );
    }
  }
  function isExportOfNamespace(node) {
    return currentNamespace !== void 0 && hasSyntacticModifier(node, 1 /* Export */);
  }
  function isExternalModuleExport(node) {
    return currentNamespace === void 0 && hasSyntacticModifier(node, 1 /* Export */);
  }
  function isNamedExternalModuleExport(node) {
    return isExternalModuleExport(node) && !hasSyntacticModifier(node, 1024 /* Default */);
  }
  function isDefaultExternalModuleExport(node) {
    return isExternalModuleExport(node) && hasSyntacticModifier(node, 1024 /* Default */);
  }
  function createExportMemberAssignmentStatement(node) {
    const expression = factory2.createAssignment(
      factory2.getExternalModuleOrNamespaceExportName(
        currentNamespaceContainerName,
        node,
        /*allowComments*/
        false,
        /*allowSourceMaps*/
        true
      ),
      factory2.getLocalName(node)
    );
    setSourceMapRange(expression, createRange(node.name ? node.name.pos : node.pos, node.end));
    const statement = factory2.createExpressionStatement(expression);
    setSourceMapRange(statement, createRange(-1, node.end));
    return statement;
  }
  function addExportMemberAssignment(statements, node) {
    statements.push(createExportMemberAssignmentStatement(node));
  }
  function createNamespaceExport(exportName, exportValue, location) {
    return setTextRange(
      factory2.createExpressionStatement(
        factory2.createAssignment(
          factory2.getNamespaceMemberName(
            currentNamespaceContainerName,
            exportName,
            /*allowComments*/
            false,
            /*allowSourceMaps*/
            true
          ),
          exportValue
        )
      ),
      location
    );
  }
  function createNamespaceExportExpression(exportName, exportValue, location) {
    return setTextRange(factory2.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
  }
  function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
    return factory2.getNamespaceMemberName(
      currentNamespaceContainerName,
      name,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    );
  }
  function getNamespaceParameterName(node) {
    const name = factory2.getGeneratedNameForNode(node);
    setSourceMapRange(name, node.name);
    return name;
  }
  function getNamespaceContainerName(node) {
    return factory2.getGeneratedNameForNode(node);
  }
  function enableSubstitutionForNonQualifiedEnumMembers() {
    if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
      enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
      context.enableSubstitution(80 /* Identifier */);
    }
  }
  function enableSubstitutionForNamespaceExports() {
    if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
      enabledSubstitutions |= 2 /* NamespaceExports */;
      context.enableSubstitution(80 /* Identifier */);
      context.enableSubstitution(303 /* ShorthandPropertyAssignment */);
      context.enableEmitNotification(266 /* ModuleDeclaration */);
    }
  }
  function isTransformedModuleDeclaration(node) {
    return getOriginalNode(node).kind === 266 /* ModuleDeclaration */;
  }
  function isTransformedEnumDeclaration(node) {
    return getOriginalNode(node).kind === 265 /* EnumDeclaration */;
  }
  function onEmitNode(hint, node, emitCallback) {
    const savedApplicableSubstitutions = applicableSubstitutions;
    const savedCurrentSourceFile = currentSourceFile;
    if (isSourceFile(node)) {
      currentSourceFile = node;
    }
    if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
      applicableSubstitutions |= 2 /* NamespaceExports */;
    }
    if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
      applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
    }
    previousOnEmitNode(hint, node, emitCallback);
    applicableSubstitutions = savedApplicableSubstitutions;
    currentSourceFile = savedCurrentSourceFile;
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    } else if (isShorthandPropertyAssignment(node)) {
      return substituteShorthandPropertyAssignment(node);
    }
    return node;
  }
  function substituteShorthandPropertyAssignment(node) {
    if (enabledSubstitutions & 2 /* NamespaceExports */) {
      const name = node.name;
      const exportedName = trySubstituteNamespaceExportedName(name);
      if (exportedName) {
        if (node.objectAssignmentInitializer) {
          const initializer = factory2.createAssignment(exportedName, node.objectAssignmentInitializer);
          return setTextRange(factory2.createPropertyAssignment(name, initializer), node);
        }
        return setTextRange(factory2.createPropertyAssignment(name, exportedName), node);
      }
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return substituteExpressionIdentifier(node);
      case 210 /* PropertyAccessExpression */:
        return substitutePropertyAccessExpression(node);
      case 211 /* ElementAccessExpression */:
        return substituteElementAccessExpression(node);
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    return trySubstituteNamespaceExportedName(node) || node;
  }
  function trySubstituteNamespaceExportedName(node) {
    if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) {
      const container = resolver.getReferencedExportContainer(
        node,
        /*prefixLocals*/
        false
      );
      if (container && container.kind !== 311 /* SourceFile */) {
        const substitute = applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 266 /* ModuleDeclaration */ || applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 265 /* EnumDeclaration */;
        if (substitute) {
          return setTextRange(
            factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(container), node),
            /*location*/
            node
          );
        }
      }
    }
    return void 0;
  }
  function substitutePropertyAccessExpression(node) {
    return substituteConstantValue(node);
  }
  function substituteElementAccessExpression(node) {
    return substituteConstantValue(node);
  }
  function safeMultiLineComment(value) {
    return value.replace(/\*\//g, "*_/");
  }
  function substituteConstantValue(node) {
    const constantValue = tryGetConstEnumValue(node);
    if (constantValue !== void 0) {
      setConstantValue(node, constantValue);
      const substitute = typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : factory2.createNumericLiteral(constantValue);
      if (!compilerOptions.removeComments) {
        const originalNode = getOriginalNode(node, isAccessExpression);
        addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, ` ${safeMultiLineComment(getTextOfNode(originalNode))} `);
      }
      return substitute;
    }
    return node;
  }
  function tryGetConstEnumValue(node) {
    if (getIsolatedModules(compilerOptions)) {
      return void 0;
    }
    return isPropertyAccessExpression(node) || isElementAccessExpression(node) ? resolver.getConstantValue(node) : void 0;
  }
  function shouldEmitAliasDeclaration(node) {
    return compilerOptions.verbatimModuleSyntax || isInJSFile(node) || (compilerOptions.preserveValueImports ? resolver.isValueAliasDeclaration(node) : resolver.isReferencedAliasDeclaration(node));
  }
}

// src/compiler/transformers/classFields.ts
function transformClassFields(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    hoistVariableDeclaration,
    endLexicalEnvironment,
    startLexicalEnvironment,
    resumeLexicalEnvironment,
    addBlockScopedVariable
  } = context;
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
  const legacyDecorators = !!compilerOptions.experimentalDecorators;
  const shouldTransformInitializersUsingSet = !useDefineForClassFields;
  const shouldTransformInitializersUsingDefine = useDefineForClassFields && languageVersion < 9 /* ES2022 */;
  const shouldTransformInitializers = shouldTransformInitializersUsingSet || shouldTransformInitializersUsingDefine;
  const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 9 /* ES2022 */;
  const shouldTransformAutoAccessors = languageVersion < 99 /* ESNext */ ? -1 /* True */ : !useDefineForClassFields ? 3 /* Maybe */ : 0 /* False */;
  const shouldTransformThisInStaticInitializers = languageVersion < 9 /* ES2022 */;
  const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= 2 /* ES2015 */;
  const shouldTransformAnything = shouldTransformInitializers || shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformAutoAccessors === -1 /* True */;
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onSubstituteNode = onSubstituteNode;
  const previousOnEmitNode = context.onEmitNode;
  context.onEmitNode = onEmitNode;
  let shouldTransformPrivateStaticElementsInFile = false;
  let enabledSubstitutions;
  let classAliases;
  let pendingExpressions;
  let pendingStatements;
  let lexicalEnvironment;
  const lexicalEnvironmentMap = /* @__PURE__ */ new Map();
  let currentClassContainer;
  let currentStaticPropertyDeclarationOrStaticBlock;
  let shouldSubstituteThisWithClassThis = false;
  let previousShouldSubstituteThisWithClassThis = false;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    lexicalEnvironment = void 0;
    shouldTransformPrivateStaticElementsInFile = !!(getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */);
    if (!shouldTransformAnything && !shouldTransformPrivateStaticElementsInFile) {
      return node;
    }
    const visited = visitEachChild(node, visitor, context);
    addEmitHelpers(visited, context.readEmitHelpers());
    return visited;
  }
  function modifierVisitor(node) {
    switch (node.kind) {
      case 129 /* AccessorKeyword */:
        return shouldTransformAutoAccessorsInCurrentClass() ? void 0 : node;
      default:
        return tryCast(node, isModifier);
    }
  }
  function visitor(node) {
    if (!(node.transformFlags & 16777216 /* ContainsClassFields */) && !(node.transformFlags & 134234112 /* ContainsLexicalThisOrSuper */)) {
      return node;
    }
    switch (node.kind) {
      case 129 /* AccessorKeyword */:
        return Debug.fail("Use `modifierVisitor` instead.");
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 230 /* ClassExpression */:
        return visitClassExpression(
          node,
          /*referencedName*/
          void 0
        );
      case 174 /* ClassStaticBlockDeclaration */:
      case 171 /* PropertyDeclaration */:
        return Debug.fail("Use `classElementVisitor` instead.");
      case 302 /* PropertyAssignment */:
        return visitPropertyAssignment(node);
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 259 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 168 /* Parameter */:
        return visitParameterDeclaration(node);
      case 207 /* BindingElement */:
        return visitBindingElement(node);
      case 276 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 81 /* PrivateIdentifier */:
        return visitPrivateIdentifier(node);
      case 210 /* PropertyAccessExpression */:
        return visitPropertyAccessExpression(node);
      case 211 /* ElementAccessExpression */:
        return visitElementAccessExpression(node);
      case 223 /* PrefixUnaryExpression */:
      case 224 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          false
        );
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          false
        );
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          false,
          /*referencedName*/
          void 0
        );
      case 212 /* CallExpression */:
        return visitCallExpression(node);
      case 243 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 214 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 247 /* ForStatement */:
        return visitForStatement(node);
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
      case 175 /* Constructor */:
      case 173 /* MethodDeclaration */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */: {
        return setCurrentStaticPropertyDeclarationOrStaticBlockAnd(
          /*current*/
          void 0,
          fallbackVisitor,
          node
        );
      }
      default:
        return fallbackVisitor(node);
    }
  }
  function fallbackVisitor(node) {
    return visitEachChild(node, visitor, context);
  }
  function namedEvaluationVisitor(node, referencedName) {
    switch (node.kind) {
      case 359 /* PartiallyEmittedExpression */:
        return visitPartiallyEmittedExpression(
          node,
          /*discarded*/
          false,
          referencedName
        );
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          false,
          referencedName
        );
      case 230 /* ClassExpression */:
        return visitClassExpression(node, referencedName);
      default:
        return visitor(node);
    }
  }
  function discardedValueVisitor(node) {
    switch (node.kind) {
      case 223 /* PrefixUnaryExpression */:
      case 224 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          true
        );
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          true
        );
      case 360 /* CommaListExpression */:
        return visitCommaListExpression(
          node,
          /*discarded*/
          true
        );
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          true,
          /*referencedName*/
          void 0
        );
      default:
        return visitor(node);
    }
  }
  function heritageClauseVisitor(node) {
    switch (node.kind) {
      case 297 /* HeritageClause */:
        return visitEachChild(node, heritageClauseVisitor, context);
      case 232 /* ExpressionWithTypeArguments */:
        return visitExpressionWithTypeArgumentsInHeritageClause(node);
      default:
        return visitor(node);
    }
  }
  function assignmentTargetVisitor(node) {
    switch (node.kind) {
      case 209 /* ObjectLiteralExpression */:
      case 208 /* ArrayLiteralExpression */:
        return visitAssignmentPattern(node);
      default:
        return visitor(node);
    }
  }
  function classElementVisitor(node) {
    switch (node.kind) {
      case 175 /* Constructor */:
        return visitConstructorDeclaration(node);
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
      case 173 /* MethodDeclaration */:
        return setCurrentStaticPropertyDeclarationOrStaticBlockAnd(
          /*current*/
          void 0,
          visitMethodOrAccessorDeclaration,
          node
        );
      case 171 /* PropertyDeclaration */:
        return setCurrentStaticPropertyDeclarationOrStaticBlockAnd(
          /*current*/
          void 0,
          visitPropertyDeclaration,
          node
        );
      case 174 /* ClassStaticBlockDeclaration */:
        return visitClassStaticBlockDeclaration(node);
      case 166 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      case 239 /* SemicolonClassElement */:
        return node;
      default:
        return isModifierLike(node) ? modifierVisitor(node) : visitor(node);
    }
  }
  function propertyNameVisitor(node) {
    switch (node.kind) {
      case 166 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      default:
        return visitor(node);
    }
  }
  function accessorFieldResultVisitor(node) {
    switch (node.kind) {
      case 171 /* PropertyDeclaration */:
        return transformFieldInitializer(node);
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        return classElementVisitor(node);
      default:
        Debug.assertMissingNode(node, "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration");
        break;
    }
  }
  function visitPrivateIdentifier(node) {
    if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
      return node;
    }
    if (isStatement(node.parent)) {
      return node;
    }
    return setOriginalNode(factory2.createIdentifier(""), node);
  }
  function transformPrivateIdentifierInInExpression(node) {
    const info = accessPrivateIdentifier2(node.left);
    if (info) {
      const receiver = visitNode(node.right, visitor, isExpression);
      return setOriginalNode(
        emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver),
        node
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitPropertyAssignment(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const { referencedName, name } = visitReferencedPropertyName(node.name);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, referencedName), isExpression);
      return factory2.updatePropertyAssignment(node, name, initializer);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitVariableStatement(node) {
    const savedPendingStatements = pendingStatements;
    pendingStatements = [];
    const visitedNode = visitEachChild(node, visitor, context);
    const statement = some(pendingStatements) ? [visitedNode, ...pendingStatements] : visitedNode;
    pendingStatements = savedPendingStatements;
    return statement;
  }
  function getAssignedNameOfIdentifier(name, initializer) {
    const originalClass = getOriginalNode(initializer, isClassLike);
    return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, 1024 /* Default */) ? factory2.createStringLiteral("default") : factory2.createStringLiteralFromNode(name);
  }
  function visitVariableDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer);
      const name = visitNode(node.name, visitor, isBindingName);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateVariableDeclaration(
        node,
        name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        initializer
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitParameterDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer);
      const name = visitNode(node.name, visitor, isBindingName);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateParameterDeclaration(
        node,
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        /*type*/
        void 0,
        initializer
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitBindingElement(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer);
      const propertyName = visitNode(node.propertyName, visitor, isPropertyName);
      const name = visitNode(node.name, visitor, isBindingName);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateBindingElement(
        node,
        /*dotDotDotToken*/
        void 0,
        propertyName,
        name,
        initializer
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitExportAssignment(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = factory2.createStringLiteral(node.isExportEquals ? "" : "default");
      const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
      const expression = visitNode(node.expression, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateExportAssignment(node, modifiers, expression);
    }
    return visitEachChild(node, visitor, context);
  }
  function injectPendingExpressions(expression) {
    if (some(pendingExpressions)) {
      if (isParenthesizedExpression(expression)) {
        pendingExpressions.push(expression.expression);
        expression = factory2.updateParenthesizedExpression(expression, factory2.inlineExpressions(pendingExpressions));
      } else {
        pendingExpressions.push(expression);
        expression = factory2.inlineExpressions(pendingExpressions);
      }
      pendingExpressions = void 0;
    }
    return expression;
  }
  function visitComputedPropertyName(node) {
    const expression = visitNode(node.expression, visitor, isExpression);
    return factory2.updateComputedPropertyName(node, injectPendingExpressions(expression));
  }
  function visitConstructorDeclaration(node) {
    if (currentClassContainer) {
      return transformConstructor(node, currentClassContainer);
    }
    return fallbackVisitor(node);
  }
  function shouldTransformClassElementToWeakMap(node) {
    if (shouldTransformPrivateElementsOrClassStaticBlocks)
      return true;
    if (hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */)
      return true;
    return false;
  }
  function visitMethodOrAccessorDeclaration(node) {
    Debug.assert(!hasDecorators(node));
    if (!isPrivateIdentifierClassElementDeclaration(node) || !shouldTransformClassElementToWeakMap(node)) {
      return visitEachChild(node, classElementVisitor, context);
    }
    const info = accessPrivateIdentifier2(node.name);
    Debug.assert(info, "Undeclared private name for property declaration.");
    if (!info.isValid) {
      return node;
    }
    const functionName = getHoistedFunctionName(node);
    if (functionName) {
      getPendingExpressions().push(
        factory2.createAssignment(
          functionName,
          factory2.createFunctionExpression(
            filter(node.modifiers, (m) => isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)),
            node.asteriskToken,
            functionName,
            /*typeParameters*/
            void 0,
            visitParameterList(node.parameters, visitor, context),
            /*type*/
            void 0,
            visitFunctionBody(node.body, visitor, context)
          )
        )
      );
    }
    return void 0;
  }
  function setCurrentStaticPropertyDeclarationOrStaticBlockAnd(current, visitor2, arg) {
    const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
    currentStaticPropertyDeclarationOrStaticBlock = current;
    const result = visitor2(arg);
    currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
    return result;
  }
  function getHoistedFunctionName(node) {
    Debug.assert(isPrivateIdentifier(node.name));
    const info = accessPrivateIdentifier2(node.name);
    Debug.assert(info, "Undeclared private name for property declaration.");
    if (info.kind === "m" /* Method */) {
      return info.methodName;
    }
    if (info.kind === "a" /* Accessor */) {
      if (isGetAccessor(node)) {
        return info.getterName;
      }
      if (isSetAccessor(node)) {
        return info.setterName;
      }
    }
  }
  function transformAutoAccessor(node) {
    const commentRange = getCommentRange(node);
    const sourceMapRange = getSourceMapRange(node);
    const name = node.name;
    let getterName = name;
    let setterName = name;
    if (isComputedPropertyName(name) && !isSimpleInlineableExpression(name.expression)) {
      const cacheAssignment = findComputedPropertyNameCacheAssignment(name);
      if (cacheAssignment) {
        getterName = factory2.updateComputedPropertyName(name, visitNode(name.expression, visitor, isExpression));
        setterName = factory2.updateComputedPropertyName(name, cacheAssignment.left);
      } else {
        const temp = factory2.createTempVariable(hoistVariableDeclaration);
        setSourceMapRange(temp, name.expression);
        const expression = visitNode(name.expression, visitor, isExpression);
        const assignment = factory2.createAssignment(temp, expression);
        setSourceMapRange(assignment, name.expression);
        getterName = factory2.updateComputedPropertyName(name, assignment);
        setterName = factory2.updateComputedPropertyName(name, temp);
      }
    }
    const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
    const backingField = createAccessorPropertyBackingField(factory2, node, modifiers, node.initializer);
    setOriginalNode(backingField, node);
    setEmitFlags(backingField, 3072 /* NoComments */);
    setSourceMapRange(backingField, sourceMapRange);
    const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName);
    setOriginalNode(getter, node);
    setCommentRange(getter, commentRange);
    setSourceMapRange(getter, sourceMapRange);
    const setter = createAccessorPropertySetRedirector(factory2, node, modifiers, setterName);
    setOriginalNode(setter, node);
    setEmitFlags(setter, 3072 /* NoComments */);
    setSourceMapRange(setter, sourceMapRange);
    return visitArray([backingField, getter, setter], accessorFieldResultVisitor, isClassElement);
  }
  function transformPrivateFieldInitializer(node) {
    if (shouldTransformClassElementToWeakMap(node)) {
      const info = accessPrivateIdentifier2(node.name);
      Debug.assert(info, "Undeclared private name for property declaration.");
      if (!info.isValid) {
        return node;
      }
      if (info.isStatic && !shouldTransformPrivateElementsOrClassStaticBlocks) {
        const statement = transformPropertyOrClassStaticBlock(node, factory2.createThis());
        if (statement) {
          return factory2.createClassStaticBlockDeclaration(factory2.createBlock(
            [statement],
            /*multiLine*/
            true
          ));
        }
      }
      return void 0;
    }
    if (shouldTransformInitializersUsingSet && !isStatic(node) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */) {
      return factory2.updatePropertyDeclaration(
        node,
        visitNodes2(node.modifiers, visitor, isModifierLike),
        node.name,
        /*questionOrExclamationToken*/
        void 0,
        /*type*/
        void 0,
        /*initializer*/
        void 0
      );
    }
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const { referencedName, name } = visitReferencedPropertyName(node.name);
      return factory2.updatePropertyDeclaration(
        node,
        visitNodes2(node.modifiers, modifierVisitor, isModifier),
        name,
        /*questionOrExclamationToken*/
        void 0,
        /*type*/
        void 0,
        visitNode(node.initializer, (child) => namedEvaluationVisitor(child, referencedName), isExpression)
      );
    }
    return factory2.updatePropertyDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      visitNode(node.name, propertyNameVisitor, isPropertyName),
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    );
  }
  function transformPublicFieldInitializer(node) {
    if (shouldTransformInitializers && !isAutoAccessorPropertyDeclaration(node)) {
      const expr = getPropertyNameExpressionIfNeeded(
        node.name,
        /*shouldHoist*/
        !!node.initializer || useDefineForClassFields,
        /*captureReferencedName*/
        isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)
      );
      if (expr) {
        getPendingExpressions().push(...flattenCommaList(expr));
      }
      if (isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks) {
        const initializerStatement = transformPropertyOrClassStaticBlock(node, factory2.createThis());
        if (initializerStatement) {
          const staticBlock = factory2.createClassStaticBlockDeclaration(
            factory2.createBlock([initializerStatement])
          );
          setOriginalNode(staticBlock, node);
          setCommentRange(staticBlock, node);
          setCommentRange(initializerStatement, { pos: -1, end: -1 });
          setSyntheticLeadingComments(initializerStatement, void 0);
          setSyntheticTrailingComments(initializerStatement, void 0);
          return staticBlock;
        }
      }
      return void 0;
    }
    return factory2.updatePropertyDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      visitNode(node.name, propertyNameVisitor, isPropertyName),
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    );
  }
  function transformFieldInitializer(node) {
    Debug.assert(!hasDecorators(node), "Decorators should already have been transformed and elided.");
    return isPrivateIdentifierClassElementDeclaration(node) ? transformPrivateFieldInitializer(node) : transformPublicFieldInitializer(node);
  }
  function shouldTransformAutoAccessorsInCurrentClass() {
    return shouldTransformAutoAccessors === -1 /* True */ || shouldTransformAutoAccessors === 3 /* Maybe */ && !!(lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && !!(lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */);
  }
  function visitPropertyDeclaration(node) {
    if (isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */)) {
      return transformAutoAccessor(node);
    }
    return transformFieldInitializer(node);
  }
  function createPrivateIdentifierAccess(info, receiver) {
    return createPrivateIdentifierAccessHelper(info, visitNode(receiver, visitor, isExpression));
  }
  function createPrivateIdentifierAccessHelper(info, receiver) {
    setCommentRange(receiver, moveRangePos(receiver, -1));
    switch (info.kind) {
      case "a" /* Accessor */:
        return emitHelpers().createClassPrivateFieldGetHelper(
          receiver,
          info.brandCheckIdentifier,
          info.kind,
          info.getterName
        );
      case "m" /* Method */:
        return emitHelpers().createClassPrivateFieldGetHelper(
          receiver,
          info.brandCheckIdentifier,
          info.kind,
          info.methodName
        );
      case "f" /* Field */:
        return emitHelpers().createClassPrivateFieldGetHelper(
          receiver,
          info.brandCheckIdentifier,
          info.kind,
          info.isStatic ? info.variableName : void 0
        );
      case "untransformed":
        return Debug.fail("Access helpers should not be created for untransformed private elements");
      default:
        Debug.assertNever(info, "Unknown private element type");
    }
  }
  function visitPropertyAccessExpression(node) {
    if (isPrivateIdentifier(node.name)) {
      const privateIdentifierInfo = accessPrivateIdentifier2(node.name);
      if (privateIdentifierInfo) {
        return setTextRange(
          setOriginalNode(
            createPrivateIdentifierAccess(privateIdentifierInfo, node.expression),
            node
          ),
          node
        );
      }
    }
    if (shouldTransformSuperInStaticInitializers && isSuperProperty(node) && isIdentifier(node.name) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
      const { classConstructor, superClassReference, facts } = lexicalEnvironment.data;
      if (facts & 1 /* ClassWasDecorated */) {
        return visitInvalidSuperProperty(node);
      }
      if (classConstructor && superClassReference) {
        const superProperty = factory2.createReflectGetCall(
          superClassReference,
          factory2.createStringLiteralFromNode(node.name),
          classConstructor
        );
        setOriginalNode(superProperty, node.expression);
        setTextRange(superProperty, node.expression);
        return superProperty;
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitElementAccessExpression(node) {
    if (shouldTransformSuperInStaticInitializers && isSuperProperty(node) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
      const { classConstructor, superClassReference, facts } = lexicalEnvironment.data;
      if (facts & 1 /* ClassWasDecorated */) {
        return visitInvalidSuperProperty(node);
      }
      if (classConstructor && superClassReference) {
        const superProperty = factory2.createReflectGetCall(
          superClassReference,
          visitNode(node.argumentExpression, visitor, isExpression),
          classConstructor
        );
        setOriginalNode(superProperty, node.expression);
        setTextRange(superProperty, node.expression);
        return superProperty;
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitPreOrPostfixUnaryExpression(node, discarded) {
    if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
      const operand = skipParentheses(node.operand);
      if (isPrivateIdentifierPropertyAccessExpression(operand)) {
        let info;
        if (info = accessPrivateIdentifier2(operand.name)) {
          const receiver = visitNode(operand.expression, visitor, isExpression);
          const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
          let expression = createPrivateIdentifierAccess(info, readExpression);
          const temp = isPrefixUnaryExpression(node) || discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration);
          expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp);
          expression = createPrivateIdentifierAssignment(
            info,
            initializeExpression || readExpression,
            expression,
            64 /* EqualsToken */
          );
          setOriginalNode(expression, node);
          setTextRange(expression, node);
          if (temp) {
            expression = factory2.createComma(expression, temp);
            setTextRange(expression, node);
          }
          return expression;
        }
      } else if (shouldTransformSuperInStaticInitializers && isSuperProperty(operand) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
        const { classConstructor, superClassReference, facts } = lexicalEnvironment.data;
        if (facts & 1 /* ClassWasDecorated */) {
          const expression = visitInvalidSuperProperty(operand);
          return isPrefixUnaryExpression(node) ? factory2.updatePrefixUnaryExpression(node, expression) : factory2.updatePostfixUnaryExpression(node, expression);
        }
        if (classConstructor && superClassReference) {
          let setterName;
          let getterName;
          if (isPropertyAccessExpression(operand)) {
            if (isIdentifier(operand.name)) {
              getterName = setterName = factory2.createStringLiteralFromNode(operand.name);
            }
          } else {
            if (isSimpleInlineableExpression(operand.argumentExpression)) {
              getterName = setterName = operand.argumentExpression;
            } else {
              getterName = factory2.createTempVariable(hoistVariableDeclaration);
              setterName = factory2.createAssignment(getterName, visitNode(operand.argumentExpression, visitor, isExpression));
            }
          }
          if (setterName && getterName) {
            let expression = factory2.createReflectGetCall(superClassReference, getterName, classConstructor);
            setTextRange(expression, operand);
            const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration);
            expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp);
            expression = factory2.createReflectSetCall(superClassReference, setterName, expression, classConstructor);
            setOriginalNode(expression, node);
            setTextRange(expression, node);
            if (temp) {
              expression = factory2.createComma(expression, temp);
              setTextRange(expression, node);
            }
            return expression;
          }
        }
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitForStatement(node) {
    return factory2.updateForStatement(
      node,
      visitNode(node.initializer, discardedValueVisitor, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, discardedValueVisitor, isExpression),
      visitIterationBody(node.statement, visitor, context)
    );
  }
  function visitExpressionStatement(node) {
    return factory2.updateExpressionStatement(
      node,
      visitNode(node.expression, discardedValueVisitor, isExpression)
    );
  }
  function createCopiableReceiverExpr(receiver) {
    const clone2 = nodeIsSynthesized(receiver) ? receiver : factory2.cloneNode(receiver);
    if (isSimpleInlineableExpression(receiver)) {
      return { readExpression: clone2, initializeExpression: void 0 };
    }
    const readExpression = factory2.createTempVariable(hoistVariableDeclaration);
    const initializeExpression = factory2.createAssignment(readExpression, clone2);
    return { readExpression, initializeExpression };
  }
  function visitCallExpression(node) {
    var _a;
    if (isPrivateIdentifierPropertyAccessExpression(node.expression) && accessPrivateIdentifier2(node.expression.name)) {
      const { thisArg, target } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion);
      if (isCallChain(node)) {
        return factory2.updateCallChain(
          node,
          factory2.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"),
          /*questionDotToken*/
          void 0,
          /*typeArguments*/
          void 0,
          [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)]
        );
      }
      return factory2.updateCallExpression(
        node,
        factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "call"),
        /*typeArguments*/
        void 0,
        [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)]
      );
    }
    if (shouldTransformSuperInStaticInitializers && isSuperProperty(node.expression) && currentStaticPropertyDeclarationOrStaticBlock && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) {
      const invocation = factory2.createFunctionCallCall(
        visitNode(node.expression, visitor, isExpression),
        lexicalEnvironment.data.classConstructor,
        visitNodes2(node.arguments, visitor, isExpression)
      );
      setOriginalNode(invocation, node);
      setTextRange(invocation, node);
      return invocation;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitTaggedTemplateExpression(node) {
    var _a;
    if (isPrivateIdentifierPropertyAccessExpression(node.tag) && accessPrivateIdentifier2(node.tag.name)) {
      const { thisArg, target } = factory2.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion);
      return factory2.updateTaggedTemplateExpression(
        node,
        factory2.createCallExpression(
          factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"),
          /*typeArguments*/
          void 0,
          [visitNode(thisArg, visitor, isExpression)]
        ),
        /*typeArguments*/
        void 0,
        visitNode(node.template, visitor, isTemplateLiteral)
      );
    }
    if (shouldTransformSuperInStaticInitializers && isSuperProperty(node.tag) && currentStaticPropertyDeclarationOrStaticBlock && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) {
      const invocation = factory2.createFunctionBindCall(
        visitNode(node.tag, visitor, isExpression),
        lexicalEnvironment.data.classConstructor,
        []
      );
      setOriginalNode(invocation, node);
      setTextRange(invocation, node);
      return factory2.updateTaggedTemplateExpression(
        node,
        invocation,
        /*typeArguments*/
        void 0,
        visitNode(node.template, visitor, isTemplateLiteral)
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function transformClassStaticBlockDeclaration(node) {
    if (lexicalEnvironment) {
      lexicalEnvironmentMap.set(getOriginalNode(node), lexicalEnvironment);
    }
    if (shouldTransformPrivateElementsOrClassStaticBlocks) {
      startLexicalEnvironment();
      let statements = setCurrentStaticPropertyDeclarationOrStaticBlockAnd(
        node,
        (statements2) => visitNodes2(statements2, visitor, isStatement),
        node.body.statements
      );
      statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment());
      const iife = factory2.createImmediatelyInvokedArrowFunction(statements);
      setOriginalNode(iife, node);
      setTextRange(iife, node);
      addEmitFlags(iife, 4 /* AdviseOnEmitNode */);
      return iife;
    }
  }
  function isAnonymousClassNeedingAssignedName(node) {
    if (isClassExpression(node) && !node.name) {
      const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node);
      const classStaticBlock = find(staticPropertiesOrClassStaticBlocks, isClassStaticBlockDeclaration);
      if (classStaticBlock) {
        for (const statement of classStaticBlock.body.statements) {
          if (isExpressionStatement(statement) && isCallToHelper(statement.expression, "___setFunctionName")) {
            return false;
          }
        }
      }
      const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || !!(getInternalEmitFlags(node) && 32 /* TransformPrivateStaticElements */)) && some(staticPropertiesOrClassStaticBlocks, (node2) => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2));
      return hasTransformableStatics;
    }
    return false;
  }
  function visitBinaryExpression(node, discarded) {
    if (isDestructuringAssignment(node)) {
      const savedPendingExpressions = pendingExpressions;
      pendingExpressions = void 0;
      node = factory2.updateBinaryExpression(
        node,
        visitNode(node.left, assignmentTargetVisitor, isExpression),
        node.operatorToken,
        visitNode(node.right, visitor, isExpression)
      );
      const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact([...pendingExpressions, node])) : node;
      pendingExpressions = savedPendingExpressions;
      return expr;
    }
    if (isAssignmentExpression(node)) {
      if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
        const assignedName = getAssignedNameOfIdentifier(node.left, node.right);
        const left2 = visitNode(node.left, visitor, isExpression);
        const right = visitNode(node.right, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
        return factory2.updateBinaryExpression(node, left2, node.operatorToken, right);
      }
      const left = skipOuterExpressions(node.left, 8 /* PartiallyEmittedExpressions */ | 1 /* Parentheses */);
      if (isPrivateIdentifierPropertyAccessExpression(left)) {
        const info = accessPrivateIdentifier2(left.name);
        if (info) {
          return setTextRange(
            setOriginalNode(
              createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind),
              node
            ),
            node
          );
        }
      } else if (shouldTransformSuperInStaticInitializers && isSuperProperty(node.left) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
        const { classConstructor, superClassReference, facts } = lexicalEnvironment.data;
        if (facts & 1 /* ClassWasDecorated */) {
          return factory2.updateBinaryExpression(
            node,
            visitInvalidSuperProperty(node.left),
            node.operatorToken,
            visitNode(node.right, visitor, isExpression)
          );
        }
        if (classConstructor && superClassReference) {
          let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0;
          if (setterName) {
            let expression = visitNode(node.right, visitor, isExpression);
            if (isCompoundAssignment(node.operatorToken.kind)) {
              let getterName = setterName;
              if (!isSimpleInlineableExpression(setterName)) {
                getterName = factory2.createTempVariable(hoistVariableDeclaration);
                setterName = factory2.createAssignment(getterName, setterName);
              }
              const superPropertyGet = factory2.createReflectGetCall(
                superClassReference,
                getterName,
                classConstructor
              );
              setOriginalNode(superPropertyGet, node.left);
              setTextRange(superPropertyGet, node.left);
              expression = factory2.createBinaryExpression(
                superPropertyGet,
                getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind),
                expression
              );
              setTextRange(expression, node);
            }
            const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration);
            if (temp) {
              expression = factory2.createAssignment(temp, expression);
              setTextRange(temp, node);
            }
            expression = factory2.createReflectSetCall(
              superClassReference,
              setterName,
              expression,
              classConstructor
            );
            setOriginalNode(expression, node);
            setTextRange(expression, node);
            if (temp) {
              expression = factory2.createComma(expression, temp);
              setTextRange(expression, node);
            }
            return expression;
          }
        }
      }
    }
    if (isPrivateIdentifierInExpression(node)) {
      return transformPrivateIdentifierInInExpression(node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCommaListExpression(node, discarded) {
    const elements = discarded ? visitCommaListElements(node.elements, discardedValueVisitor) : visitCommaListElements(node.elements, visitor, discardedValueVisitor);
    return factory2.updateCommaListExpression(node, elements);
  }
  function visitParenthesizedExpression(node, discarded, referencedName) {
    const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2) => namedEvaluationVisitor(node2, referencedName) : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updateParenthesizedExpression(node, expression);
  }
  function visitPartiallyEmittedExpression(node, discarded, referencedName) {
    const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2) => namedEvaluationVisitor(node2, referencedName) : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updatePartiallyEmittedExpression(node, expression);
  }
  function visitReferencedPropertyName(node) {
    if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) {
      const referencedName2 = factory2.createStringLiteralFromNode(node);
      const name2 = visitNode(node, visitor, isPropertyName);
      return { referencedName: referencedName2, name: name2 };
    }
    if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) {
      const referencedName2 = factory2.createStringLiteralFromNode(node.expression);
      const name2 = visitNode(node, visitor, isPropertyName);
      return { referencedName: referencedName2, name: name2 };
    }
    const referencedName = factory2.createTempVariable(hoistVariableDeclaration);
    const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression));
    const assignment = factory2.createAssignment(referencedName, key);
    const name = factory2.updateComputedPropertyName(node, injectPendingExpressions(assignment));
    return { referencedName, name };
  }
  function createPrivateIdentifierAssignment(info, receiver, right, operator) {
    receiver = visitNode(receiver, visitor, isExpression);
    right = visitNode(right, visitor, isExpression);
    if (isCompoundAssignment(operator)) {
      const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
      receiver = initializeExpression || readExpression;
      right = factory2.createBinaryExpression(
        createPrivateIdentifierAccessHelper(info, readExpression),
        getNonAssignmentOperatorForCompoundAssignment(operator),
        right
      );
    }
    setCommentRange(receiver, moveRangePos(receiver, -1));
    switch (info.kind) {
      case "a" /* Accessor */:
        return emitHelpers().createClassPrivateFieldSetHelper(
          receiver,
          info.brandCheckIdentifier,
          right,
          info.kind,
          info.setterName
        );
      case "m" /* Method */:
        return emitHelpers().createClassPrivateFieldSetHelper(
          receiver,
          info.brandCheckIdentifier,
          right,
          info.kind,
          /*f*/
          void 0
        );
      case "f" /* Field */:
        return emitHelpers().createClassPrivateFieldSetHelper(
          receiver,
          info.brandCheckIdentifier,
          right,
          info.kind,
          info.isStatic ? info.variableName : void 0
        );
      case "untransformed":
        return Debug.fail("Access helpers should not be created for untransformed private elements");
      default:
        Debug.assertNever(info, "Unknown private element type");
    }
  }
  function getPrivateInstanceMethodsAndAccessors(node) {
    return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName);
  }
  function getClassFacts(node) {
    let facts = 0 /* None */;
    const original = getOriginalNode(node);
    if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) {
      facts |= 1 /* ClassWasDecorated */;
    }
    let containsPublicInstanceFields = false;
    let containsInitializedPublicInstanceFields = false;
    let containsInstancePrivateElements = false;
    let containsInstanceAutoAccessors = false;
    for (const member of node.members) {
      if (isStatic(member)) {
        if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks) {
          facts |= 2 /* NeedsClassConstructorReference */;
        }
        if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) {
          if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) {
            facts |= 8 /* NeedsSubstitutionForThisInClassStaticField */;
            if (!(facts & 1 /* ClassWasDecorated */)) {
              facts |= 2 /* NeedsClassConstructorReference */;
            }
          }
          if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* ContainsLexicalSuper */) {
            if (!(facts & 1 /* ClassWasDecorated */)) {
              facts |= 2 /* NeedsClassConstructorReference */ | 4 /* NeedsClassSuperReference */;
            }
          }
        }
      } else if (!hasAbstractModifier(getOriginalNode(member))) {
        if (isAutoAccessorPropertyDeclaration(member)) {
          containsInstanceAutoAccessors = true;
          containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member));
        } else if (isPrivateIdentifierClassElementDeclaration(member)) {
          containsInstancePrivateElements = true;
        } else if (isPropertyDeclaration(member)) {
          containsPublicInstanceFields = true;
          containsInitializedPublicInstanceFields || (containsInitializedPublicInstanceFields = !!member.initializer);
        }
      }
    }
    const willHoistInitializersToConstructor = shouldTransformInitializersUsingDefine && containsPublicInstanceFields || shouldTransformInitializersUsingSet && containsInitializedPublicInstanceFields || shouldTransformPrivateElementsOrClassStaticBlocks && containsInstancePrivateElements || shouldTransformPrivateElementsOrClassStaticBlocks && containsInstanceAutoAccessors && shouldTransformAutoAccessors === -1 /* True */;
    if (willHoistInitializersToConstructor) {
      facts |= 16 /* WillHoistInitializersToConstructor */;
    }
    return facts;
  }
  function visitExpressionWithTypeArgumentsInHeritageClause(node) {
    var _a;
    const facts = ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts) || 0 /* None */;
    if (facts & 4 /* NeedsClassSuperReference */) {
      const temp = factory2.createTempVariable(
        hoistVariableDeclaration,
        /*reservedInNestedScopes*/
        true
      );
      getClassLexicalEnvironment().superClassReference = temp;
      return factory2.updateExpressionWithTypeArguments(
        node,
        factory2.createAssignment(
          temp,
          visitNode(node.expression, visitor, isExpression)
        ),
        /*typeArguments*/
        void 0
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitInNewClassLexicalEnvironment(node, referencedName, visitor2) {
    const savedCurrentClassContainer = currentClassContainer;
    const savedPendingExpressions = pendingExpressions;
    const savedLexicalEnvironment = lexicalEnvironment;
    currentClassContainer = node;
    pendingExpressions = void 0;
    startClassLexicalEnvironment();
    const shouldAlwaysTransformPrivateStaticElements = getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */;
    if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldAlwaysTransformPrivateStaticElements) {
      const name = getNameOfDeclaration(node);
      if (name && isIdentifier(name)) {
        getPrivateIdentifierEnvironment().data.className = name;
      }
    }
    if (shouldTransformPrivateElementsOrClassStaticBlocks) {
      const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
      if (some(privateInstanceMethodsAndAccessors)) {
        getPrivateIdentifierEnvironment().data.weakSetName = createHoistedVariableForClass(
          "instances",
          privateInstanceMethodsAndAccessors[0].name
        );
      }
    }
    const facts = getClassFacts(node);
    if (facts) {
      getClassLexicalEnvironment().facts = facts;
    }
    if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */) {
      enableSubstitutionForClassStaticThisOrSuperReference();
    }
    const result = visitor2(node, facts, referencedName);
    endClassLexicalEnvironment();
    Debug.assert(lexicalEnvironment === savedLexicalEnvironment);
    currentClassContainer = savedCurrentClassContainer;
    pendingExpressions = savedPendingExpressions;
    return result;
  }
  function visitClassDeclaration(node) {
    return visitInNewClassLexicalEnvironment(
      node,
      /*referencedName*/
      void 0,
      visitClassDeclarationInNewClassLexicalEnvironment
    );
  }
  function visitClassDeclarationInNewClassLexicalEnvironment(node, facts) {
    var _a, _b;
    let pendingClassReferenceAssignment;
    if (facts & 2 /* NeedsClassConstructorReference */) {
      if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a = node.emitNode) == null ? void 0 : _a.classThis)) {
        getClassLexicalEnvironment().classConstructor = node.emitNode.classThis;
        pendingClassReferenceAssignment = factory2.createAssignment(node.emitNode.classThis, factory2.getInternalName(node));
      } else {
        const temp = factory2.createTempVariable(
          hoistVariableDeclaration,
          /*reservedInNestedScopes*/
          true
        );
        getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp);
        pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node));
      }
      if ((_b = node.emitNode) == null ? void 0 : _b.classThis) {
        getClassLexicalEnvironment().classThis = node.emitNode.classThis;
      }
    }
    const isExport = hasSyntacticModifier(node, 1 /* Export */);
    const isDefault = hasSyntacticModifier(node, 1024 /* Default */);
    let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
    const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause);
    const { members, prologue } = transformClassMembers(node);
    const statements = [];
    if (pendingClassReferenceAssignment) {
      getPendingExpressions().unshift(pendingClassReferenceAssignment);
    }
    if (some(pendingExpressions)) {
      statements.push(factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions)));
    }
    if (shouldTransformInitializersUsingSet || shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) {
      const staticProperties = getStaticPropertiesAndClassStaticBlock(node);
      if (some(staticProperties)) {
        addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node));
      }
    }
    if (statements.length > 0 && isExport && isDefault) {
      modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier);
      statements.push(factory2.createExportAssignment(
        /*modifiers*/
        void 0,
        /*isExportEquals*/
        false,
        factory2.getLocalName(
          node,
          /*allowComments*/
          false,
          /*allowSourceMaps*/
          true
        )
      ));
    }
    const classDecl = factory2.updateClassDeclaration(
      node,
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      heritageClauses,
      members
    );
    statements.unshift(classDecl);
    if (prologue) {
      statements.unshift(factory2.createExpressionStatement(prologue));
    }
    return statements;
  }
  function visitClassExpression(node, referencedName) {
    return visitInNewClassLexicalEnvironment(node, referencedName, visitClassExpressionInNewClassLexicalEnvironment);
  }
  function visitClassExpressionInNewClassLexicalEnvironment(node, facts, referencedName) {
    var _a, _b, _c, _d;
    const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */);
    const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node);
    const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */;
    let temp;
    function createClassTempVar() {
      var _a2;
      if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) {
        return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis;
      }
      const classCheckFlags = resolver.getNodeCheckFlags(node);
      const isClassWithConstructorReference2 = classCheckFlags & 1048576 /* ClassWithConstructorReference */;
      const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */;
      const temp2 = factory2.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference2);
      getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp2);
      return temp2;
    }
    if ((_a = node.emitNode) == null ? void 0 : _a.classThis) {
      getClassLexicalEnvironment().classThis = node.emitNode.classThis;
    }
    if (facts & 2 /* NeedsClassConstructorReference */) {
      temp ?? (temp = createClassTempVar());
    }
    const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
    const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause);
    const { members, prologue } = transformClassMembers(node);
    let classExpression = factory2.updateClassExpression(
      node,
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      heritageClauses,
      members
    );
    const expressions = [];
    if (prologue) {
      expressions.push(prologue);
    }
    const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) && some(staticPropertiesOrClassStaticBlocks, (node2) => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2));
    if (hasTransformableStatics || some(pendingExpressions) || referencedName) {
      if (isDecoratedClassDeclaration) {
        Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
        if (some(pendingExpressions)) {
          addRange(pendingStatements, map(pendingExpressions, factory2.createExpressionStatement));
        }
        if (referencedName) {
          if (shouldTransformPrivateElementsOrClassStaticBlocks) {
            const setNameExpression = emitHelpers().createSetFunctionNameHelper(temp ?? ((_b = node.emitNode) == null ? void 0 : _b.classThis) ?? factory2.getInternalName(node), referencedName);
            pendingStatements.push(factory2.createExpressionStatement(setNameExpression));
          } else {
            const setNameExpression = emitHelpers().createSetFunctionNameHelper(factory2.createThis(), referencedName);
            classExpression = factory2.updateClassExpression(
              classExpression,
              classExpression.modifiers,
              classExpression.name,
              classExpression.typeParameters,
              classExpression.heritageClauses,
              [
                factory2.createClassStaticBlockDeclaration(
                  factory2.createBlock([
                    factory2.createExpressionStatement(setNameExpression)
                  ])
                ),
                ...classExpression.members
              ]
            );
          }
        }
        if (some(staticPropertiesOrClassStaticBlocks)) {
          addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, ((_c = node.emitNode) == null ? void 0 : _c.classThis) ?? factory2.getInternalName(node));
        }
        if (temp) {
          expressions.push(factory2.createAssignment(temp, classExpression));
        } else if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_d = node.emitNode) == null ? void 0 : _d.classThis)) {
          expressions.push(factory2.createAssignment(node.emitNode.classThis, classExpression));
        } else {
          expressions.push(classExpression);
        }
      } else {
        temp ?? (temp = createClassTempVar());
        if (isClassWithConstructorReference) {
          enableSubstitutionForClassAliases();
          const alias = factory2.cloneNode(temp);
          alias.emitNode.autoGenerate.flags &= ~8 /* ReservedInNestedScopes */;
          classAliases[getOriginalNodeId(node)] = alias;
        }
        expressions.push(factory2.createAssignment(temp, classExpression));
        addRange(expressions, pendingExpressions);
        if (referencedName) {
          expressions.push(emitHelpers().createSetFunctionNameHelper(temp, referencedName));
        }
        addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp));
        expressions.push(factory2.cloneNode(temp));
      }
    } else {
      expressions.push(classExpression);
    }
    if (expressions.length > 1) {
      addEmitFlags(classExpression, 131072 /* Indented */);
      expressions.forEach(startOnNewLine);
    }
    return factory2.inlineExpressions(expressions);
  }
  function visitClassStaticBlockDeclaration(node) {
    if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
      return visitEachChild(node, visitor, context);
    }
    return void 0;
  }
  function transformClassMembers(node) {
    const shouldTransformPrivateStaticElementsInClass = !!(getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */);
    if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInFile) {
      for (const member of node.members) {
        if (isPrivateIdentifierClassElementDeclaration(member)) {
          if (shouldTransformClassElementToWeakMap(member)) {
            addPrivateIdentifierToEnvironment(member, member.name, addPrivateIdentifierClassElementToEnvironment);
          } else {
            const privateEnv = getPrivateIdentifierEnvironment();
            setPrivateIdentifier(privateEnv, member.name, { kind: "untransformed" });
          }
        }
      }
      if (shouldTransformPrivateElementsOrClassStaticBlocks) {
        if (some(getPrivateInstanceMethodsAndAccessors(node))) {
          createBrandCheckWeakSetForPrivateMethods();
        }
      }
      if (shouldTransformAutoAccessorsInCurrentClass()) {
        for (const member of node.members) {
          if (isAutoAccessorPropertyDeclaration(member)) {
            const storageName = factory2.getGeneratedPrivateNameForNode(
              member.name,
              /*prefix*/
              void 0,
              "_accessor_storage"
            );
            if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInClass && hasStaticModifier(member)) {
              addPrivateIdentifierToEnvironment(member, storageName, addPrivateIdentifierPropertyDeclarationToEnvironment);
            } else {
              const privateEnv = getPrivateIdentifierEnvironment();
              setPrivateIdentifier(privateEnv, storageName, { kind: "untransformed" });
            }
          }
        }
      }
    }
    let members = visitNodes2(node.members, classElementVisitor, isClassElement);
    let syntheticConstructor;
    if (!some(members, isConstructorDeclaration)) {
      syntheticConstructor = transformConstructor(
        /*constructor*/
        void 0,
        node
      );
    }
    let prologue;
    let syntheticStaticBlock;
    if (!shouldTransformPrivateElementsOrClassStaticBlocks && some(pendingExpressions)) {
      let statement = factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions));
      if (statement.transformFlags & 134234112 /* ContainsLexicalThisOrSuper */) {
        const temp = factory2.createTempVariable(hoistVariableDeclaration);
        const arrow = factory2.createArrowFunction(
          /*modifiers*/
          void 0,
          /*typeParameters*/
          void 0,
          /*parameters*/
          [],
          /*type*/
          void 0,
          /*equalsGreaterThanToken*/
          void 0,
          factory2.createBlock([statement])
        );
        prologue = factory2.createAssignment(temp, arrow);
        statement = factory2.createExpressionStatement(factory2.createCallExpression(
          temp,
          /*typeArguments*/
          void 0,
          []
        ));
      }
      const block = factory2.createBlock([statement]);
      syntheticStaticBlock = factory2.createClassStaticBlockDeclaration(block);
      pendingExpressions = void 0;
    }
    if (syntheticConstructor || syntheticStaticBlock) {
      let membersArray;
      membersArray = append(membersArray, syntheticConstructor);
      membersArray = append(membersArray, syntheticStaticBlock);
      membersArray = addRange(membersArray, members);
      members = setTextRange(
        factory2.createNodeArray(membersArray),
        /*location*/
        node.members
      );
    }
    return { members, prologue };
  }
  function createBrandCheckWeakSetForPrivateMethods() {
    const { weakSetName } = getPrivateIdentifierEnvironment().data;
    Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
    getPendingExpressions().push(
      factory2.createAssignment(
        weakSetName,
        factory2.createNewExpression(
          factory2.createIdentifier("WeakSet"),
          /*typeArguments*/
          void 0,
          []
        )
      )
    );
  }
  function transformConstructor(constructor, container) {
    constructor = visitNode(constructor, visitor, isConstructorDeclaration);
    if (!(lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) || !(lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */)) {
      return constructor;
    }
    const extendsClauseElement = getEffectiveBaseTypeNode(container);
    const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */);
    const parameters = visitParameterList(constructor ? constructor.parameters : void 0, visitor, context);
    const body = transformConstructorBody(container, constructor, isDerivedClass);
    if (!body) {
      return constructor;
    }
    if (constructor) {
      Debug.assert(parameters);
      return factory2.updateConstructorDeclaration(
        constructor,
        /*modifiers*/
        void 0,
        parameters,
        body
      );
    }
    return startOnNewLine(
      setOriginalNode(
        setTextRange(
          factory2.createConstructorDeclaration(
            /*modifiers*/
            void 0,
            parameters ?? [],
            body
          ),
          constructor || container
        ),
        constructor
      )
    );
  }
  function transformConstructorBody(node, constructor, isDerivedClass) {
    var _a;
    const instanceProperties = getProperties(
      node,
      /*requireInitializer*/
      false,
      /*isStatic*/
      false
    );
    let properties = instanceProperties;
    if (!useDefineForClassFields) {
      properties = filter(properties, (property) => !!property.initializer || isPrivateIdentifier(property.name) || hasAccessorModifier(property));
    }
    const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
    const needsConstructorBody = some(properties) || some(privateMethodsAndAccessors);
    if (!constructor && !needsConstructorBody) {
      return visitFunctionBody(
        /*node*/
        void 0,
        visitor,
        context
      );
    }
    resumeLexicalEnvironment();
    const needsSyntheticConstructor = !constructor && isDerivedClass;
    let indexOfFirstStatementAfterSuperAndPrologue = 0;
    let prologueStatementCount = 0;
    let superStatementIndex = -1;
    let statements = [];
    if ((_a = constructor == null ? void 0 : constructor.body) == null ? void 0 : _a.statements) {
      prologueStatementCount = factory2.copyPrologue(
        constructor.body.statements,
        statements,
        /*ensureUseStrict*/
        false,
        visitor
      );
      superStatementIndex = findSuperStatementIndex(constructor.body.statements, prologueStatementCount);
      if (superStatementIndex >= 0) {
        indexOfFirstStatementAfterSuperAndPrologue = superStatementIndex + 1;
        statements = [
          ...statements.slice(0, prologueStatementCount),
          ...visitNodes2(constructor.body.statements, visitor, isStatement, prologueStatementCount, indexOfFirstStatementAfterSuperAndPrologue - prologueStatementCount),
          ...statements.slice(prologueStatementCount)
        ];
      } else if (prologueStatementCount >= 0) {
        indexOfFirstStatementAfterSuperAndPrologue = prologueStatementCount;
      }
    }
    if (needsSyntheticConstructor) {
      statements.push(
        factory2.createExpressionStatement(
          factory2.createCallExpression(
            factory2.createSuper(),
            /*typeArguments*/
            void 0,
            [factory2.createSpreadElement(factory2.createIdentifier("arguments"))]
          )
        )
      );
    }
    let parameterPropertyDeclarationCount = 0;
    if (constructor == null ? void 0 : constructor.body) {
      for (let i = indexOfFirstStatementAfterSuperAndPrologue; i < constructor.body.statements.length; i++) {
        const statement = constructor.body.statements[i];
        if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) {
          parameterPropertyDeclarationCount++;
        } else {
          break;
        }
      }
      if (parameterPropertyDeclarationCount > 0) {
        indexOfFirstStatementAfterSuperAndPrologue += parameterPropertyDeclarationCount;
      }
    }
    const receiver = factory2.createThis();
    addInstanceMethodStatements(statements, privateMethodsAndAccessors, receiver);
    if (constructor) {
      const parameterProperties = filter(instanceProperties, (prop) => isParameterPropertyDeclaration(getOriginalNode(prop), constructor));
      const nonParameterProperties = filter(properties, (prop) => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor));
      addPropertyOrClassStaticBlockStatements(statements, parameterProperties, receiver);
      addPropertyOrClassStaticBlockStatements(statements, nonParameterProperties, receiver);
    } else {
      addPropertyOrClassStaticBlockStatements(statements, properties, receiver);
    }
    if (constructor) {
      addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, indexOfFirstStatementAfterSuperAndPrologue));
    }
    statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment());
    if (statements.length === 0 && !constructor) {
      return void 0;
    }
    const multiLine = (constructor == null ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? constructor.body.multiLine ?? statements.length > 0 : statements.length > 0;
    return setTextRange(
      factory2.createBlock(
        setTextRange(
          factory2.createNodeArray(statements),
          /*location*/
          constructor ? constructor.body.statements : node.members
        ),
        multiLine
      ),
      /*location*/
      constructor ? constructor.body : void 0
    );
  }
  function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) {
    for (const property of properties) {
      if (isStatic(property) && !shouldTransformPrivateElementsOrClassStaticBlocks) {
        continue;
      }
      const statement = transformPropertyOrClassStaticBlock(property, receiver);
      if (!statement) {
        continue;
      }
      statements.push(statement);
    }
  }
  function transformPropertyOrClassStaticBlock(property, receiver) {
    const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver);
    if (!expression) {
      return void 0;
    }
    const statement = factory2.createExpressionStatement(expression);
    setOriginalNode(statement, property);
    addEmitFlags(statement, getEmitFlags(property) & 3072 /* NoComments */);
    setCommentRange(statement, property);
    const propertyOriginalNode = getOriginalNode(property);
    if (isParameter(propertyOriginalNode)) {
      setSourceMapRange(statement, propertyOriginalNode);
      removeAllComments(statement);
    } else {
      setSourceMapRange(statement, moveRangePastModifiers(property));
    }
    setSyntheticLeadingComments(expression, void 0);
    setSyntheticTrailingComments(expression, void 0);
    if (hasAccessorModifier(propertyOriginalNode)) {
      addEmitFlags(statement, 3072 /* NoComments */);
    }
    return statement;
  }
  function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks, receiver) {
    const expressions = [];
    for (const property of propertiesOrClassStaticBlocks) {
      const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver);
      if (!expression) {
        continue;
      }
      startOnNewLine(expression);
      setOriginalNode(expression, property);
      addEmitFlags(expression, getEmitFlags(property) & 3072 /* NoComments */);
      setSourceMapRange(expression, moveRangePastModifiers(property));
      setCommentRange(expression, property);
      expressions.push(expression);
    }
    return expressions;
  }
  function transformProperty(property, receiver) {
    var _a;
    const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
    const transformed = transformPropertyWorker(property, receiver);
    if (transformed && hasStaticModifier(property) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts)) {
      setOriginalNode(transformed, property);
      addEmitFlags(transformed, 4 /* AdviseOnEmitNode */);
      setSourceMapRange(transformed, getSourceMapRange(property.name));
      lexicalEnvironmentMap.set(getOriginalNode(property), lexicalEnvironment);
    }
    currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
    return transformed;
  }
  function transformPropertyWorker(property, receiver) {
    const emitAssignment = !useDefineForClassFields;
    let referencedName;
    if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) {
      if (isPropertyNameLiteral(property.name) || isPrivateIdentifier(property.name)) {
        referencedName = factory2.createStringLiteralFromNode(property.name);
      } else if (isPropertyNameLiteral(property.name.expression) && !isIdentifier(property.name.expression)) {
        referencedName = factory2.createStringLiteralFromNode(property.name.expression);
      } else {
        referencedName = factory2.getGeneratedNameForNode(property.name);
      }
    }
    const propertyName = hasAccessorModifier(property) ? factory2.getGeneratedPrivateNameForNode(property.name) : isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? factory2.updateComputedPropertyName(property.name, factory2.getGeneratedNameForNode(property.name)) : property.name;
    if (hasStaticModifier(property)) {
      currentStaticPropertyDeclarationOrStaticBlock = property;
    }
    const initializerVisitor = referencedName ? (child) => namedEvaluationVisitor(child, referencedName) : visitor;
    if (isPrivateIdentifier(propertyName) && shouldTransformClassElementToWeakMap(property)) {
      const privateIdentifierInfo = accessPrivateIdentifier2(propertyName);
      if (privateIdentifierInfo) {
        if (privateIdentifierInfo.kind === "f" /* Field */) {
          if (!privateIdentifierInfo.isStatic) {
            return createPrivateInstanceFieldInitializer(
              factory2,
              receiver,
              visitNode(property.initializer, initializerVisitor, isExpression),
              privateIdentifierInfo.brandCheckIdentifier
            );
          } else {
            return createPrivateStaticFieldInitializer(
              factory2,
              privateIdentifierInfo.variableName,
              visitNode(property.initializer, initializerVisitor, isExpression)
            );
          }
        } else {
          return void 0;
        }
      } else {
        Debug.fail("Undeclared private name for property declaration.");
      }
    }
    if ((isPrivateIdentifier(propertyName) || hasStaticModifier(property)) && !property.initializer) {
      return void 0;
    }
    const propertyOriginalNode = getOriginalNode(property);
    if (hasSyntacticModifier(propertyOriginalNode, 256 /* Abstract */)) {
      return void 0;
    }
    let initializer = visitNode(property.initializer, initializerVisitor, isExpression);
    if (isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName)) {
      const localName = factory2.cloneNode(propertyName);
      if (initializer) {
        if (isParenthesizedExpression(initializer) && isCommaExpression(initializer.expression) && isCallToHelper(initializer.expression.left, "___runInitializers") && isVoidExpression(initializer.expression.right) && isNumericLiteral(initializer.expression.right.expression)) {
          initializer = initializer.expression.left;
        }
        initializer = factory2.inlineExpressions([initializer, localName]);
      } else {
        initializer = localName;
      }
      setEmitFlags(propertyName, 3072 /* NoComments */ | 96 /* NoSourceMap */);
      setSourceMapRange(localName, propertyOriginalNode.name);
      setEmitFlags(localName, 3072 /* NoComments */);
    } else {
      initializer ?? (initializer = factory2.createVoidZero());
    }
    if (emitAssignment || isPrivateIdentifier(propertyName)) {
      const memberAccess = createMemberAccessForPropertyName(
        factory2,
        receiver,
        propertyName,
        /*location*/
        propertyName
      );
      addEmitFlags(memberAccess, 1024 /* NoLeadingComments */);
      const expression = factory2.createAssignment(memberAccess, initializer);
      return expression;
    } else {
      const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory2.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName;
      const descriptor = factory2.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
      return factory2.createObjectDefinePropertyCall(receiver, name, descriptor);
    }
  }
  function enableSubstitutionForClassAliases() {
    if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
      enabledSubstitutions |= 1 /* ClassAliases */;
      context.enableSubstitution(80 /* Identifier */);
      classAliases = [];
    }
  }
  function enableSubstitutionForClassStaticThisOrSuperReference() {
    if ((enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */) === 0) {
      enabledSubstitutions |= 2 /* ClassStaticThisOrSuperReference */;
      context.enableSubstitution(110 /* ThisKeyword */);
      context.enableEmitNotification(261 /* FunctionDeclaration */);
      context.enableEmitNotification(217 /* FunctionExpression */);
      context.enableEmitNotification(175 /* Constructor */);
      context.enableEmitNotification(176 /* GetAccessor */);
      context.enableEmitNotification(177 /* SetAccessor */);
      context.enableEmitNotification(173 /* MethodDeclaration */);
      context.enableEmitNotification(171 /* PropertyDeclaration */);
      context.enableEmitNotification(166 /* ComputedPropertyName */);
    }
  }
  function addInstanceMethodStatements(statements, methods, receiver) {
    if (!shouldTransformPrivateElementsOrClassStaticBlocks || !some(methods)) {
      return;
    }
    const { weakSetName } = getPrivateIdentifierEnvironment().data;
    Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
    statements.push(
      factory2.createExpressionStatement(
        createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName)
      )
    );
  }
  function visitInvalidSuperProperty(node) {
    return isPropertyAccessExpression(node) ? factory2.updatePropertyAccessExpression(
      node,
      factory2.createVoidZero(),
      node.name
    ) : factory2.updateElementAccessExpression(
      node,
      factory2.createVoidZero(),
      visitNode(node.argumentExpression, visitor, isExpression)
    );
  }
  function getPropertyNameExpressionIfNeeded(name, shouldHoist, captureReferencedName) {
    if (isComputedPropertyName(name)) {
      const cacheAssignment = findComputedPropertyNameCacheAssignment(name);
      let expression = visitNode(name.expression, visitor, isExpression);
      const innerExpression = skipPartiallyEmittedExpressions(expression);
      const inlinable = isSimpleInlineableExpression(innerExpression);
      const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left);
      if (!alreadyTransformed && !inlinable && shouldHoist) {
        const generatedName = factory2.getGeneratedNameForNode(name);
        if (resolver.getNodeCheckFlags(name) & 32768 /* BlockScopedBindingInLoop */) {
          addBlockScopedVariable(generatedName);
        } else {
          hoistVariableDeclaration(generatedName);
        }
        if (captureReferencedName) {
          expression = emitHelpers().createPropKeyHelper(expression);
        }
        return factory2.createAssignment(generatedName, expression);
      }
      return inlinable || isIdentifier(innerExpression) ? void 0 : expression;
    }
  }
  function startClassLexicalEnvironment() {
    lexicalEnvironment = { previous: lexicalEnvironment, data: void 0 };
  }
  function endClassLexicalEnvironment() {
    lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous;
  }
  function getClassLexicalEnvironment() {
    Debug.assert(lexicalEnvironment);
    return lexicalEnvironment.data ?? (lexicalEnvironment.data = {
      facts: 0 /* None */,
      classConstructor: void 0,
      classThis: void 0,
      superClassReference: void 0
      // privateIdentifierEnvironment: undefined,
    });
  }
  function getPrivateIdentifierEnvironment() {
    Debug.assert(lexicalEnvironment);
    return lexicalEnvironment.privateEnv ?? (lexicalEnvironment.privateEnv = newPrivateEnvironment({
      className: void 0,
      weakSetName: void 0
    }));
  }
  function getPendingExpressions() {
    return pendingExpressions ?? (pendingExpressions = []);
  }
  function addPrivateIdentifierClassElementToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo) {
    if (isAutoAccessorPropertyDeclaration(node)) {
      addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo);
    } else if (isPropertyDeclaration(node)) {
      addPrivateIdentifierPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo);
    } else if (isMethodDeclaration(node)) {
      addPrivateIdentifierMethodDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo);
    } else if (isGetAccessorDeclaration(node)) {
      addPrivateIdentifierGetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo);
    } else if (isSetAccessorDeclaration(node)) {
      addPrivateIdentifierSetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo);
    }
  }
  function addPrivateIdentifierPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) {
    if (isStatic2) {
      const brandCheckIdentifier = Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment");
      const variableName = createHoistedVariableForPrivateName(name);
      setPrivateIdentifier(privateEnv, name, {
        kind: "f" /* Field */,
        isStatic: true,
        brandCheckIdentifier,
        variableName,
        isValid
      });
    } else {
      const weakMapName = createHoistedVariableForPrivateName(name);
      setPrivateIdentifier(privateEnv, name, {
        kind: "f" /* Field */,
        isStatic: false,
        brandCheckIdentifier: weakMapName,
        isValid
      });
      getPendingExpressions().push(factory2.createAssignment(
        weakMapName,
        factory2.createNewExpression(
          factory2.createIdentifier("WeakMap"),
          /*typeArguments*/
          void 0,
          []
        )
      ));
    }
  }
  function addPrivateIdentifierMethodDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) {
    const methodName = createHoistedVariableForPrivateName(name);
    const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment");
    setPrivateIdentifier(privateEnv, name, {
      kind: "m" /* Method */,
      methodName,
      brandCheckIdentifier,
      isStatic: isStatic2,
      isValid
    });
  }
  function addPrivateIdentifierGetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) {
    const getterName = createHoistedVariableForPrivateName(name, "_get");
    const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment");
    if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.getterName) {
      previousInfo.getterName = getterName;
    } else {
      setPrivateIdentifier(privateEnv, name, {
        kind: "a" /* Accessor */,
        getterName,
        setterName: void 0,
        brandCheckIdentifier,
        isStatic: isStatic2,
        isValid
      });
    }
  }
  function addPrivateIdentifierSetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) {
    const setterName = createHoistedVariableForPrivateName(name, "_set");
    const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment");
    if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.setterName) {
      previousInfo.setterName = setterName;
    } else {
      setPrivateIdentifier(privateEnv, name, {
        kind: "a" /* Accessor */,
        getterName: void 0,
        setterName,
        brandCheckIdentifier,
        isStatic: isStatic2,
        isValid
      });
    }
  }
  function addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) {
    const getterName = createHoistedVariableForPrivateName(name, "_get");
    const setterName = createHoistedVariableForPrivateName(name, "_set");
    const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment");
    setPrivateIdentifier(privateEnv, name, {
      kind: "a" /* Accessor */,
      getterName,
      setterName,
      brandCheckIdentifier,
      isStatic: isStatic2,
      isValid
    });
  }
  function addPrivateIdentifierToEnvironment(node, name, addDeclaration) {
    const lex = getClassLexicalEnvironment();
    const privateEnv = getPrivateIdentifierEnvironment();
    const previousInfo = getPrivateIdentifier(privateEnv, name);
    const isStatic2 = hasStaticModifier(node);
    const isValid = !isReservedPrivateName(name) && previousInfo === void 0;
    addDeclaration(node, name, lex, privateEnv, isStatic2, isValid, previousInfo);
  }
  function createHoistedVariableForClass(name, node, suffix) {
    const { className } = getPrivateIdentifierEnvironment().data;
    const prefix = className ? { prefix: "_", node: className, suffix: "_" } : "_";
    const identifier = typeof name === "object" ? factory2.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */, prefix, suffix) : typeof name === "string" ? factory2.createUniqueName(name, 16 /* Optimistic */, prefix, suffix) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0,
      /*reservedInNestedScopes*/
      true,
      prefix,
      suffix
    );
    if (resolver.getNodeCheckFlags(node) & 32768 /* BlockScopedBindingInLoop */) {
      addBlockScopedVariable(identifier);
    } else {
      hoistVariableDeclaration(identifier);
    }
    return identifier;
  }
  function createHoistedVariableForPrivateName(name, suffix) {
    const text = tryGetTextOfPropertyName(name);
    return createHoistedVariableForClass((text == null ? void 0 : text.substring(1)) ?? name, name, suffix);
  }
  function accessPrivateIdentifier2(name) {
    const info = accessPrivateIdentifier(lexicalEnvironment, name);
    return (info == null ? void 0 : info.kind) === "untransformed" ? void 0 : info;
  }
  function wrapPrivateIdentifierForDestructuringTarget(node) {
    const parameter = factory2.getGeneratedNameForNode(node);
    const info = accessPrivateIdentifier2(node.name);
    if (!info) {
      return visitEachChild(node, visitor, context);
    }
    let receiver = node.expression;
    if (isThisProperty(node) || isSuperProperty(node) || !isSimpleCopiableExpression(node.expression)) {
      receiver = factory2.createTempVariable(
        hoistVariableDeclaration,
        /*reservedInNestedScopes*/
        true
      );
      getPendingExpressions().push(factory2.createBinaryExpression(receiver, 64 /* EqualsToken */, visitNode(node.expression, visitor, isExpression)));
    }
    return factory2.createAssignmentTargetWrapper(
      parameter,
      createPrivateIdentifierAssignment(
        info,
        receiver,
        parameter,
        64 /* EqualsToken */
      )
    );
  }
  function visitDestructuringAssignmentTarget(node) {
    if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) {
      return visitAssignmentPattern(node);
    }
    if (isPrivateIdentifierPropertyAccessExpression(node)) {
      return wrapPrivateIdentifierForDestructuringTarget(node);
    } else if (shouldTransformSuperInStaticInitializers && isSuperProperty(node) && currentStaticPropertyDeclarationOrStaticBlock && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
      const { classConstructor, superClassReference, facts } = lexicalEnvironment.data;
      if (facts & 1 /* ClassWasDecorated */) {
        return visitInvalidSuperProperty(node);
      } else if (classConstructor && superClassReference) {
        const name = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0;
        if (name) {
          const temp = factory2.createTempVariable(
            /*recordTempVariable*/
            void 0
          );
          return factory2.createAssignmentTargetWrapper(
            temp,
            factory2.createReflectSetCall(
              superClassReference,
              name,
              temp,
              classConstructor
            )
          );
        }
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentElement(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const left = visitDestructuringAssignmentTarget(node.left);
      const assignedName = getAssignedNameOfIdentifier(node.left, node.right);
      const right = visitNode(node.right, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateBinaryExpression(node, left, node.operatorToken, right);
    }
    if (isAssignmentExpression(
      node,
      /*excludeCompoundAssignment*/
      true
    )) {
      const left = visitDestructuringAssignmentTarget(node.left);
      const right = visitNode(node.right, visitor, isExpression);
      return factory2.updateBinaryExpression(node, left, node.operatorToken, right);
    }
    return visitDestructuringAssignmentTarget(node);
  }
  function visitAssignmentRestElement(node) {
    if (isLeftHandSideExpression(node.expression)) {
      const expression = visitDestructuringAssignmentTarget(node.expression);
      return factory2.updateSpreadElement(node, expression);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitArrayAssignmentElement(node) {
    if (isArrayBindingOrAssignmentElement(node)) {
      if (isSpreadElement(node))
        return visitAssignmentRestElement(node);
      if (!isOmittedExpression(node))
        return visitAssignmentElement(node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentProperty(node) {
    const name = visitNode(node.name, visitor, isPropertyName);
    if (isAssignmentExpression(
      node.initializer,
      /*excludeCompoundAssignment*/
      true
    )) {
      const assignmentElement = visitAssignmentElement(node.initializer);
      return factory2.updatePropertyAssignment(node, name, assignmentElement);
    }
    if (isLeftHandSideExpression(node.initializer)) {
      const assignmentElement = visitDestructuringAssignmentTarget(node.initializer);
      return factory2.updatePropertyAssignment(node, name, assignmentElement);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitShorthandAssignmentProperty(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer);
      const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateShorthandPropertyAssignment(node, node.name, objectAssignmentInitializer);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentRestProperty(node) {
    if (isLeftHandSideExpression(node.expression)) {
      const expression = visitDestructuringAssignmentTarget(node.expression);
      return factory2.updateSpreadAssignment(node, expression);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitObjectAssignmentElement(node) {
    Debug.assertNode(node, isObjectBindingOrAssignmentElement);
    if (isSpreadAssignment(node))
      return visitAssignmentRestProperty(node);
    if (isShorthandPropertyAssignment(node))
      return visitShorthandAssignmentProperty(node);
    if (isPropertyAssignment(node))
      return visitAssignmentProperty(node);
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentPattern(node) {
    if (isArrayLiteralExpression(node)) {
      return factory2.updateArrayLiteralExpression(
        node,
        visitNodes2(node.elements, visitArrayAssignmentElement, isExpression)
      );
    } else {
      return factory2.updateObjectLiteralExpression(
        node,
        visitNodes2(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike)
      );
    }
  }
  function onEmitNode(hint, node, emitCallback) {
    const original = getOriginalNode(node);
    const lex = lexicalEnvironmentMap.get(original);
    if (lex) {
      const savedLexicalEnvironment = lexicalEnvironment;
      const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis;
      lexicalEnvironment = lex;
      previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis;
      shouldSubstituteThisWithClassThis = !isClassStaticBlockDeclaration(original) || !(getInternalEmitFlags(original) & 32 /* TransformPrivateStaticElements */);
      previousOnEmitNode(hint, node, emitCallback);
      shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis;
      previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis;
      lexicalEnvironment = savedLexicalEnvironment;
      return;
    }
    switch (node.kind) {
      case 217 /* FunctionExpression */:
        if (isArrowFunction(original) || getEmitFlags(node) & 524288 /* AsyncFunctionBody */) {
          break;
        }
      case 261 /* FunctionDeclaration */:
      case 175 /* Constructor */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
      case 173 /* MethodDeclaration */:
      case 171 /* PropertyDeclaration */: {
        const savedLexicalEnvironment = lexicalEnvironment;
        const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis;
        lexicalEnvironment = void 0;
        previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis;
        shouldSubstituteThisWithClassThis = false;
        previousOnEmitNode(hint, node, emitCallback);
        shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis;
        previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis;
        lexicalEnvironment = savedLexicalEnvironment;
        return;
      }
      case 166 /* ComputedPropertyName */: {
        const savedLexicalEnvironment = lexicalEnvironment;
        const savedShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis;
        lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous;
        shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis;
        previousOnEmitNode(hint, node, emitCallback);
        shouldSubstituteThisWithClassThis = savedShouldSubstituteThisWithClassThis;
        lexicalEnvironment = savedLexicalEnvironment;
        return;
      }
    }
    previousOnEmitNode(hint, node, emitCallback);
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return substituteExpressionIdentifier(node);
      case 110 /* ThisKeyword */:
        return substituteThisExpression(node);
    }
    return node;
  }
  function substituteThisExpression(node) {
    if (enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
      const { facts, classConstructor, classThis } = lexicalEnvironment.data;
      if (facts & 1 /* ClassWasDecorated */ && legacyDecorators) {
        return factory2.createParenthesizedExpression(factory2.createVoidZero());
      }
      const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor;
      if (substituteThis) {
        return setTextRange(
          setOriginalNode(
            factory2.cloneNode(substituteThis),
            node
          ),
          node
        );
      }
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    return trySubstituteClassAlias(node) || node;
  }
  function trySubstituteClassAlias(node) {
    if (enabledSubstitutions & 1 /* ClassAliases */) {
      if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) {
        const declaration = resolver.getReferencedValueDeclaration(node);
        if (declaration) {
          const classAlias = classAliases[declaration.id];
          if (classAlias) {
            const clone2 = factory2.cloneNode(classAlias);
            setSourceMapRange(clone2, node);
            setCommentRange(clone2, node);
            return clone2;
          }
        }
      }
    }
    return void 0;
  }
}
function createPrivateStaticFieldInitializer(factory2, variableName, initializer) {
  return factory2.createAssignment(
    variableName,
    factory2.createObjectLiteralExpression([
      factory2.createPropertyAssignment("value", initializer || factory2.createVoidZero())
    ])
  );
}
function createPrivateInstanceFieldInitializer(factory2, receiver, initializer, weakMapName) {
  return factory2.createCallExpression(
    factory2.createPropertyAccessExpression(weakMapName, "set"),
    /*typeArguments*/
    void 0,
    [receiver, initializer || factory2.createVoidZero()]
  );
}
function createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName) {
  return factory2.createCallExpression(
    factory2.createPropertyAccessExpression(weakSetName, "add"),
    /*typeArguments*/
    void 0,
    [receiver]
  );
}
function isReservedPrivateName(node) {
  return !isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor";
}
function isPrivateIdentifierInExpression(node) {
  return isPrivateIdentifier(node.left) && node.operatorToken.kind === 103 /* InKeyword */;
}

// src/compiler/transformers/typeSerializer.ts
function createRuntimeTypeSerializer(context) {
  const {
    factory: factory2,
    hoistVariableDeclaration
  } = context;
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
  let currentLexicalScope;
  let currentNameScope;
  return {
    serializeTypeNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeTypeNode, node),
    serializeTypeOfNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeTypeOfNode, node),
    serializeParameterTypesOfNode: (serializerContext, node, container) => setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container),
    serializeReturnTypeOfNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node)
  };
  function setSerializerContextAnd(serializerContext, cb, node, arg) {
    const savedCurrentLexicalScope = currentLexicalScope;
    const savedCurrentNameScope = currentNameScope;
    currentLexicalScope = serializerContext.currentLexicalScope;
    currentNameScope = serializerContext.currentNameScope;
    const result = arg === void 0 ? cb(node) : cb(node, arg);
    currentLexicalScope = savedCurrentLexicalScope;
    currentNameScope = savedCurrentNameScope;
    return result;
  }
  function getAccessorTypeNode(node) {
    const accessors = resolver.getAllAccessorDeclarations(node);
    return accessors.setAccessor && getSetAccessorTypeAnnotationNode(accessors.setAccessor) || accessors.getAccessor && getEffectiveReturnTypeNode(accessors.getAccessor);
  }
  function serializeTypeOfNode(node) {
    switch (node.kind) {
      case 171 /* PropertyDeclaration */:
      case 168 /* Parameter */:
        return serializeTypeNode(node.type);
      case 177 /* SetAccessor */:
      case 176 /* GetAccessor */:
        return serializeTypeNode(getAccessorTypeNode(node));
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
      case 173 /* MethodDeclaration */:
        return factory2.createIdentifier("Function");
      default:
        return factory2.createVoidZero();
    }
  }
  function serializeParameterTypesOfNode(node, container) {
    const valueDeclaration = isClassLike(node) ? getFirstConstructorWithBody(node) : isFunctionLike(node) && nodeIsPresent(node.body) ? node : void 0;
    const expressions = [];
    if (valueDeclaration) {
      const parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
      const numParameters = parameters.length;
      for (let i = 0; i < numParameters; i++) {
        const parameter = parameters[i];
        if (i === 0 && isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
          continue;
        }
        if (parameter.dotDotDotToken) {
          expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type)));
        } else {
          expressions.push(serializeTypeOfNode(parameter));
        }
      }
    }
    return factory2.createArrayLiteralExpression(expressions);
  }
  function getParametersOfDecoratedDeclaration(node, container) {
    if (container && node.kind === 176 /* GetAccessor */) {
      const { setAccessor } = getAllAccessorDeclarations(container.members, node);
      if (setAccessor) {
        return setAccessor.parameters;
      }
    }
    return node.parameters;
  }
  function serializeReturnTypeOfNode(node) {
    if (isFunctionLike(node) && node.type) {
      return serializeTypeNode(node.type);
    } else if (isAsyncFunction(node)) {
      return factory2.createIdentifier("Promise");
    }
    return factory2.createVoidZero();
  }
  function serializeTypeNode(node) {
    if (node === void 0) {
      return factory2.createIdentifier("Object");
    }
    node = skipTypeParentheses(node);
    switch (node.kind) {
      case 116 /* VoidKeyword */:
      case 157 /* UndefinedKeyword */:
      case 146 /* NeverKeyword */:
        return factory2.createVoidZero();
      case 183 /* FunctionType */:
      case 184 /* ConstructorType */:
        return factory2.createIdentifier("Function");
      case 187 /* ArrayType */:
      case 188 /* TupleType */:
        return factory2.createIdentifier("Array");
      case 181 /* TypePredicate */:
        return node.assertsModifier ? factory2.createVoidZero() : factory2.createIdentifier("Boolean");
      case 136 /* BooleanKeyword */:
        return factory2.createIdentifier("Boolean");
      case 202 /* TemplateLiteralType */:
      case 154 /* StringKeyword */:
        return factory2.createIdentifier("String");
      case 151 /* ObjectKeyword */:
        return factory2.createIdentifier("Object");
      case 200 /* LiteralType */:
        return serializeLiteralOfLiteralTypeNode(node.literal);
      case 150 /* NumberKeyword */:
        return factory2.createIdentifier("Number");
      case 162 /* BigIntKeyword */:
        return getGlobalConstructor("BigInt", 7 /* ES2020 */);
      case 155 /* SymbolKeyword */:
        return getGlobalConstructor("Symbol", 2 /* ES2015 */);
      case 182 /* TypeReference */:
        return serializeTypeReferenceNode(node);
      case 192 /* IntersectionType */:
        return serializeUnionOrIntersectionConstituents(
          node.types,
          /*isIntersection*/
          true
        );
      case 191 /* UnionType */:
        return serializeUnionOrIntersectionConstituents(
          node.types,
          /*isIntersection*/
          false
        );
      case 193 /* ConditionalType */:
        return serializeUnionOrIntersectionConstituents(
          [node.trueType, node.falseType],
          /*isIntersection*/
          false
        );
      case 197 /* TypeOperator */:
        if (node.operator === 148 /* ReadonlyKeyword */) {
          return serializeTypeNode(node.type);
        }
        break;
      case 185 /* TypeQuery */:
      case 198 /* IndexedAccessType */:
      case 199 /* MappedType */:
      case 186 /* TypeLiteral */:
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 196 /* ThisType */:
      case 204 /* ImportType */:
        break;
      case 318 /* JSDocAllType */:
      case 319 /* JSDocUnknownType */:
      case 323 /* JSDocFunctionType */:
      case 324 /* JSDocVariadicType */:
      case 325 /* JSDocNamepathType */:
        break;
      case 320 /* JSDocNullableType */:
      case 321 /* JSDocNonNullableType */:
      case 322 /* JSDocOptionalType */:
        return serializeTypeNode(node.type);
      default:
        return Debug.failBadSyntaxKind(node);
    }
    return factory2.createIdentifier("Object");
  }
  function serializeLiteralOfLiteralTypeNode(node) {
    switch (node.kind) {
      case 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
        return factory2.createIdentifier("String");
      case 223 /* PrefixUnaryExpression */: {
        const operand = node.operand;
        switch (operand.kind) {
          case 9 /* NumericLiteral */:
          case 10 /* BigIntLiteral */:
            return serializeLiteralOfLiteralTypeNode(operand);
          default:
            return Debug.failBadSyntaxKind(operand);
        }
      }
      case 9 /* NumericLiteral */:
        return factory2.createIdentifier("Number");
      case 10 /* BigIntLiteral */:
        return getGlobalConstructor("BigInt", 7 /* ES2020 */);
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
        return factory2.createIdentifier("Boolean");
      case 106 /* NullKeyword */:
        return factory2.createVoidZero();
      default:
        return Debug.failBadSyntaxKind(node);
    }
  }
  function serializeUnionOrIntersectionConstituents(types, isIntersection) {
    let serializedType;
    for (let typeNode of types) {
      typeNode = skipTypeParentheses(typeNode);
      if (typeNode.kind === 146 /* NeverKeyword */) {
        if (isIntersection)
          return factory2.createVoidZero();
        continue;
      }
      if (typeNode.kind === 159 /* UnknownKeyword */) {
        if (!isIntersection)
          return factory2.createIdentifier("Object");
        continue;
      }
      if (typeNode.kind === 133 /* AnyKeyword */) {
        return factory2.createIdentifier("Object");
      }
      if (!strictNullChecks && (isLiteralTypeNode(typeNode) && typeNode.literal.kind === 106 /* NullKeyword */ || typeNode.kind === 157 /* UndefinedKeyword */)) {
        continue;
      }
      const serializedConstituent = serializeTypeNode(typeNode);
      if (isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") {
        return serializedConstituent;
      }
      if (serializedType) {
        if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) {
          return factory2.createIdentifier("Object");
        }
      } else {
        serializedType = serializedConstituent;
      }
    }
    return serializedType ?? factory2.createVoidZero();
  }
  function equateSerializedTypeNodes(left, right) {
    return (
      // temp vars used in fallback
      isGeneratedIdentifier(left) ? isGeneratedIdentifier(right) : (
        // entity names
        isIdentifier(left) ? isIdentifier(right) && left.escapedText === right.escapedText : isPropertyAccessExpression(left) ? isPropertyAccessExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) && equateSerializedTypeNodes(left.name, right.name) : (
          // `void 0`
          isVoidExpression(left) ? isVoidExpression(right) && isNumericLiteral(left.expression) && left.expression.text === "0" && isNumericLiteral(right.expression) && right.expression.text === "0" : (
            // `"undefined"` or `"function"` in `typeof` checks
            isStringLiteral(left) ? isStringLiteral(right) && left.text === right.text : (
              // used in `typeof` checks for fallback
              isTypeOfExpression(left) ? isTypeOfExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : (
                // parens in `typeof` checks with temps
                isParenthesizedExpression(left) ? isParenthesizedExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : (
                  // conditionals used in fallback
                  isConditionalExpression(left) ? isConditionalExpression(right) && equateSerializedTypeNodes(left.condition, right.condition) && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : (
                    // logical binary and assignments used in fallback
                    isBinaryExpression(left) ? isBinaryExpression(right) && left.operatorToken.kind === right.operatorToken.kind && equateSerializedTypeNodes(left.left, right.left) && equateSerializedTypeNodes(left.right, right.right) : false
                  )
                )
              )
            )
          )
        )
      )
    );
  }
  function serializeTypeReferenceNode(node) {
    const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope ?? currentLexicalScope);
    switch (kind) {
      case 0 /* Unknown */:
        if (findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) {
          return factory2.createIdentifier("Object");
        }
        const serialized = serializeEntityNameAsExpressionFallback(node.typeName);
        const temp = factory2.createTempVariable(hoistVariableDeclaration);
        return factory2.createConditionalExpression(
          factory2.createTypeCheck(factory2.createAssignment(temp, serialized), "function"),
          /*questionToken*/
          void 0,
          temp,
          /*colonToken*/
          void 0,
          factory2.createIdentifier("Object")
        );
      case 1 /* TypeWithConstructSignatureAndValue */:
        return serializeEntityNameAsExpression(node.typeName);
      case 2 /* VoidNullableOrNeverType */:
        return factory2.createVoidZero();
      case 4 /* BigIntLikeType */:
        return getGlobalConstructor("BigInt", 7 /* ES2020 */);
      case 6 /* BooleanType */:
        return factory2.createIdentifier("Boolean");
      case 3 /* NumberLikeType */:
        return factory2.createIdentifier("Number");
      case 5 /* StringLikeType */:
        return factory2.createIdentifier("String");
      case 7 /* ArrayLikeType */:
        return factory2.createIdentifier("Array");
      case 8 /* ESSymbolType */:
        return getGlobalConstructor("Symbol", 2 /* ES2015 */);
      case 10 /* TypeWithCallSignature */:
        return factory2.createIdentifier("Function");
      case 9 /* Promise */:
        return factory2.createIdentifier("Promise");
      case 11 /* ObjectType */:
        return factory2.createIdentifier("Object");
      default:
        return Debug.assertNever(kind);
    }
  }
  function createCheckedValue(left, right) {
    return factory2.createLogicalAnd(
      factory2.createStrictInequality(factory2.createTypeOfExpression(left), factory2.createStringLiteral("undefined")),
      right
    );
  }
  function serializeEntityNameAsExpressionFallback(node) {
    if (node.kind === 80 /* Identifier */) {
      const copied = serializeEntityNameAsExpression(node);
      return createCheckedValue(copied, copied);
    }
    if (node.left.kind === 80 /* Identifier */) {
      return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
    }
    const left = serializeEntityNameAsExpressionFallback(node.left);
    const temp = factory2.createTempVariable(hoistVariableDeclaration);
    return factory2.createLogicalAnd(
      factory2.createLogicalAnd(
        left.left,
        factory2.createStrictInequality(factory2.createAssignment(temp, left.right), factory2.createVoidZero())
      ),
      factory2.createPropertyAccessExpression(temp, node.right)
    );
  }
  function serializeEntityNameAsExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        const name = setParent(setTextRange(parseNodeFactory.cloneNode(node), node), node.parent);
        name.original = void 0;
        setParent(name, getParseTreeNode(currentLexicalScope));
        return name;
      case 165 /* QualifiedName */:
        return serializeQualifiedNameAsExpression(node);
    }
  }
  function serializeQualifiedNameAsExpression(node) {
    return factory2.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right);
  }
  function getGlobalConstructorWithFallback(name) {
    return factory2.createConditionalExpression(
      factory2.createTypeCheck(factory2.createIdentifier(name), "function"),
      /*questionToken*/
      void 0,
      factory2.createIdentifier(name),
      /*colonToken*/
      void 0,
      factory2.createIdentifier("Object")
    );
  }
  function getGlobalConstructor(name, minLanguageVersion) {
    return languageVersion < minLanguageVersion ? getGlobalConstructorWithFallback(name) : factory2.createIdentifier(name);
  }
}

// src/compiler/transformers/legacyDecorators.ts
function transformLegacyDecorators(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    hoistVariableDeclaration
  } = context;
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onSubstituteNode = onSubstituteNode;
  let classAliases;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    const visited = visitEachChild(node, visitor, context);
    addEmitHelpers(visited, context.readEmitHelpers());
    return visited;
  }
  function modifierVisitor(node) {
    return isDecorator(node) ? void 0 : node;
  }
  function visitor(node) {
    if (!(node.transformFlags & 33554432 /* ContainsDecorators */)) {
      return node;
    }
    switch (node.kind) {
      case 169 /* Decorator */:
        return void 0;
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 230 /* ClassExpression */:
        return visitClassExpression(node);
      case 175 /* Constructor */:
        return visitConstructorDeclaration(node);
      case 173 /* MethodDeclaration */:
        return visitMethodDeclaration(node);
      case 177 /* SetAccessor */:
        return visitSetAccessorDeclaration(node);
      case 176 /* GetAccessor */:
        return visitGetAccessorDeclaration(node);
      case 171 /* PropertyDeclaration */:
        return visitPropertyDeclaration(node);
      case 168 /* Parameter */:
        return visitParameterDeclaration(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitClassDeclaration(node) {
    if (!(classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      true,
      node
    ) || childIsDecorated(
      /*useLegacyDecorators*/
      true,
      node
    ))) {
      return visitEachChild(node, visitor, context);
    }
    const statements = classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      true,
      node
    ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name);
    return singleOrMany(statements);
  }
  function decoratorContainsPrivateIdentifierInExpression(decorator) {
    return !!(decorator.transformFlags & 536870912 /* ContainsPrivateIdentifierInExpression */);
  }
  function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) {
    return some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression);
  }
  function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) {
    for (const member of node.members) {
      if (!canHaveDecorators(member))
        continue;
      const allDecorators = getAllDecoratorsOfClassElement(
        member,
        node,
        /*useLegacyDecorators*/
        true
      );
      if (some(allDecorators == null ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression))
        return true;
      if (some(allDecorators == null ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression))
        return true;
    }
    return false;
  }
  function transformDecoratorsOfClassElements(node, members) {
    let decorationStatements = [];
    addClassElementDecorationStatements(
      decorationStatements,
      node,
      /*isStatic*/
      false
    );
    addClassElementDecorationStatements(
      decorationStatements,
      node,
      /*isStatic*/
      true
    );
    if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) {
      members = setTextRange(factory2.createNodeArray([
        ...members,
        factory2.createClassStaticBlockDeclaration(
          factory2.createBlock(
            decorationStatements,
            /*multiLine*/
            true
          )
        )
      ]), members);
      decorationStatements = void 0;
    }
    return { decorationStatements, members };
  }
  function transformClassDeclarationWithoutClassDecorators(node, name) {
    const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
    const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause);
    let members = visitNodes2(node.members, visitor, isClassElement);
    let decorationStatements = [];
    ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members));
    const updated = factory2.updateClassDeclaration(
      node,
      modifiers,
      name,
      /*typeParameters*/
      void 0,
      heritageClauses,
      members
    );
    return addRange([updated], decorationStatements);
  }
  function transformClassDeclarationWithClassDecorators(node, name) {
    const isExport = hasSyntacticModifier(node, 1 /* Export */);
    const isDefault = hasSyntacticModifier(node, 1024 /* Default */);
    const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike);
    const location = moveRangePastModifiers(node);
    const classAlias = getClassAliasIfNeeded(node);
    const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    ) : factory2.getLocalName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    );
    const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause);
    let members = visitNodes2(node.members, visitor, isClassElement);
    let decorationStatements = [];
    ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members));
    const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */) || isClassStaticBlockDeclaration(member));
    if (assignClassAliasInStaticBlock) {
      members = setTextRange(factory2.createNodeArray([
        factory2.createClassStaticBlockDeclaration(
          factory2.createBlock([
            factory2.createExpressionStatement(
              factory2.createAssignment(classAlias, factory2.createThis())
            )
          ])
        ),
        ...members
      ]), members);
    }
    const classExpression = factory2.createClassExpression(
      modifiers,
      name && isGeneratedIdentifier(name) ? void 0 : name,
      /*typeParameters*/
      void 0,
      heritageClauses,
      members
    );
    setOriginalNode(classExpression, node);
    setTextRange(classExpression, location);
    const varDecl = factory2.createVariableDeclaration(
      declName,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression
    );
    setOriginalNode(varDecl, node);
    let varModifiers;
    if (isExport && !isDefault) {
      varModifiers = factory2.createModifiersFromModifierFlags(1 /* Export */);
    }
    const statement = factory2.createVariableStatement(
      varModifiers,
      factory2.createVariableDeclarationList([
        varDecl
      ], 1 /* Let */)
    );
    setOriginalNode(statement, node);
    setTextRange(statement, location);
    setCommentRange(statement, node);
    const statements = [statement];
    addRange(statements, decorationStatements);
    addConstructorDecorationStatement(statements, node);
    if (isExport && isDefault) {
      statements.push(factory2.createExportAssignment(
        /*modifiers*/
        void 0,
        /*isExportEquals*/
        false,
        declName
      ));
    }
    return statements;
  }
  function visitClassExpression(node) {
    return factory2.updateClassExpression(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      node.name,
      /*typeParameters*/
      void 0,
      visitNodes2(node.heritageClauses, visitor, isHeritageClause),
      visitNodes2(node.members, visitor, isClassElement)
    );
  }
  function visitConstructorDeclaration(node) {
    return factory2.updateConstructorDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      visitNodes2(node.parameters, visitor, isParameter),
      visitNode(node.body, visitor, isBlock)
    );
  }
  function finishClassElement(updated, original) {
    if (updated !== original) {
      setCommentRange(updated, original);
      setSourceMapRange(updated, moveRangePastModifiers(original));
    }
    return updated;
  }
  function visitMethodDeclaration(node) {
    return finishClassElement(factory2.updateMethodDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      node.asteriskToken,
      Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)),
      /*questionToken*/
      void 0,
      /*typeParameters*/
      void 0,
      visitNodes2(node.parameters, visitor, isParameter),
      /*type*/
      void 0,
      visitNode(node.body, visitor, isBlock)
    ), node);
  }
  function visitGetAccessorDeclaration(node) {
    return finishClassElement(factory2.updateGetAccessorDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)),
      visitNodes2(node.parameters, visitor, isParameter),
      /*type*/
      void 0,
      visitNode(node.body, visitor, isBlock)
    ), node);
  }
  function visitSetAccessorDeclaration(node) {
    return finishClassElement(factory2.updateSetAccessorDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)),
      visitNodes2(node.parameters, visitor, isParameter),
      visitNode(node.body, visitor, isBlock)
    ), node);
  }
  function visitPropertyDeclaration(node) {
    if (node.flags & 16777216 /* Ambient */ || hasSyntacticModifier(node, 2 /* Ambient */)) {
      return void 0;
    }
    return finishClassElement(factory2.updatePropertyDeclaration(
      node,
      visitNodes2(node.modifiers, modifierVisitor, isModifier),
      Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)),
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    ), node);
  }
  function visitParameterDeclaration(node) {
    const updated = factory2.updateParameterDeclaration(
      node,
      elideNodes(factory2, node.modifiers),
      node.dotDotDotToken,
      Debug.checkDefined(visitNode(node.name, visitor, isBindingName)),
      /*questionToken*/
      void 0,
      /*type*/
      void 0,
      visitNode(node.initializer, visitor, isExpression)
    );
    if (updated !== node) {
      setCommentRange(updated, node);
      setTextRange(updated, moveRangePastModifiers(node));
      setSourceMapRange(updated, moveRangePastModifiers(node));
      setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */);
    }
    return updated;
  }
  function isSyntheticMetadataDecorator(node) {
    return isCallToHelper(node.expression, "___metadata");
  }
  function transformAllDecoratorsOfDeclaration(allDecorators) {
    if (!allDecorators) {
      return void 0;
    }
    const { false: decorators, true: metadata } = groupBy(allDecorators.decorators, isSyntheticMetadataDecorator);
    const decoratorExpressions = [];
    addRange(decoratorExpressions, map(decorators, transformDecorator));
    addRange(decoratorExpressions, flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
    addRange(decoratorExpressions, map(metadata, transformDecorator));
    return decoratorExpressions;
  }
  function addClassElementDecorationStatements(statements, node, isStatic2) {
    addRange(statements, map(generateClassElementDecorationExpressions(node, isStatic2), (expr) => factory2.createExpressionStatement(expr)));
  }
  function isDecoratedClassElement(member, isStaticElement, parent2) {
    return nodeOrChildIsDecorated(
      /*useLegacyDecorators*/
      true,
      member,
      parent2
    ) && isStaticElement === isStatic(member);
  }
  function getDecoratedClassElements(node, isStatic2) {
    return filter(node.members, (m) => isDecoratedClassElement(m, isStatic2, node));
  }
  function generateClassElementDecorationExpressions(node, isStatic2) {
    const members = getDecoratedClassElements(node, isStatic2);
    let expressions;
    for (const member of members) {
      expressions = append(expressions, generateClassElementDecorationExpression(node, member));
    }
    return expressions;
  }
  function generateClassElementDecorationExpression(node, member) {
    const allDecorators = getAllDecoratorsOfClassElement(
      member,
      node,
      /*useLegacyDecorators*/
      true
    );
    const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators);
    if (!decoratorExpressions) {
      return void 0;
    }
    const prefix = getClassMemberPrefix(node, member);
    const memberName = getExpressionForPropertyName(
      member,
      /*generateNameForComputedPropertyName*/
      !hasSyntacticModifier(member, 2 /* Ambient */)
    );
    const descriptor = languageVersion > 0 /* ES3 */ ? isPropertyDeclaration(member) && !hasAccessorModifier(member) ? factory2.createVoidZero() : factory2.createNull() : void 0;
    const helper = emitHelpers().createDecorateHelper(
      decoratorExpressions,
      prefix,
      memberName,
      descriptor
    );
    setEmitFlags(helper, 3072 /* NoComments */);
    setSourceMapRange(helper, moveRangePastModifiers(member));
    return helper;
  }
  function addConstructorDecorationStatement(statements, node) {
    const expression = generateConstructorDecorationExpression(node);
    if (expression) {
      statements.push(setOriginalNode(factory2.createExpressionStatement(expression), node));
    }
  }
  function generateConstructorDecorationExpression(node) {
    const allDecorators = getAllDecoratorsOfClass(node);
    const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators);
    if (!decoratorExpressions) {
      return void 0;
    }
    const classAlias = classAliases && classAliases[getOriginalNodeId(node)];
    const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    ) : factory2.getDeclarationName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      true
    );
    const decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName);
    const expression = factory2.createAssignment(localName, classAlias ? factory2.createAssignment(classAlias, decorate) : decorate);
    setEmitFlags(expression, 3072 /* NoComments */);
    setSourceMapRange(expression, moveRangePastModifiers(node));
    return expression;
  }
  function transformDecorator(decorator) {
    return Debug.checkDefined(visitNode(decorator.expression, visitor, isExpression));
  }
  function transformDecoratorsOfParameter(decorators, parameterOffset) {
    let expressions;
    if (decorators) {
      expressions = [];
      for (const decorator of decorators) {
        const helper = emitHelpers().createParamHelper(
          transformDecorator(decorator),
          parameterOffset
        );
        setTextRange(helper, decorator.expression);
        setEmitFlags(helper, 3072 /* NoComments */);
        expressions.push(helper);
      }
    }
    return expressions;
  }
  function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
    const name = member.name;
    if (isPrivateIdentifier(name)) {
      return factory2.createIdentifier("");
    } else if (isComputedPropertyName(name)) {
      return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression) ? factory2.getGeneratedNameForNode(name) : name.expression;
    } else if (isIdentifier(name)) {
      return factory2.createStringLiteral(idText(name));
    } else {
      return factory2.cloneNode(name);
    }
  }
  function enableSubstitutionForClassAliases() {
    if (!classAliases) {
      context.enableSubstitution(80 /* Identifier */);
      classAliases = [];
    }
  }
  function getClassAliasIfNeeded(node) {
    if (resolver.getNodeCheckFlags(node) & 1048576 /* ClassWithConstructorReference */) {
      enableSubstitutionForClassAliases();
      const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default");
      classAliases[getOriginalNodeId(node)] = classAlias;
      hoistVariableDeclaration(classAlias);
      return classAlias;
    }
  }
  function getClassPrototype(node) {
    return factory2.createPropertyAccessExpression(factory2.getDeclarationName(node), "prototype");
  }
  function getClassMemberPrefix(node, member) {
    return isStatic(member) ? factory2.getDeclarationName(node) : getClassPrototype(node);
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return substituteExpressionIdentifier(node);
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    return trySubstituteClassAlias(node) ?? node;
  }
  function trySubstituteClassAlias(node) {
    if (classAliases) {
      if (resolver.getNodeCheckFlags(node) & 2097152 /* ConstructorReferenceInClass */) {
        const declaration = resolver.getReferencedValueDeclaration(node);
        if (declaration) {
          const classAlias = classAliases[declaration.id];
          if (classAlias) {
            const clone2 = factory2.cloneNode(classAlias);
            setSourceMapRange(clone2, node);
            setCommentRange(clone2, node);
            return clone2;
          }
        }
      }
    }
    return void 0;
  }
}

// src/compiler/transformers/esDecorators.ts
function transformESDecorators(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    startLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  let top;
  let classInfo;
  let classThis;
  let classSuper;
  let pendingExpressions;
  let shouldTransformPrivateStaticElementsInFile;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    top = void 0;
    shouldTransformPrivateStaticElementsInFile = false;
    const visited = visitEachChild(node, visitor, context);
    addEmitHelpers(visited, context.readEmitHelpers());
    if (shouldTransformPrivateStaticElementsInFile) {
      addInternalEmitFlags(visited, 32 /* TransformPrivateStaticElements */);
      shouldTransformPrivateStaticElementsInFile = false;
    }
    return visited;
  }
  function updateState() {
    classInfo = void 0;
    classThis = void 0;
    classSuper = void 0;
    switch (top == null ? void 0 : top.kind) {
      case "class":
        classInfo = top.classInfo;
        break;
      case "class-element":
        classInfo = top.next.classInfo;
        classThis = top.classThis;
        classSuper = top.classSuper;
        break;
      case "name":
        const grandparent = top.next.next.next;
        if ((grandparent == null ? void 0 : grandparent.kind) === "class-element") {
          classInfo = grandparent.next.classInfo;
          classThis = grandparent.classThis;
          classSuper = grandparent.classSuper;
        }
        break;
    }
  }
  function enterClass(classInfo2) {
    top = { kind: "class", next: top, classInfo: classInfo2, savedPendingExpressions: pendingExpressions };
    pendingExpressions = void 0;
    updateState();
  }
  function exitClass() {
    Debug.assert((top == null ? void 0 : top.kind) === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top == null ? void 0 : top.kind}' instead.`);
    pendingExpressions = top.savedPendingExpressions;
    top = top.next;
    updateState();
  }
  function enterClassElement(node) {
    var _a, _b;
    Debug.assert((top == null ? void 0 : top.kind) === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top == null ? void 0 : top.kind}' instead.`);
    top = { kind: "class-element", next: top };
    if (isClassStaticBlockDeclaration(node) || isPropertyDeclaration(node) && hasStaticModifier(node)) {
      top.classThis = (_a = top.next.classInfo) == null ? void 0 : _a.classThis;
      top.classSuper = (_b = top.next.classInfo) == null ? void 0 : _b.classSuper;
    }
    updateState();
  }
  function exitClassElement() {
    var _a;
    Debug.assert((top == null ? void 0 : top.kind) === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top == null ? void 0 : top.kind}' instead.`);
    Debug.assert(((_a = top.next) == null ? void 0 : _a.kind) === "class", "Incorrect value for top.next.kind.", () => {
      var _a2;
      return `Expected top.next.kind to be 'class' but got '${(_a2 = top.next) == null ? void 0 : _a2.kind}' instead.`;
    });
    top = top.next;
    updateState();
  }
  function enterName() {
    Debug.assert((top == null ? void 0 : top.kind) === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top == null ? void 0 : top.kind}' instead.`);
    top = { kind: "name", next: top };
    updateState();
  }
  function exitName() {
    Debug.assert((top == null ? void 0 : top.kind) === "name", "Incorrect value for top.kind.", () => `Expected top.kind to be 'name' but got '${top == null ? void 0 : top.kind}' instead.`);
    top = top.next;
    updateState();
  }
  function enterOther() {
    if ((top == null ? void 0 : top.kind) === "other") {
      Debug.assert(!pendingExpressions);
      top.depth++;
    } else {
      top = { kind: "other", next: top, depth: 0, savedPendingExpressions: pendingExpressions };
      pendingExpressions = void 0;
      updateState();
    }
  }
  function exitOther() {
    Debug.assert((top == null ? void 0 : top.kind) === "other", "Incorrect value for top.kind.", () => `Expected top.kind to be 'other' but got '${top == null ? void 0 : top.kind}' instead.`);
    if (top.depth > 0) {
      Debug.assert(!pendingExpressions);
      top.depth--;
    } else {
      pendingExpressions = top.savedPendingExpressions;
      top = top.next;
      updateState();
    }
  }
  function shouldVisitNode(node) {
    return !!(node.transformFlags & 33554432 /* ContainsDecorators */) || !!classThis && !!(node.transformFlags & 16384 /* ContainsLexicalThis */) || !!classThis && !!classSuper && !!(node.transformFlags & 134217728 /* ContainsLexicalSuper */);
  }
  function visitor(node) {
    if (!shouldVisitNode(node)) {
      return node;
    }
    switch (node.kind) {
      case 169 /* Decorator */:
        return Debug.fail("Use `modifierVisitor` instead.");
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 230 /* ClassExpression */:
        return visitClassExpression(
          node,
          /*referencedName*/
          void 0
        );
      case 175 /* Constructor */:
      case 171 /* PropertyDeclaration */:
      case 174 /* ClassStaticBlockDeclaration */:
        return Debug.fail("Not supported outside of a class. Use 'classElementVisitor' instead.");
      case 168 /* Parameter */:
        return visitParameterDeclaration(node);
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          false
        );
      case 302 /* PropertyAssignment */:
        return visitPropertyAssignment(node);
      case 259 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 207 /* BindingElement */:
        return visitBindingElement(node);
      case 276 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 110 /* ThisKeyword */:
        return visitThisExpression(node);
      case 247 /* ForStatement */:
        return visitForStatement(node);
      case 243 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 360 /* CommaListExpression */:
        return visitCommaListExpression(
          node,
          /*discarded*/
          false
        );
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          false,
          /*referencedName*/
          void 0
        );
      case 359 /* PartiallyEmittedExpression */:
        return visitPartiallyEmittedExpression(
          node,
          /*discarded*/
          false,
          /*referencedName*/
          void 0
        );
      case 212 /* CallExpression */:
        return visitCallExpression(node);
      case 214 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 223 /* PrefixUnaryExpression */:
      case 224 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          false
        );
      case 210 /* PropertyAccessExpression */:
        return visitPropertyAccessExpression(node);
      case 211 /* ElementAccessExpression */:
        return visitElementAccessExpression(node);
      case 166 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      case 173 /* MethodDeclaration */:
      case 177 /* SetAccessor */:
      case 176 /* GetAccessor */:
      case 217 /* FunctionExpression */:
      case 261 /* FunctionDeclaration */: {
        enterOther();
        const result = visitEachChild(node, fallbackVisitor, context);
        exitOther();
        return result;
      }
      default:
        return visitEachChild(node, fallbackVisitor, context);
    }
  }
  function fallbackVisitor(node) {
    switch (node.kind) {
      case 169 /* Decorator */:
        return void 0;
      default:
        return visitor(node);
    }
  }
  function modifierVisitor(node) {
    switch (node.kind) {
      case 169 /* Decorator */:
        return void 0;
      default:
        return node;
    }
  }
  function classElementVisitor(node) {
    switch (node.kind) {
      case 175 /* Constructor */:
        return visitConstructorDeclaration(node);
      case 173 /* MethodDeclaration */:
        return visitMethodDeclaration(node);
      case 176 /* GetAccessor */:
        return visitGetAccessorDeclaration(node);
      case 177 /* SetAccessor */:
        return visitSetAccessorDeclaration(node);
      case 171 /* PropertyDeclaration */:
        return visitPropertyDeclaration(node);
      case 174 /* ClassStaticBlockDeclaration */:
        return visitClassStaticBlockDeclaration(node);
      default:
        return visitor(node);
    }
  }
  function namedEvaluationVisitor(node, referencedName) {
    switch (node.kind) {
      case 359 /* PartiallyEmittedExpression */:
        return visitPartiallyEmittedExpression(
          node,
          /*discarded*/
          false,
          referencedName
        );
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          false,
          referencedName
        );
      case 230 /* ClassExpression */:
        return visitClassExpression(node, referencedName);
      default:
        return visitor(node);
    }
  }
  function discardedValueVisitor(node) {
    switch (node.kind) {
      case 223 /* PrefixUnaryExpression */:
      case 224 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          true
        );
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          true
        );
      case 360 /* CommaListExpression */:
        return visitCommaListExpression(
          node,
          /*discarded*/
          true
        );
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          true,
          /*referencedName*/
          void 0
        );
      default:
        return visitor(node);
    }
  }
  function getHelperVariableName(node) {
    let declarationName = node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : node.name && isPrivateIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name).slice(1) : node.name && isStringLiteral(node.name) && isIdentifierText(node.name.text, 99 /* ESNext */) ? node.name.text : isClassLike(node) ? "class" : "member";
    if (isGetAccessor(node))
      declarationName = `get_${declarationName}`;
    if (isSetAccessor(node))
      declarationName = `set_${declarationName}`;
    if (node.name && isPrivateIdentifier(node.name))
      declarationName = `private_${declarationName}`;
    if (isStatic(node))
      declarationName = `static_${declarationName}`;
    return "_" + declarationName;
  }
  function createHelperVariable(node, suffix) {
    return factory2.createUniqueName(`${getHelperVariableName(node)}_${suffix}`, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */);
  }
  function createLet(name, initializer) {
    return factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      factory2.createVariableDeclarationList([
        factory2.createVariableDeclaration(
          name,
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          initializer
        )
      ], 1 /* Let */)
    );
  }
  function createClassInfo(node) {
    let instanceExtraInitializersName;
    let staticExtraInitializersName;
    let hasStaticInitializers = false;
    let hasNonAmbientInstanceFields = false;
    let hasStaticPrivateClassElements = false;
    for (const member of node.members) {
      if (isNamedClassElement(member) && nodeOrChildIsDecorated(
        /*useLegacyDecorators*/
        false,
        member,
        node
      )) {
        if (hasStaticModifier(member)) {
          staticExtraInitializersName ?? (staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */));
        } else {
          instanceExtraInitializersName ?? (instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */));
        }
      }
      if (isClassStaticBlockDeclaration(member)) {
        hasStaticInitializers = true;
      } else if (isPropertyDeclaration(member)) {
        if (hasStaticModifier(member)) {
          hasStaticInitializers || (hasStaticInitializers = !!member.initializer || hasDecorators(member));
        } else {
          hasNonAmbientInstanceFields || (hasNonAmbientInstanceFields = !isAmbientPropertyDeclaration(member));
        }
      }
      if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) {
        hasStaticPrivateClassElements = true;
      }
      if (staticExtraInitializersName && instanceExtraInitializersName && hasStaticInitializers && hasNonAmbientInstanceFields && hasStaticPrivateClassElements) {
        break;
      }
    }
    return {
      class: node,
      instanceExtraInitializersName,
      staticExtraInitializersName,
      hasStaticInitializers,
      hasNonAmbientInstanceFields,
      hasStaticPrivateClassElements
    };
  }
  function containsLexicalSuperInStaticInitializer(node) {
    for (const member of node.members) {
      if (isClassStaticBlockDeclaration(member) || isPropertyDeclaration(member) && hasStaticModifier(member)) {
        if (member.transformFlags & 134217728 /* ContainsLexicalSuper */) {
          return true;
        }
      }
    }
    return false;
  }
  function transformClassLike(node, className) {
    var _a;
    startLexicalEnvironment();
    const classReference = factory2.getLocalName(
      node,
      /*allowComments*/
      false,
      /*allowSourceMaps*/
      false,
      /*ignoreAssignedName*/
      true
    );
    const classInfo2 = createClassInfo(node);
    const classDefinitionStatements = [];
    let leadingBlockStatements;
    let trailingBlockStatements;
    let syntheticConstructor;
    let heritageClauses;
    let shouldTransformPrivateStaticElementsInClass = false;
    const classDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClass(node));
    if (classDecorators) {
      classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 16 /* Optimistic */);
      classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */);
      classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 16 /* Optimistic */);
      classInfo2.classThis = factory2.createUniqueName("_classThis", 16 /* Optimistic */);
      classDefinitionStatements.push(
        createLet(classInfo2.classDecoratorsName, factory2.createArrayLiteralExpression(classDecorators)),
        createLet(classInfo2.classDescriptorName),
        createLet(classInfo2.classExtraInitializersName, factory2.createArrayLiteralExpression()),
        createLet(classInfo2.classThis)
      );
      if (classInfo2.hasStaticPrivateClassElements) {
        shouldTransformPrivateStaticElementsInClass = true;
        shouldTransformPrivateStaticElementsInFile = true;
      }
    }
    if (classDecorators && containsLexicalSuperInStaticInitializer(node)) {
      const extendsClause = getHeritageClause(node.heritageClauses, 96 /* ExtendsKeyword */);
      const extendsElement = extendsClause && firstOrUndefined(extendsClause.types);
      const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression);
      if (extendsExpression) {
        classInfo2.classSuper = factory2.createUniqueName("_classSuper", 16 /* Optimistic */);
        const unwrapped = skipOuterExpressions(extendsExpression);
        const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || isFunctionExpression(unwrapped) && !unwrapped.name || isArrowFunction(unwrapped) ? factory2.createComma(factory2.createNumericLiteral(0), extendsExpression) : extendsExpression;
        classDefinitionStatements.push(createLet(classInfo2.classSuper, safeExtendsExpression));
        const updatedExtendsElement = factory2.updateExpressionWithTypeArguments(
          extendsElement,
          classInfo2.classSuper,
          /*typeArguments*/
          void 0
        );
        const updatedExtendsClause = factory2.updateHeritageClause(extendsClause, [updatedExtendsElement]);
        heritageClauses = factory2.createNodeArray([updatedExtendsClause]);
      }
    } else {
      heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause);
    }
    const renamedClassThis = classInfo2.classThis ?? factory2.createThis();
    const needsSetNameHelper = !((_a = getOriginalNode(node, isClassLike)) == null ? void 0 : _a.name) && (classDecorators || !isStringLiteral(className) || !isEmptyStringLiteral(className));
    if (needsSetNameHelper) {
      const setNameExpr = emitHelpers().createSetFunctionNameHelper(factory2.createThis(), className);
      leadingBlockStatements = append(leadingBlockStatements, factory2.createExpressionStatement(setNameExpr));
    }
    enterClass(classInfo2);
    let members = visitNodes2(node.members, classElementVisitor, isClassElement);
    if (pendingExpressions) {
      let outerThis;
      for (let expression of pendingExpressions) {
        expression = visitNode(expression, function thisVisitor(node2) {
          if (!(node2.transformFlags & 16384 /* ContainsLexicalThis */)) {
            return node2;
          }
          switch (node2.kind) {
            case 110 /* ThisKeyword */:
              if (!outerThis) {
                outerThis = factory2.createUniqueName("_outerThis", 16 /* Optimistic */);
                classDefinitionStatements.unshift(createLet(outerThis, factory2.createThis()));
              }
              return outerThis;
            default:
              return visitEachChild(node2, thisVisitor, context);
          }
        }, isExpression);
        const statement = factory2.createExpressionStatement(expression);
        leadingBlockStatements = append(leadingBlockStatements, statement);
      }
      pendingExpressions = void 0;
    }
    exitClass();
    if (classInfo2.instanceExtraInitializersName && !getFirstConstructorWithBody(node)) {
      const initializerStatements = prepareConstructor(node, classInfo2);
      if (initializerStatements) {
        const extendsClauseElement = getEffectiveBaseTypeNode(node);
        const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */);
        const constructorStatements = [];
        if (isDerivedClass) {
          const spreadArguments = factory2.createSpreadElement(factory2.createIdentifier("arguments"));
          const superCall = factory2.createCallExpression(
            factory2.createSuper(),
            /*typeArguments*/
            void 0,
            [spreadArguments]
          );
          constructorStatements.push(factory2.createExpressionStatement(superCall));
        }
        addRange(constructorStatements, initializerStatements);
        const constructorBody = factory2.createBlock(
          constructorStatements,
          /*multiLine*/
          true
        );
        syntheticConstructor = factory2.createConstructorDeclaration(
          /*modifiers*/
          void 0,
          [],
          constructorBody
        );
      }
    }
    if (classInfo2.staticExtraInitializersName) {
      classDefinitionStatements.push(
        createLet(classInfo2.staticExtraInitializersName, factory2.createArrayLiteralExpression())
      );
    }
    if (classInfo2.instanceExtraInitializersName) {
      classDefinitionStatements.push(
        createLet(classInfo2.instanceExtraInitializersName, factory2.createArrayLiteralExpression())
      );
    }
    if (classInfo2.memberInfos) {
      forEachEntry(classInfo2.memberInfos, (memberInfo, member) => {
        if (isStatic(member)) {
          classDefinitionStatements.push(createLet(memberInfo.memberDecoratorsName));
          if (memberInfo.memberInitializersName) {
            classDefinitionStatements.push(createLet(memberInfo.memberInitializersName, factory2.createArrayLiteralExpression()));
          }
          if (memberInfo.memberDescriptorName) {
            classDefinitionStatements.push(createLet(memberInfo.memberDescriptorName));
          }
        }
      });
    }
    if (classInfo2.memberInfos) {
      forEachEntry(classInfo2.memberInfos, (memberInfo, member) => {
        if (!isStatic(member)) {
          classDefinitionStatements.push(createLet(memberInfo.memberDecoratorsName));
          if (memberInfo.memberInitializersName) {
            classDefinitionStatements.push(createLet(memberInfo.memberInitializersName, factory2.createArrayLiteralExpression()));
          }
          if (memberInfo.memberDescriptorName) {
            classDefinitionStatements.push(createLet(memberInfo.memberDescriptorName));
          }
        }
      });
    }
    leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.staticNonFieldDecorationStatements);
    leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.nonStaticNonFieldDecorationStatements);
    leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.staticFieldDecorationStatements);
    leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.nonStaticFieldDecorationStatements);
    if (classInfo2.classDescriptorName && classInfo2.classDecoratorsName && classInfo2.classExtraInitializersName && classInfo2.classThis) {
      leadingBlockStatements ?? (leadingBlockStatements = []);
      const valueProperty = factory2.createPropertyAssignment("value", factory2.createThis());
      const classDescriptor = factory2.createObjectLiteralExpression([valueProperty]);
      const classDescriptorAssignment = factory2.createAssignment(classInfo2.classDescriptorName, classDescriptor);
      const classNameReference = factory2.createPropertyAccessExpression(factory2.createThis(), "name");
      const esDecorateHelper2 = emitHelpers().createESDecorateHelper(
        factory2.createNull(),
        classDescriptorAssignment,
        classInfo2.classDecoratorsName,
        { kind: "class", name: classNameReference },
        factory2.createNull(),
        classInfo2.classExtraInitializersName
      );
      const esDecorateStatement = factory2.createExpressionStatement(esDecorateHelper2);
      setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node));
      leadingBlockStatements.push(esDecorateStatement);
      const classDescriptorValueReference = factory2.createPropertyAccessExpression(classInfo2.classDescriptorName, "value");
      const classThisAssignment = factory2.createAssignment(classInfo2.classThis, classDescriptorValueReference);
      const classReferenceAssignment = factory2.createAssignment(classReference, classThisAssignment);
      leadingBlockStatements.push(factory2.createExpressionStatement(classReferenceAssignment));
    }
    if (classInfo2.staticExtraInitializersName) {
      const runStaticInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.staticExtraInitializersName);
      const runStaticInitializersStatement = factory2.createExpressionStatement(runStaticInitializersHelper);
      setSourceMapRange(runStaticInitializersStatement, node.name ?? moveRangePastDecorators(node));
      leadingBlockStatements = append(leadingBlockStatements, runStaticInitializersStatement);
    }
    if (classInfo2.classExtraInitializersName) {
      const runClassInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.classExtraInitializersName);
      const runClassInitializersStatement = factory2.createExpressionStatement(runClassInitializersHelper);
      setSourceMapRange(runClassInitializersStatement, node.name ?? moveRangePastDecorators(node));
      trailingBlockStatements = append(trailingBlockStatements, runClassInitializersStatement);
    }
    if (leadingBlockStatements && trailingBlockStatements && !classInfo2.hasStaticInitializers) {
      addRange(leadingBlockStatements, trailingBlockStatements);
      trailingBlockStatements = void 0;
    }
    let newMembers = members;
    if (leadingBlockStatements) {
      const leadingStaticBlockBody = factory2.createBlock(
        leadingBlockStatements,
        /*multiLine*/
        true
      );
      const leadingStaticBlock = factory2.createClassStaticBlockDeclaration(leadingStaticBlockBody);
      if (shouldTransformPrivateStaticElementsInClass) {
        setInternalEmitFlags(leadingStaticBlock, 32 /* TransformPrivateStaticElements */);
      }
      newMembers = [leadingStaticBlock, ...newMembers];
    }
    if (syntheticConstructor) {
      newMembers = [...newMembers, syntheticConstructor];
    }
    if (trailingBlockStatements) {
      const trailingStaticBlockBody = factory2.createBlock(
        trailingBlockStatements,
        /*multiLine*/
        true
      );
      const trailingStaticBlock = factory2.createClassStaticBlockDeclaration(trailingStaticBlockBody);
      newMembers = [...newMembers, trailingStaticBlock];
    }
    if (newMembers !== members) {
      members = setTextRange(factory2.createNodeArray(newMembers), members);
    }
    const lexicalEnvironment = endLexicalEnvironment();
    let classExpression;
    if (classDecorators) {
      classExpression = factory2.createClassExpression(
        /*modifiers*/
        void 0,
        /*name*/
        void 0,
        /*typeParameters*/
        void 0,
        heritageClauses,
        members
      );
      const classReferenceDeclaration = factory2.createVariableDeclaration(
        classReference,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        classExpression
      );
      const classReferenceVarDeclList = factory2.createVariableDeclarationList([classReferenceDeclaration]);
      const returnExpr = classInfo2.classThis ? factory2.createAssignment(classReference, classInfo2.classThis) : classReference;
      classDefinitionStatements.push(
        factory2.createVariableStatement(
          /*modifiers*/
          void 0,
          classReferenceVarDeclList
        ),
        factory2.createReturnStatement(returnExpr)
      );
    } else {
      classExpression = factory2.createClassExpression(
        /*modifiers*/
        void 0,
        node.name,
        /*typeParameters*/
        void 0,
        heritageClauses,
        members
      );
      classDefinitionStatements.push(factory2.createReturnStatement(classExpression));
    }
    if (shouldTransformPrivateStaticElementsInClass) {
      addInternalEmitFlags(classExpression, 32 /* TransformPrivateStaticElements */);
      for (const member of classExpression.members) {
        if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) {
          addInternalEmitFlags(member, 32 /* TransformPrivateStaticElements */);
        }
      }
    }
    setOriginalNode(classExpression, node);
    getOrCreateEmitNode(classExpression).classThis = classInfo2.classThis;
    return factory2.createImmediatelyInvokedArrowFunction(factory2.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment));
  }
  function isDecoratedClassLike(node) {
    return classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    ) || childIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    );
  }
  function visitClassDeclaration(node) {
    if (isDecoratedClassLike(node)) {
      if (hasSyntacticModifier(node, 1 /* Export */) && hasSyntacticModifier(node, 1024 /* Default */)) {
        const originalClass = getOriginalNode(node, isClassLike) ?? node;
        const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default");
        const iife = transformClassLike(node, className);
        const statement = factory2.createExportDefault(iife);
        setOriginalNode(statement, node);
        setCommentRange(statement, getCommentRange(node));
        setSourceMapRange(statement, moveRangePastDecorators(node));
        return statement;
      } else {
        Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name.");
        const iife = transformClassLike(node, factory2.createStringLiteralFromNode(node.name));
        const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
        const declName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName(
          node,
          /*allowComments*/
          false,
          /*allowSourceMaps*/
          true
        ) : factory2.getLocalName(
          node,
          /*allowComments*/
          false,
          /*allowSourceMaps*/
          true
        );
        const varDecl = factory2.createVariableDeclaration(
          declName,
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          iife
        );
        setOriginalNode(varDecl, node);
        const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */);
        const statement = factory2.createVariableStatement(modifiers, varDecls);
        setOriginalNode(statement, node);
        setCommentRange(statement, getCommentRange(node));
        return statement;
      }
    } else {
      const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
      const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause);
      enterClass(
        /*classInfo*/
        void 0
      );
      const members = visitNodes2(node.members, classElementVisitor, isClassElement);
      exitClass();
      return factory2.updateClassDeclaration(
        node,
        modifiers,
        node.name,
        /*typeParameters*/
        void 0,
        heritageClauses,
        members
      );
    }
  }
  function visitClassExpression(node, referencedName) {
    if (isDecoratedClassLike(node)) {
      const className = node.name ? factory2.createStringLiteralFromNode(node.name) : referencedName ?? factory2.createStringLiteral("");
      const iife = transformClassLike(node, className);
      setOriginalNode(iife, node);
      return iife;
    } else {
      const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
      const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause);
      enterClass(
        /*classInfo*/
        void 0
      );
      const members = visitNodes2(node.members, classElementVisitor, isClassElement);
      exitClass();
      return factory2.updateClassExpression(
        node,
        modifiers,
        node.name,
        /*typeParameters*/
        void 0,
        heritageClauses,
        members
      );
    }
  }
  function prepareConstructor(_parent, classInfo2) {
    if (classInfo2.instanceExtraInitializersName && !classInfo2.hasNonAmbientInstanceFields) {
      const statements = [];
      statements.push(
        factory2.createExpressionStatement(
          emitHelpers().createRunInitializersHelper(
            factory2.createThis(),
            classInfo2.instanceExtraInitializersName
          )
        )
      );
      return statements;
    }
  }
  function visitConstructorDeclaration(node) {
    enterClassElement(node);
    const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
    const parameters = visitNodes2(node.parameters, visitor, isParameter);
    let body;
    if (node.body && classInfo) {
      const initializerStatements = prepareConstructor(classInfo.class, classInfo);
      if (initializerStatements) {
        const statements = [];
        const nonPrologueStart = factory2.copyPrologue(
          node.body.statements,
          statements,
          /*ensureUseStrict*/
          false,
          visitor
        );
        const superStatementIndex = findSuperStatementIndex(node.body.statements, nonPrologueStart);
        if (superStatementIndex >= 0) {
          addRange(statements, visitNodes2(node.body.statements, visitor, isStatement, nonPrologueStart, superStatementIndex + 1 - nonPrologueStart));
          addRange(statements, initializerStatements);
          addRange(statements, visitNodes2(node.body.statements, visitor, isStatement, superStatementIndex + 1));
        } else {
          addRange(statements, initializerStatements);
          addRange(statements, visitNodes2(node.body.statements, visitor, isStatement));
        }
        body = factory2.createBlock(
          statements,
          /*multiLine*/
          true
        );
        setOriginalNode(body, node.body);
        setTextRange(body, node.body);
      }
    }
    body ?? (body = visitNode(node.body, visitor, isBlock));
    exitClassElement();
    return factory2.updateConstructorDeclaration(node, modifiers, parameters, body);
  }
  function finishClassElement(updated, original) {
    if (updated !== original) {
      setCommentRange(updated, original);
      setSourceMapRange(updated, moveRangePastDecorators(original));
    }
    return updated;
  }
  function partialTransformClassElement(member, useNamedEvaluation, classInfo2, createDescriptor) {
    let referencedName;
    let name;
    let initializersName;
    let thisArg;
    let descriptorName;
    if (!classInfo2) {
      const modifiers2 = visitNodes2(member.modifiers, modifierVisitor, isModifier);
      enterName();
      if (useNamedEvaluation) {
        ({ referencedName, name } = visitReferencedPropertyName(member.name));
      } else {
        name = visitPropertyName(member.name);
      }
      exitName();
      return { modifiers: modifiers2, referencedName, name, initializersName, descriptorName, thisArg };
    }
    const memberDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClassElement(
      member,
      classInfo2.class,
      /*useLegacyDecorators*/
      false
    ));
    const modifiers = visitNodes2(member.modifiers, modifierVisitor, isModifier);
    if (memberDecorators) {
      const memberDecoratorsName = createHelperVariable(member, "decorators");
      const memberDecoratorsArray = factory2.createArrayLiteralExpression(memberDecorators);
      const memberDecoratorsAssignment = factory2.createAssignment(memberDecoratorsName, memberDecoratorsArray);
      const memberInfo = { memberDecoratorsName };
      classInfo2.memberInfos ?? (classInfo2.memberInfos = /* @__PURE__ */ new Map());
      classInfo2.memberInfos.set(member, memberInfo);
      pendingExpressions ?? (pendingExpressions = []);
      pendingExpressions.push(memberDecoratorsAssignment);
      const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticNonFieldDecorationStatements ?? (classInfo2.staticNonFieldDecorationStatements = []) : classInfo2.nonStaticNonFieldDecorationStatements ?? (classInfo2.nonStaticNonFieldDecorationStatements = []) : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticFieldDecorationStatements ?? (classInfo2.staticFieldDecorationStatements = []) : classInfo2.nonStaticFieldDecorationStatements ?? (classInfo2.nonStaticFieldDecorationStatements = []) : Debug.fail();
      const kind = isGetAccessorDeclaration(member) ? "getter" : isSetAccessorDeclaration(member) ? "setter" : isMethodDeclaration(member) ? "method" : isAutoAccessorPropertyDeclaration(member) ? "accessor" : isPropertyDeclaration(member) ? "field" : Debug.fail();
      let propertyName;
      if (isIdentifier(member.name) || isPrivateIdentifier(member.name)) {
        propertyName = { computed: false, name: member.name };
      } else if (isPropertyNameLiteral(member.name)) {
        propertyName = { computed: true, name: factory2.createStringLiteralFromNode(member.name) };
      } else {
        const expression = member.name.expression;
        if (isPropertyNameLiteral(expression) && !isIdentifier(expression)) {
          propertyName = { computed: true, name: factory2.createStringLiteralFromNode(expression) };
        } else {
          enterName();
          ({ referencedName, name } = visitReferencedPropertyName(member.name));
          propertyName = { computed: true, name: referencedName };
          exitName();
        }
      }
      const context2 = {
        kind,
        name: propertyName,
        static: isStatic(member),
        private: isPrivateIdentifier(member.name),
        access: {
          // 15.7.3 CreateDecoratorAccessObject (kind, name)
          // 2. If _kind_ is ~field~, ~method~, ~accessor~, or ~getter~, then ...
          get: isPropertyDeclaration(member) || isGetAccessorDeclaration(member) || isMethodDeclaration(member),
          // 3. If _kind_ is ~field~, ~accessor~, or ~setter~, then ...
          set: isPropertyDeclaration(member) || isSetAccessorDeclaration(member)
        }
      };
      const extraInitializers = isStatic(member) ? classInfo2.staticExtraInitializersName ?? (classInfo2.staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */)) : classInfo2.instanceExtraInitializersName ?? (classInfo2.instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */));
      if (isMethodOrAccessor(member)) {
        let descriptor;
        if (isPrivateIdentifierClassElementDeclaration(member) && createDescriptor) {
          descriptor = createDescriptor(member, visitNodes2(modifiers, (node) => tryCast(node, isAsyncModifier), isModifier));
          memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor");
          descriptor = factory2.createAssignment(descriptorName, descriptor);
        }
        const esDecorateExpression = emitHelpers().createESDecorateHelper(factory2.createThis(), descriptor ?? factory2.createNull(), memberDecoratorsName, context2, factory2.createNull(), extraInitializers);
        const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression);
        setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member));
        statements.push(esDecorateStatement);
      } else if (isPropertyDeclaration(member)) {
        initializersName = memberInfo.memberInitializersName ?? (memberInfo.memberInitializersName = createHelperVariable(member, "initializers"));
        if (isStatic(member)) {
          thisArg = classInfo2.classThis;
        }
        let descriptor;
        if (isPrivateIdentifierClassElementDeclaration(member) && hasAccessorModifier(member) && createDescriptor) {
          descriptor = createDescriptor(
            member,
            /*modifiers*/
            void 0
          );
          memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor");
          descriptor = factory2.createAssignment(descriptorName, descriptor);
        }
        const esDecorateExpression = emitHelpers().createESDecorateHelper(
          isAutoAccessorPropertyDeclaration(member) ? factory2.createThis() : factory2.createNull(),
          descriptor ?? factory2.createNull(),
          memberDecoratorsName,
          context2,
          initializersName,
          extraInitializers
        );
        const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression);
        setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member));
        statements.push(esDecorateStatement);
      }
    }
    if (name === void 0) {
      enterName();
      if (useNamedEvaluation) {
        ({ referencedName, name } = visitReferencedPropertyName(member.name));
      } else {
        name = visitPropertyName(member.name);
      }
      exitName();
    }
    if (!some(modifiers) && (isMethodDeclaration(member) || isPropertyDeclaration(member))) {
      setEmitFlags(name, 1024 /* NoLeadingComments */);
    }
    return { modifiers, referencedName, name, initializersName, descriptorName, thisArg };
  }
  function visitMethodDeclaration(node) {
    enterClassElement(node);
    const { modifiers, name, descriptorName } = partialTransformClassElement(
      node,
      /*useNamedEvaluation*/
      false,
      classInfo,
      createMethodDescriptorObject
    );
    if (descriptorName) {
      exitClassElement();
      return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node);
    } else {
      const parameters = visitNodes2(node.parameters, visitor, isParameter);
      const body = visitNode(node.body, visitor, isBlock);
      exitClassElement();
      return finishClassElement(factory2.updateMethodDeclaration(
        node,
        modifiers,
        node.asteriskToken,
        name,
        /*questionToken*/
        void 0,
        /*typeParameters*/
        void 0,
        parameters,
        /*type*/
        void 0,
        body
      ), node);
    }
  }
  function visitGetAccessorDeclaration(node) {
    enterClassElement(node);
    const { modifiers, name, descriptorName } = partialTransformClassElement(
      node,
      /*useNamedEvaluation*/
      false,
      classInfo,
      createGetAccessorDescriptorObject
    );
    if (descriptorName) {
      exitClassElement();
      return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node);
    } else {
      const parameters = visitNodes2(node.parameters, visitor, isParameter);
      const body = visitNode(node.body, visitor, isBlock);
      exitClassElement();
      return finishClassElement(factory2.updateGetAccessorDeclaration(
        node,
        modifiers,
        name,
        parameters,
        /*type*/
        void 0,
        body
      ), node);
    }
  }
  function visitSetAccessorDeclaration(node) {
    enterClassElement(node);
    const { modifiers, name, descriptorName } = partialTransformClassElement(
      node,
      /*useNamedEvaluation*/
      false,
      classInfo,
      createSetAccessorDescriptorObject
    );
    if (descriptorName) {
      exitClassElement();
      return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node);
    } else {
      const parameters = visitNodes2(node.parameters, visitor, isParameter);
      const body = visitNode(node.body, visitor, isBlock);
      exitClassElement();
      return finishClassElement(factory2.updateSetAccessorDeclaration(node, modifiers, name, parameters, body), node);
    }
  }
  function visitClassStaticBlockDeclaration(node) {
    enterClassElement(node);
    if (classInfo)
      classInfo.hasStaticInitializers = true;
    const result = visitEachChild(node, visitor, context);
    exitClassElement();
    return result;
  }
  function visitPropertyDeclaration(node) {
    enterClassElement(node);
    Debug.assert(!isAmbientPropertyDeclaration(node), "Not yet implemented.");
    const useNamedEvaluation = isNamedEvaluation(node, isAnonymousClassNeedingAssignedName);
    const { modifiers, name, referencedName, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, useNamedEvaluation, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0);
    startLexicalEnvironment();
    let initializer = referencedName ? visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, referencedName), isExpression) : visitNode(node.initializer, visitor, isExpression);
    if (initializersName) {
      initializer = emitHelpers().createRunInitializersHelper(
        thisArg ?? factory2.createThis(),
        initializersName,
        initializer ?? factory2.createVoidZero()
      );
    }
    if (!isStatic(node) && (classInfo == null ? void 0 : classInfo.instanceExtraInitializersName) && !(classInfo == null ? void 0 : classInfo.hasInjectedInstanceInitializers)) {
      classInfo.hasInjectedInstanceInitializers = true;
      initializer ?? (initializer = factory2.createVoidZero());
      initializer = factory2.createParenthesizedExpression(factory2.createComma(
        emitHelpers().createRunInitializersHelper(
          factory2.createThis(),
          classInfo.instanceExtraInitializersName
        ),
        initializer
      ));
    }
    if (isStatic(node) && classInfo && initializer) {
      classInfo.hasStaticInitializers = true;
    }
    const declarations = endLexicalEnvironment();
    if (some(declarations)) {
      initializer = factory2.createImmediatelyInvokedArrowFunction([
        ...declarations,
        factory2.createReturnStatement(initializer)
      ]);
    }
    exitClassElement();
    if (hasAccessorModifier(node) && descriptorName) {
      const commentRange = getCommentRange(node);
      const sourceMapRange = getSourceMapRange(node);
      const name2 = node.name;
      let getterName = name2;
      let setterName = name2;
      if (isComputedPropertyName(name2) && !isSimpleInlineableExpression(name2.expression)) {
        const cacheAssignment = findComputedPropertyNameCacheAssignment(name2);
        if (cacheAssignment) {
          getterName = factory2.updateComputedPropertyName(name2, visitNode(name2.expression, visitor, isExpression));
          setterName = factory2.updateComputedPropertyName(name2, cacheAssignment.left);
        } else {
          const temp = factory2.createTempVariable(hoistVariableDeclaration);
          setSourceMapRange(temp, name2.expression);
          const expression = visitNode(name2.expression, visitor, isExpression);
          const assignment = factory2.createAssignment(temp, expression);
          setSourceMapRange(assignment, name2.expression);
          getterName = factory2.updateComputedPropertyName(name2, assignment);
          setterName = factory2.updateComputedPropertyName(name2, temp);
        }
      }
      const modifiersWithoutAccessor = visitNodes2(modifiers, (node2) => node2.kind !== 129 /* AccessorKeyword */ ? node2 : void 0, isModifier);
      const backingField = createAccessorPropertyBackingField(factory2, node, modifiersWithoutAccessor, initializer);
      setOriginalNode(backingField, node);
      setEmitFlags(backingField, 3072 /* NoComments */);
      setSourceMapRange(backingField, sourceMapRange);
      setSourceMapRange(backingField.name, node.name);
      const getter = createGetAccessorDescriptorForwarder(modifiersWithoutAccessor, getterName, descriptorName);
      setOriginalNode(getter, node);
      setCommentRange(getter, commentRange);
      setSourceMapRange(getter, sourceMapRange);
      const setter = createSetAccessorDescriptorForwarder(modifiersWithoutAccessor, setterName, descriptorName);
      setOriginalNode(setter, node);
      setEmitFlags(setter, 3072 /* NoComments */);
      setSourceMapRange(setter, sourceMapRange);
      return [backingField, getter, setter];
    }
    return finishClassElement(factory2.updatePropertyDeclaration(
      node,
      modifiers,
      name,
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      initializer
    ), node);
  }
  function visitThisExpression(node) {
    return classThis ?? node;
  }
  function visitCallExpression(node) {
    if (isSuperProperty(node.expression) && classThis) {
      const expression = visitNode(node.expression, visitor, isExpression);
      const argumentsList = visitNodes2(node.arguments, visitor, isExpression);
      const invocation = factory2.createFunctionCallCall(expression, classThis, argumentsList);
      setOriginalNode(invocation, node);
      setTextRange(invocation, node);
      return invocation;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitTaggedTemplateExpression(node) {
    if (isSuperProperty(node.tag) && classThis) {
      const tag = visitNode(node.tag, visitor, isExpression);
      const boundTag = factory2.createFunctionBindCall(tag, classThis, []);
      setOriginalNode(boundTag, node);
      setTextRange(boundTag, node);
      const template = visitNode(node.template, visitor, isTemplateLiteral);
      return factory2.updateTaggedTemplateExpression(
        node,
        boundTag,
        /*typeArguments*/
        void 0,
        template
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitPropertyAccessExpression(node) {
    if (isSuperProperty(node) && isIdentifier(node.name) && classThis && classSuper) {
      const propertyName = factory2.createStringLiteralFromNode(node.name);
      const superProperty = factory2.createReflectGetCall(classSuper, propertyName, classThis);
      setOriginalNode(superProperty, node.expression);
      setTextRange(superProperty, node.expression);
      return superProperty;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitElementAccessExpression(node) {
    if (isSuperProperty(node) && classThis && classSuper) {
      const propertyName = visitNode(node.argumentExpression, visitor, isExpression);
      const superProperty = factory2.createReflectGetCall(classSuper, propertyName, classThis);
      setOriginalNode(superProperty, node.expression);
      setTextRange(superProperty, node.expression);
      return superProperty;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitParameterDeclaration(node) {
    let updated;
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer);
      const name = visitNode(node.name, visitor, isBindingName);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      updated = factory2.updateParameterDeclaration(
        node,
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        /*type*/
        void 0,
        initializer
      );
    } else {
      updated = factory2.updateParameterDeclaration(
        node,
        /*modifiers*/
        void 0,
        node.dotDotDotToken,
        visitNode(node.name, visitor, isBindingName),
        /*questionToken*/
        void 0,
        /*type*/
        void 0,
        visitNode(node.initializer, visitor, isExpression)
      );
    }
    if (updated !== node) {
      setCommentRange(updated, node);
      setTextRange(updated, moveRangePastModifiers(node));
      setSourceMapRange(updated, moveRangePastModifiers(node));
      setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */);
    }
    return updated;
  }
  function isAnonymousClassNeedingAssignedName(node) {
    return isClassExpression(node) && !node.name && isDecoratedClassLike(node);
  }
  function visitForStatement(node) {
    return factory2.updateForStatement(
      node,
      visitNode(node.initializer, discardedValueVisitor, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, discardedValueVisitor, isExpression),
      visitIterationBody(node.statement, visitor, context)
    );
  }
  function visitExpressionStatement(node) {
    return visitEachChild(node, discardedValueVisitor, context);
  }
  function visitBinaryExpression(node, discarded) {
    if (isDestructuringAssignment(node)) {
      const left = visitAssignmentPattern(node.left);
      const right = visitNode(node.right, visitor, isExpression);
      return factory2.updateBinaryExpression(node, left, node.operatorToken, right);
    }
    if (isAssignmentExpression(node)) {
      if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
        const assignedName = getAssignedNameOfIdentifier(node.left, node.right);
        const left = visitNode(node.left, visitor, isExpression);
        const right = visitNode(node.right, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
        return factory2.updateBinaryExpression(node, left, node.operatorToken, right);
      }
      if (isSuperProperty(node.left) && classThis && classSuper) {
        let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0;
        if (setterName) {
          let expression = visitNode(node.right, visitor, isExpression);
          if (isCompoundAssignment(node.operatorToken.kind)) {
            let getterName = setterName;
            if (!isSimpleInlineableExpression(setterName)) {
              getterName = factory2.createTempVariable(hoistVariableDeclaration);
              setterName = factory2.createAssignment(getterName, setterName);
            }
            const superPropertyGet = factory2.createReflectGetCall(
              classSuper,
              getterName,
              classThis
            );
            setOriginalNode(superPropertyGet, node.left);
            setTextRange(superPropertyGet, node.left);
            expression = factory2.createBinaryExpression(
              superPropertyGet,
              getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind),
              expression
            );
            setTextRange(expression, node);
          }
          const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration);
          if (temp) {
            expression = factory2.createAssignment(temp, expression);
            setTextRange(temp, node);
          }
          expression = factory2.createReflectSetCall(
            classSuper,
            setterName,
            expression,
            classThis
          );
          setOriginalNode(expression, node);
          setTextRange(expression, node);
          if (temp) {
            expression = factory2.createComma(expression, temp);
            setTextRange(expression, node);
          }
          return expression;
        }
      }
    }
    if (node.operatorToken.kind === 28 /* CommaToken */) {
      const left = visitNode(node.left, discardedValueVisitor, isExpression);
      const right = visitNode(node.right, discarded ? discardedValueVisitor : visitor, isExpression);
      return factory2.updateBinaryExpression(node, left, node.operatorToken, right);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitPreOrPostfixUnaryExpression(node, discarded) {
    if (node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) {
      const operand = skipParentheses(node.operand);
      if (isSuperProperty(operand) && classThis && classSuper) {
        let setterName = isElementAccessExpression(operand) ? visitNode(operand.argumentExpression, visitor, isExpression) : isIdentifier(operand.name) ? factory2.createStringLiteralFromNode(operand.name) : void 0;
        if (setterName) {
          let getterName = setterName;
          if (!isSimpleInlineableExpression(setterName)) {
            getterName = factory2.createTempVariable(hoistVariableDeclaration);
            setterName = factory2.createAssignment(getterName, setterName);
          }
          let expression = factory2.createReflectGetCall(classSuper, getterName, classThis);
          setOriginalNode(expression, node);
          setTextRange(expression, node);
          const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration);
          expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp);
          expression = factory2.createReflectSetCall(classSuper, setterName, expression, classThis);
          setOriginalNode(expression, node);
          setTextRange(expression, node);
          if (temp) {
            expression = factory2.createComma(expression, temp);
            setTextRange(expression, node);
          }
          return expression;
        }
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCommaListExpression(node, discarded) {
    const elements = discarded ? visitCommaListElements(node.elements, discardedValueVisitor) : visitCommaListElements(node.elements, visitor, discardedValueVisitor);
    return factory2.updateCommaListExpression(node, elements);
  }
  function visitReferencedPropertyName(node) {
    if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) {
      const referencedName2 = factory2.createStringLiteralFromNode(node);
      const name2 = visitNode(node, visitor, isPropertyName);
      return { referencedName: referencedName2, name: name2 };
    }
    if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) {
      const referencedName2 = factory2.createStringLiteralFromNode(node.expression);
      const name2 = visitNode(node, visitor, isPropertyName);
      return { referencedName: referencedName2, name: name2 };
    }
    const referencedName = factory2.getGeneratedNameForNode(node);
    hoistVariableDeclaration(referencedName);
    const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression));
    const assignment = factory2.createAssignment(referencedName, key);
    const name = factory2.updateComputedPropertyName(node, injectPendingExpressions(assignment));
    return { referencedName, name };
  }
  function visitPropertyName(node) {
    if (isComputedPropertyName(node)) {
      return visitComputedPropertyName(node);
    }
    return visitNode(node, visitor, isPropertyName);
  }
  function visitComputedPropertyName(node) {
    let expression = visitNode(node.expression, visitor, isExpression);
    if (!isSimpleInlineableExpression(expression)) {
      expression = injectPendingExpressions(expression);
    }
    return factory2.updateComputedPropertyName(node, expression);
  }
  function visitPropertyAssignment(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const { referencedName, name } = visitReferencedPropertyName(node.name);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, referencedName), isExpression);
      return factory2.updatePropertyAssignment(node, name, initializer);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitVariableDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer);
      const name = visitNode(node.name, visitor, isBindingName);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateVariableDeclaration(
        node,
        name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        initializer
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitBindingElement(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer);
      const propertyName = visitNode(node.propertyName, visitor, isPropertyName);
      const name = visitNode(node.name, visitor, isBindingName);
      const initializer = visitNode(node.initializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateBindingElement(
        node,
        /*dotDotDotToken*/
        void 0,
        propertyName,
        name,
        initializer
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitDestructuringAssignmentTarget(node) {
    if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) {
      return visitAssignmentPattern(node);
    }
    if (isSuperProperty(node) && classThis && classSuper) {
      const propertyName = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0;
      if (propertyName) {
        const paramName = factory2.createTempVariable(
          /*recordTempVariable*/
          void 0
        );
        const expression = factory2.createAssignmentTargetWrapper(
          paramName,
          factory2.createReflectSetCall(
            classSuper,
            propertyName,
            paramName,
            classThis
          )
        );
        setOriginalNode(expression, node);
        setTextRange(expression, node);
        return expression;
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentElement(node) {
    if (isAssignmentExpression(
      node,
      /*excludeCompoundAssignment*/
      true
    )) {
      const assignmentTarget = visitDestructuringAssignmentTarget(node.left);
      let initializer;
      if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
        const assignedName = getAssignedNameOfIdentifier(node.left, node.right);
        initializer = visitNode(node.right, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      } else {
        initializer = visitNode(node.right, visitor, isExpression);
      }
      return factory2.updateBinaryExpression(node, assignmentTarget, node.operatorToken, initializer);
    } else {
      return visitDestructuringAssignmentTarget(node);
    }
  }
  function visitAssignmentRestElement(node) {
    if (isLeftHandSideExpression(node.expression)) {
      const expression = visitDestructuringAssignmentTarget(node.expression);
      return factory2.updateSpreadElement(node, expression);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitArrayAssignmentElement(node) {
    Debug.assertNode(node, isArrayBindingOrAssignmentElement);
    if (isSpreadElement(node))
      return visitAssignmentRestElement(node);
    if (!isOmittedExpression(node))
      return visitAssignmentElement(node);
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentProperty(node) {
    const name = visitNode(node.name, visitor, isPropertyName);
    if (isAssignmentExpression(
      node.initializer,
      /*excludeCompoundAssignment*/
      true
    )) {
      const assignmentElement = visitAssignmentElement(node.initializer);
      return factory2.updatePropertyAssignment(node, name, assignmentElement);
    }
    if (isLeftHandSideExpression(node.initializer)) {
      const assignmentElement = visitDestructuringAssignmentTarget(node.initializer);
      return factory2.updatePropertyAssignment(node, name, assignmentElement);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitShorthandAssignmentProperty(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer);
      const name = visitNode(node.name, visitor, isIdentifier);
      const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, (node2) => namedEvaluationVisitor(node2, assignedName), isExpression);
      return factory2.updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentRestProperty(node) {
    if (isLeftHandSideExpression(node.expression)) {
      const expression = visitDestructuringAssignmentTarget(node.expression);
      return factory2.updateSpreadAssignment(node, expression);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitObjectAssignmentElement(node) {
    Debug.assertNode(node, isObjectBindingOrAssignmentElement);
    if (isSpreadAssignment(node))
      return visitAssignmentRestProperty(node);
    if (isShorthandPropertyAssignment(node))
      return visitShorthandAssignmentProperty(node);
    if (isPropertyAssignment(node))
      return visitAssignmentProperty(node);
    return visitEachChild(node, visitor, context);
  }
  function visitAssignmentPattern(node) {
    if (isArrayLiteralExpression(node)) {
      const elements = visitNodes2(node.elements, visitArrayAssignmentElement, isExpression);
      return factory2.updateArrayLiteralExpression(node, elements);
    } else {
      const properties = visitNodes2(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike);
      return factory2.updateObjectLiteralExpression(node, properties);
    }
  }
  function visitExportAssignment(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      const referencedName = factory2.createStringLiteral(node.isExportEquals ? "" : "default");
      const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
      const expression = visitNode(node.expression, (node2) => namedEvaluationVisitor(node2, referencedName), isExpression);
      return factory2.updateExportAssignment(node, modifiers, expression);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitParenthesizedExpression(node, discarded, referencedName) {
    const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2) => namedEvaluationVisitor(node2, referencedName) : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updateParenthesizedExpression(node, expression);
  }
  function visitPartiallyEmittedExpression(node, discarded, referencedName) {
    const visitorFunc = discarded ? discardedValueVisitor : referencedName ? (node2) => namedEvaluationVisitor(node2, referencedName) : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updatePartiallyEmittedExpression(node, expression);
  }
  function injectPendingExpressions(expression) {
    if (some(pendingExpressions)) {
      if (isParenthesizedExpression(expression)) {
        pendingExpressions.push(expression.expression);
        expression = factory2.updateParenthesizedExpression(expression, factory2.inlineExpressions(pendingExpressions));
      } else {
        pendingExpressions.push(expression);
        expression = factory2.inlineExpressions(pendingExpressions);
      }
      pendingExpressions = void 0;
    }
    return expression;
  }
  function transformAllDecoratorsOfDeclaration(allDecorators) {
    if (!allDecorators) {
      return void 0;
    }
    const decoratorExpressions = [];
    addRange(decoratorExpressions, map(allDecorators.decorators, transformDecorator));
    return decoratorExpressions;
  }
  function transformDecorator(decorator) {
    const expression = visitNode(decorator.expression, visitor, isExpression);
    setEmitFlags(expression, 3072 /* NoComments */);
    return expression;
  }
  function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) {
    const func = factory2.createFunctionExpression(
      modifiers,
      asteriskToken,
      /*name*/
      void 0,
      /*typeParameters*/
      void 0,
      parameters,
      /*type*/
      void 0,
      body ?? factory2.createBlock([])
    );
    setOriginalNode(func, original);
    setSourceMapRange(func, moveRangePastDecorators(original));
    setEmitFlags(func, 3072 /* NoComments */);
    const prefix = kind === "get" || kind === "set" ? kind : void 0;
    const functionName = factory2.createStringLiteralFromNode(
      name,
      /*isSingleQuote*/
      void 0
    );
    const namedFunction = emitHelpers().createSetFunctionNameHelper(func, functionName, prefix);
    const method = factory2.createPropertyAssignment(factory2.createIdentifier(kind), namedFunction);
    setOriginalNode(method, original);
    setSourceMapRange(method, moveRangePastDecorators(original));
    setEmitFlags(method, 3072 /* NoComments */);
    return method;
  }
  function createMethodDescriptorObject(node, modifiers) {
    return factory2.createObjectLiteralExpression([
      createDescriptorMethod(
        node,
        node.name,
        modifiers,
        node.asteriskToken,
        "value",
        visitNodes2(node.parameters, visitor, isParameter),
        visitNode(node.body, visitor, isBlock)
      )
    ]);
  }
  function createGetAccessorDescriptorObject(node, modifiers) {
    return factory2.createObjectLiteralExpression([
      createDescriptorMethod(
        node,
        node.name,
        modifiers,
        /*asteriskToken*/
        void 0,
        "get",
        [],
        visitNode(node.body, visitor, isBlock)
      )
    ]);
  }
  function createSetAccessorDescriptorObject(node, modifiers) {
    return factory2.createObjectLiteralExpression([
      createDescriptorMethod(
        node,
        node.name,
        modifiers,
        /*asteriskToken*/
        void 0,
        "set",
        visitNodes2(node.parameters, visitor, isParameter),
        visitNode(node.body, visitor, isBlock)
      )
    ]);
  }
  function createAccessorPropertyDescriptorObject(node, modifiers) {
    return factory2.createObjectLiteralExpression([
      createDescriptorMethod(
        node,
        node.name,
        modifiers,
        /*asteriskToken*/
        void 0,
        "get",
        [],
        factory2.createBlock([
          factory2.createReturnStatement(
            factory2.createPropertyAccessExpression(
              factory2.createThis(),
              factory2.getGeneratedPrivateNameForNode(node.name)
            )
          )
        ])
      ),
      createDescriptorMethod(
        node,
        node.name,
        modifiers,
        /*asteriskToken*/
        void 0,
        "set",
        [factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          "value"
        )],
        factory2.createBlock([
          factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.createPropertyAccessExpression(
                factory2.createThis(),
                factory2.getGeneratedPrivateNameForNode(node.name)
              ),
              factory2.createIdentifier("value")
            )
          )
        ])
      )
    ]);
  }
  function createMethodDescriptorForwarder(modifiers, name, descriptorName) {
    modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier);
    return factory2.createGetAccessorDeclaration(
      modifiers,
      name,
      [],
      /*type*/
      void 0,
      factory2.createBlock([
        factory2.createReturnStatement(
          factory2.createPropertyAccessExpression(
            descriptorName,
            factory2.createIdentifier("value")
          )
        )
      ])
    );
  }
  function createGetAccessorDescriptorForwarder(modifiers, name, descriptorName) {
    modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier);
    return factory2.createGetAccessorDeclaration(
      modifiers,
      name,
      [],
      /*type*/
      void 0,
      factory2.createBlock([
        factory2.createReturnStatement(
          factory2.createFunctionCallCall(
            factory2.createPropertyAccessExpression(
              descriptorName,
              factory2.createIdentifier("get")
            ),
            factory2.createThis(),
            []
          )
        )
      ])
    );
  }
  function createSetAccessorDescriptorForwarder(modifiers, name, descriptorName) {
    modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier);
    return factory2.createSetAccessorDeclaration(
      modifiers,
      name,
      [factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        "value"
      )],
      factory2.createBlock([
        factory2.createReturnStatement(
          factory2.createFunctionCallCall(
            factory2.createPropertyAccessExpression(
              descriptorName,
              factory2.createIdentifier("set")
            ),
            factory2.createThis(),
            [factory2.createIdentifier("value")]
          )
        )
      ])
    );
  }
  function getAssignedNameOfIdentifier(name, initializer) {
    const originalClass = getOriginalNode(initializer, isClassLike);
    return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, 1024 /* Default */) ? factory2.createStringLiteral("default") : factory2.createStringLiteralFromNode(name);
  }
}

// src/compiler/transformers/es2017.ts
function transformES2017(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    resumeLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  let enabledSubstitutions;
  let enclosingSuperContainerFlags = 0;
  let enclosingFunctionParameterNames;
  let capturedSuperProperties;
  let hasSuperElementAccess;
  const substitutedSuperAccessors = [];
  let contextFlags = 0 /* None */;
  const previousOnEmitNode = context.onEmitNode;
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    setContextFlag(1 /* NonTopLevel */, false);
    setContextFlag(2 /* HasLexicalThis */, !isEffectiveStrictModeSourceFile(node, compilerOptions));
    const visited = visitEachChild(node, visitor, context);
    addEmitHelpers(visited, context.readEmitHelpers());
    return visited;
  }
  function setContextFlag(flag, val) {
    contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
  }
  function inContext(flags) {
    return (contextFlags & flags) !== 0;
  }
  function inTopLevelContext() {
    return !inContext(1 /* NonTopLevel */);
  }
  function inHasLexicalThisContext() {
    return inContext(2 /* HasLexicalThis */);
  }
  function doWithContext(flags, cb, value) {
    const contextFlagsToSet = flags & ~contextFlags;
    if (contextFlagsToSet) {
      setContextFlag(
        contextFlagsToSet,
        /*val*/
        true
      );
      const result = cb(value);
      setContextFlag(
        contextFlagsToSet,
        /*val*/
        false
      );
      return result;
    }
    return cb(value);
  }
  function visitDefault(node) {
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 256 /* ContainsES2017 */) === 0) {
      return node;
    }
    switch (node.kind) {
      case 134 /* AsyncKeyword */:
        return void 0;
      case 222 /* AwaitExpression */:
        return visitAwaitExpression(node);
      case 173 /* MethodDeclaration */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
      case 261 /* FunctionDeclaration */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
      case 217 /* FunctionExpression */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
      case 218 /* ArrowFunction */:
        return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
      case 210 /* PropertyAccessExpression */:
        if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */) {
          capturedSuperProperties.add(node.name.escapedText);
        }
        return visitEachChild(node, visitor, context);
      case 211 /* ElementAccessExpression */:
        if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */) {
          hasSuperElementAccess = true;
        }
        return visitEachChild(node, visitor, context);
      case 176 /* GetAccessor */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitGetAccessorDeclaration, node);
      case 177 /* SetAccessor */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitSetAccessorDeclaration, node);
      case 175 /* Constructor */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitConstructorDeclaration, node);
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function asyncBodyVisitor(node) {
    if (isNodeWithPossibleHoistedDeclaration(node)) {
      switch (node.kind) {
        case 242 /* VariableStatement */:
          return visitVariableStatementInAsyncBody(node);
        case 247 /* ForStatement */:
          return visitForStatementInAsyncBody(node);
        case 248 /* ForInStatement */:
          return visitForInStatementInAsyncBody(node);
        case 249 /* ForOfStatement */:
          return visitForOfStatementInAsyncBody(node);
        case 298 /* CatchClause */:
          return visitCatchClauseInAsyncBody(node);
        case 240 /* Block */:
        case 254 /* SwitchStatement */:
        case 268 /* CaseBlock */:
        case 295 /* CaseClause */:
        case 296 /* DefaultClause */:
        case 257 /* TryStatement */:
        case 245 /* DoStatement */:
        case 246 /* WhileStatement */:
        case 244 /* IfStatement */:
        case 253 /* WithStatement */:
        case 255 /* LabeledStatement */:
          return visitEachChild(node, asyncBodyVisitor, context);
        default:
          return Debug.assertNever(node, "Unhandled node.");
      }
    }
    return visitor(node);
  }
  function visitCatchClauseInAsyncBody(node) {
    const catchClauseNames = /* @__PURE__ */ new Set();
    recordDeclarationName(node.variableDeclaration, catchClauseNames);
    let catchClauseUnshadowedNames;
    catchClauseNames.forEach((_, escapedName) => {
      if (enclosingFunctionParameterNames.has(escapedName)) {
        if (!catchClauseUnshadowedNames) {
          catchClauseUnshadowedNames = new Set(enclosingFunctionParameterNames);
        }
        catchClauseUnshadowedNames.delete(escapedName);
      }
    });
    if (catchClauseUnshadowedNames) {
      const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
      enclosingFunctionParameterNames = catchClauseUnshadowedNames;
      const result = visitEachChild(node, asyncBodyVisitor, context);
      enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
      return result;
    } else {
      return visitEachChild(node, asyncBodyVisitor, context);
    }
  }
  function visitVariableStatementInAsyncBody(node) {
    if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
      const expression = visitVariableDeclarationListWithCollidingNames(
        node.declarationList,
        /*hasReceiver*/
        false
      );
      return expression ? factory2.createExpressionStatement(expression) : void 0;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitForInStatementInAsyncBody(node) {
    return factory2.updateForInStatement(
      node,
      isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(
        node.initializer,
        /*hasReceiver*/
        true
      ) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)),
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      visitIterationBody(node.statement, asyncBodyVisitor, context)
    );
  }
  function visitForOfStatementInAsyncBody(node) {
    return factory2.updateForOfStatement(
      node,
      visitNode(node.awaitModifier, visitor, isAwaitKeyword),
      isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(
        node.initializer,
        /*hasReceiver*/
        true
      ) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)),
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      visitIterationBody(node.statement, asyncBodyVisitor, context)
    );
  }
  function visitForStatementInAsyncBody(node) {
    const initializer = node.initializer;
    return factory2.updateForStatement(
      node,
      isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(
        initializer,
        /*hasReceiver*/
        false
      ) : visitNode(node.initializer, visitor, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, visitor, isExpression),
      visitIterationBody(node.statement, asyncBodyVisitor, context)
    );
  }
  function visitAwaitExpression(node) {
    if (inTopLevelContext()) {
      return visitEachChild(node, visitor, context);
    }
    return setOriginalNode(
      setTextRange(
        factory2.createYieldExpression(
          /*asteriskToken*/
          void 0,
          visitNode(node.expression, visitor, isExpression)
        ),
        node
      ),
      node
    );
  }
  function visitConstructorDeclaration(node) {
    return factory2.updateConstructorDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      visitParameterList(node.parameters, visitor, context),
      transformMethodBody(node)
    );
  }
  function visitMethodDeclaration(node) {
    return factory2.updateMethodDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.asteriskToken,
      node.name,
      /*questionToken*/
      void 0,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : transformMethodBody(node)
    );
  }
  function visitGetAccessorDeclaration(node) {
    return factory2.updateGetAccessorDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.name,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      transformMethodBody(node)
    );
  }
  function visitSetAccessorDeclaration(node) {
    return factory2.updateSetAccessorDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.name,
      visitParameterList(node.parameters, visitor, context),
      transformMethodBody(node)
    );
  }
  function visitFunctionDeclaration(node) {
    return factory2.updateFunctionDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)
    );
  }
  function visitFunctionExpression(node) {
    return factory2.updateFunctionExpression(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)
    );
  }
  function visitArrowFunction(node) {
    return factory2.updateArrowFunction(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      node.equalsGreaterThanToken,
      getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)
    );
  }
  function recordDeclarationName({ name }, names) {
    if (isIdentifier(name)) {
      names.add(name.escapedText);
    } else {
      for (const element of name.elements) {
        if (!isOmittedExpression(element)) {
          recordDeclarationName(element, names);
        }
      }
    }
  }
  function isVariableDeclarationListWithCollidingName(node) {
    return !!node && isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */) && node.declarations.some(collidesWithParameterName);
  }
  function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
    hoistVariableDeclarationList(node);
    const variables = getInitializedVariables(node);
    if (variables.length === 0) {
      if (hasReceiver) {
        return visitNode(factory2.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, isExpression);
      }
      return void 0;
    }
    return factory2.inlineExpressions(map(variables, transformInitializedVariable));
  }
  function hoistVariableDeclarationList(node) {
    forEach(node.declarations, hoistVariable);
  }
  function hoistVariable({ name }) {
    if (isIdentifier(name)) {
      hoistVariableDeclaration(name);
    } else {
      for (const element of name.elements) {
        if (!isOmittedExpression(element)) {
          hoistVariable(element);
        }
      }
    }
  }
  function transformInitializedVariable(node) {
    const converted = setSourceMapRange(
      factory2.createAssignment(
        factory2.converters.convertToAssignmentElementTarget(node.name),
        node.initializer
      ),
      node
    );
    return Debug.checkDefined(visitNode(converted, visitor, isExpression));
  }
  function collidesWithParameterName({ name }) {
    if (isIdentifier(name)) {
      return enclosingFunctionParameterNames.has(name.escapedText);
    } else {
      for (const element of name.elements) {
        if (!isOmittedExpression(element) && collidesWithParameterName(element)) {
          return true;
        }
      }
    }
    return false;
  }
  function transformMethodBody(node) {
    Debug.assertIsDefined(node.body);
    const savedCapturedSuperProperties = capturedSuperProperties;
    const savedHasSuperElementAccess = hasSuperElementAccess;
    capturedSuperProperties = /* @__PURE__ */ new Set();
    hasSuperElementAccess = false;
    let updated = visitFunctionBody(node.body, visitor, context);
    const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration);
    const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */) && (getFunctionFlags(originalMethod) & 3 /* AsyncGenerator */) !== 3 /* AsyncGenerator */;
    if (emitSuperHelpers) {
      enableSubstitutionForAsyncMethodsWithSuper();
      if (capturedSuperProperties.size) {
        const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties);
        substitutedSuperAccessors[getNodeId(variableStatement)] = true;
        const statements = updated.statements.slice();
        insertStatementsAfterStandardPrologue(statements, [variableStatement]);
        updated = factory2.updateBlock(updated, statements);
      }
      if (hasSuperElementAccess) {
        if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) {
          addEmitHelper(updated, advancedAsyncSuperHelper);
        } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) {
          addEmitHelper(updated, asyncSuperHelper);
        }
      }
    }
    capturedSuperProperties = savedCapturedSuperProperties;
    hasSuperElementAccess = savedHasSuperElementAccess;
    return updated;
  }
  function transformAsyncFunctionBody(node) {
    resumeLexicalEnvironment();
    const original = getOriginalNode(node, isFunctionLike);
    const nodeType = original.type;
    const promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : void 0;
    const isArrowFunction2 = node.kind === 218 /* ArrowFunction */;
    const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 512 /* CaptureArguments */) !== 0;
    const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
    enclosingFunctionParameterNames = /* @__PURE__ */ new Set();
    for (const parameter of node.parameters) {
      recordDeclarationName(parameter, enclosingFunctionParameterNames);
    }
    const savedCapturedSuperProperties = capturedSuperProperties;
    const savedHasSuperElementAccess = hasSuperElementAccess;
    if (!isArrowFunction2) {
      capturedSuperProperties = /* @__PURE__ */ new Set();
      hasSuperElementAccess = false;
    }
    let result;
    if (!isArrowFunction2) {
      const statements = [];
      const statementOffset = factory2.copyPrologue(
        node.body.statements,
        statements,
        /*ensureUseStrict*/
        false,
        visitor
      );
      statements.push(
        factory2.createReturnStatement(
          emitHelpers().createAwaiterHelper(
            inHasLexicalThisContext(),
            hasLexicalArguments,
            promiseConstructor,
            transformAsyncFunctionBodyWorker(node.body, statementOffset)
          )
        )
      );
      insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
      const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */);
      if (emitSuperHelpers) {
        enableSubstitutionForAsyncMethodsWithSuper();
        if (capturedSuperProperties.size) {
          const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties);
          substitutedSuperAccessors[getNodeId(variableStatement)] = true;
          insertStatementsAfterStandardPrologue(statements, [variableStatement]);
        }
      }
      const block = factory2.createBlock(
        statements,
        /*multiLine*/
        true
      );
      setTextRange(block, node.body);
      if (emitSuperHelpers && hasSuperElementAccess) {
        if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) {
          addEmitHelper(block, advancedAsyncSuperHelper);
        } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) {
          addEmitHelper(block, asyncSuperHelper);
        }
      }
      result = block;
    } else {
      const expression = emitHelpers().createAwaiterHelper(
        inHasLexicalThisContext(),
        hasLexicalArguments,
        promiseConstructor,
        transformAsyncFunctionBodyWorker(node.body)
      );
      const declarations = endLexicalEnvironment();
      if (some(declarations)) {
        const block = factory2.converters.convertToFunctionBlock(expression);
        result = factory2.updateBlock(block, setTextRange(factory2.createNodeArray(concatenate(declarations, block.statements)), block.statements));
      } else {
        result = expression;
      }
    }
    enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
    if (!isArrowFunction2) {
      capturedSuperProperties = savedCapturedSuperProperties;
      hasSuperElementAccess = savedHasSuperElementAccess;
    }
    return result;
  }
  function transformAsyncFunctionBodyWorker(body, start2) {
    if (isBlock(body)) {
      return factory2.updateBlock(body, visitNodes2(body.statements, asyncBodyVisitor, isStatement, start2));
    } else {
      return factory2.converters.convertToFunctionBlock(Debug.checkDefined(visitNode(body, asyncBodyVisitor, isConciseBody)));
    }
  }
  function getPromiseConstructor(type) {
    const typeName = type && getEntityNameFromTypeNode(type);
    if (typeName && isEntityName(typeName)) {
      const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
      if (serializationKind === 1 /* TypeWithConstructSignatureAndValue */ || serializationKind === 0 /* Unknown */) {
        return typeName;
      }
    }
    return void 0;
  }
  function enableSubstitutionForAsyncMethodsWithSuper() {
    if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
      enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
      context.enableSubstitution(212 /* CallExpression */);
      context.enableSubstitution(210 /* PropertyAccessExpression */);
      context.enableSubstitution(211 /* ElementAccessExpression */);
      context.enableEmitNotification(262 /* ClassDeclaration */);
      context.enableEmitNotification(173 /* MethodDeclaration */);
      context.enableEmitNotification(176 /* GetAccessor */);
      context.enableEmitNotification(177 /* SetAccessor */);
      context.enableEmitNotification(175 /* Constructor */);
      context.enableEmitNotification(242 /* VariableStatement */);
    }
  }
  function onEmitNode(hint, node, emitCallback) {
    if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
      const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */);
      if (superContainerFlags !== enclosingSuperContainerFlags) {
        const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
        enclosingSuperContainerFlags = superContainerFlags;
        previousOnEmitNode(hint, node, emitCallback);
        enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
        return;
      }
    } else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) {
      const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
      enclosingSuperContainerFlags = 0;
      previousOnEmitNode(hint, node, emitCallback);
      enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
      return;
    }
    previousOnEmitNode(hint, node, emitCallback);
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
      return substituteExpression(node);
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 210 /* PropertyAccessExpression */:
        return substitutePropertyAccessExpression(node);
      case 211 /* ElementAccessExpression */:
        return substituteElementAccessExpression(node);
      case 212 /* CallExpression */:
        return substituteCallExpression(node);
    }
    return node;
  }
  function substitutePropertyAccessExpression(node) {
    if (node.expression.kind === 108 /* SuperKeyword */) {
      return setTextRange(
        factory2.createPropertyAccessExpression(
          factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */),
          node.name
        ),
        node
      );
    }
    return node;
  }
  function substituteElementAccessExpression(node) {
    if (node.expression.kind === 108 /* SuperKeyword */) {
      return createSuperElementAccessInAsyncMethod(
        node.argumentExpression,
        node
      );
    }
    return node;
  }
  function substituteCallExpression(node) {
    const expression = node.expression;
    if (isSuperProperty(expression)) {
      const argumentExpression = isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression);
      return factory2.createCallExpression(
        factory2.createPropertyAccessExpression(argumentExpression, "call"),
        /*typeArguments*/
        void 0,
        [
          factory2.createThis(),
          ...node.arguments
        ]
      );
    }
    return node;
  }
  function isSuperContainer(node) {
    const kind = node.kind;
    return kind === 262 /* ClassDeclaration */ || kind === 175 /* Constructor */ || kind === 173 /* MethodDeclaration */ || kind === 176 /* GetAccessor */ || kind === 177 /* SetAccessor */;
  }
  function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
    if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */) {
      return setTextRange(
        factory2.createPropertyAccessExpression(
          factory2.createCallExpression(
            factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */),
            /*typeArguments*/
            void 0,
            [argumentExpression]
          ),
          "value"
        ),
        location
      );
    } else {
      return setTextRange(
        factory2.createCallExpression(
          factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */),
          /*typeArguments*/
          void 0,
          [argumentExpression]
        ),
        location
      );
    }
  }
}
function createSuperAccessVariableStatement(factory2, resolver, node, names) {
  const hasBinding = (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) !== 0;
  const accessors = [];
  names.forEach((_, key) => {
    const name = unescapeLeadingUnderscores(key);
    const getterAndSetter = [];
    getterAndSetter.push(factory2.createPropertyAssignment(
      "get",
      factory2.createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        /* parameters */
        [],
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        setEmitFlags(
          factory2.createPropertyAccessExpression(
            setEmitFlags(
              factory2.createSuper(),
              8 /* NoSubstitution */
            ),
            name
          ),
          8 /* NoSubstitution */
        )
      )
    ));
    if (hasBinding) {
      getterAndSetter.push(
        factory2.createPropertyAssignment(
          "set",
          factory2.createArrowFunction(
            /*modifiers*/
            void 0,
            /*typeParameters*/
            void 0,
            /* parameters */
            [
              factory2.createParameterDeclaration(
                /*modifiers*/
                void 0,
                /*dotDotDotToken*/
                void 0,
                "v",
                /*questionToken*/
                void 0,
                /*type*/
                void 0,
                /*initializer*/
                void 0
              )
            ],
            /*type*/
            void 0,
            /*equalsGreaterThanToken*/
            void 0,
            factory2.createAssignment(
              setEmitFlags(
                factory2.createPropertyAccessExpression(
                  setEmitFlags(
                    factory2.createSuper(),
                    8 /* NoSubstitution */
                  ),
                  name
                ),
                8 /* NoSubstitution */
              ),
              factory2.createIdentifier("v")
            )
          )
        )
      );
    }
    accessors.push(
      factory2.createPropertyAssignment(
        name,
        factory2.createObjectLiteralExpression(getterAndSetter)
      )
    );
  });
  return factory2.createVariableStatement(
    /*modifiers*/
    void 0,
    factory2.createVariableDeclarationList(
      [
        factory2.createVariableDeclaration(
          factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */),
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          factory2.createCallExpression(
            factory2.createPropertyAccessExpression(
              factory2.createIdentifier("Object"),
              "create"
            ),
            /*typeArguments*/
            void 0,
            [
              factory2.createNull(),
              factory2.createObjectLiteralExpression(
                accessors,
                /*multiLine*/
                true
              )
            ]
          )
        )
      ],
      2 /* Const */
    )
  );
}

// src/compiler/transformers/es2018.ts
function transformES2018(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    resumeLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const previousOnEmitNode = context.onEmitNode;
  context.onEmitNode = onEmitNode;
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onSubstituteNode = onSubstituteNode;
  let exportedVariableStatement = false;
  let enabledSubstitutions;
  let enclosingFunctionFlags;
  let parametersWithPrecedingObjectRestOrSpread;
  let enclosingSuperContainerFlags = 0;
  let hierarchyFacts = 0;
  let currentSourceFile;
  let taggedTemplateStringDeclarations;
  let capturedSuperProperties;
  let hasSuperElementAccess;
  const substitutedSuperAccessors = [];
  return chainBundle(context, transformSourceFile);
  function affectsSubtree(excludeFacts, includeFacts) {
    return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
  }
  function enterSubtree(excludeFacts, includeFacts) {
    const ancestorFacts = hierarchyFacts;
    hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
    return ancestorFacts;
  }
  function exitSubtree(ancestorFacts) {
    hierarchyFacts = ancestorFacts;
  }
  function recordTaggedTemplateString(temp) {
    taggedTemplateStringDeclarations = append(
      taggedTemplateStringDeclarations,
      factory2.createVariableDeclaration(temp)
    );
  }
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    currentSourceFile = node;
    const visited = visitSourceFile(node);
    addEmitHelpers(visited, context.readEmitHelpers());
    currentSourceFile = void 0;
    taggedTemplateStringDeclarations = void 0;
    return visited;
  }
  function visitor(node) {
    return visitorWorker(
      node,
      /*expressionResultIsUnused*/
      false
    );
  }
  function visitorWithUnusedExpressionResult(node) {
    return visitorWorker(
      node,
      /*expressionResultIsUnused*/
      true
    );
  }
  function visitorNoAsyncModifier(node) {
    if (node.kind === 134 /* AsyncKeyword */) {
      return void 0;
    }
    return node;
  }
  function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
    if (affectsSubtree(excludeFacts, includeFacts)) {
      const ancestorFacts = enterSubtree(excludeFacts, includeFacts);
      const result = cb(value);
      exitSubtree(ancestorFacts);
      return result;
    }
    return cb(value);
  }
  function visitDefault(node) {
    return visitEachChild(node, visitor, context);
  }
  function visitorWorker(node, expressionResultIsUnused2) {
    if ((node.transformFlags & 128 /* ContainsES2018 */) === 0) {
      return node;
    }
    switch (node.kind) {
      case 222 /* AwaitExpression */:
        return visitAwaitExpression(node);
      case 228 /* YieldExpression */:
        return visitYieldExpression(node);
      case 252 /* ReturnStatement */:
        return visitReturnStatement(node);
      case 255 /* LabeledStatement */:
        return visitLabeledStatement(node);
      case 209 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(node, expressionResultIsUnused2);
      case 360 /* CommaListExpression */:
        return visitCommaListExpression(node, expressionResultIsUnused2);
      case 298 /* CatchClause */:
        return visitCatchClause(node);
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 259 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 245 /* DoStatement */:
      case 246 /* WhileStatement */:
      case 248 /* ForInStatement */:
        return doWithHierarchyFacts(
          visitDefault,
          node,
          0 /* IterationStatementExcludes */,
          2 /* IterationStatementIncludes */
        );
      case 249 /* ForOfStatement */:
        return visitForOfStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 247 /* ForStatement */:
        return doWithHierarchyFacts(
          visitForStatement,
          node,
          0 /* IterationStatementExcludes */,
          2 /* IterationStatementIncludes */
        );
      case 221 /* VoidExpression */:
        return visitVoidExpression(node);
      case 175 /* Constructor */:
        return doWithHierarchyFacts(
          visitConstructorDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 173 /* MethodDeclaration */:
        return doWithHierarchyFacts(
          visitMethodDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 176 /* GetAccessor */:
        return doWithHierarchyFacts(
          visitGetAccessorDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 177 /* SetAccessor */:
        return doWithHierarchyFacts(
          visitSetAccessorDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 261 /* FunctionDeclaration */:
        return doWithHierarchyFacts(
          visitFunctionDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 217 /* FunctionExpression */:
        return doWithHierarchyFacts(
          visitFunctionExpression,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 218 /* ArrowFunction */:
        return doWithHierarchyFacts(
          visitArrowFunction,
          node,
          2 /* ArrowFunctionExcludes */,
          0 /* ArrowFunctionIncludes */
        );
      case 168 /* Parameter */:
        return visitParameter(node);
      case 243 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node, expressionResultIsUnused2);
      case 214 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 210 /* PropertyAccessExpression */:
        if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */) {
          capturedSuperProperties.add(node.name.escapedText);
        }
        return visitEachChild(node, visitor, context);
      case 211 /* ElementAccessExpression */:
        if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */) {
          hasSuperElementAccess = true;
        }
        return visitEachChild(node, visitor, context);
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
        return doWithHierarchyFacts(
          visitDefault,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitAwaitExpression(node) {
    if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
      return setOriginalNode(
        setTextRange(
          factory2.createYieldExpression(
            /*asteriskToken*/
            void 0,
            emitHelpers().createAwaitHelper(visitNode(node.expression, visitor, isExpression))
          ),
          /*location*/
          node
        ),
        node
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitYieldExpression(node) {
    if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
      if (node.asteriskToken) {
        const expression = visitNode(Debug.checkDefined(node.expression), visitor, isExpression);
        return setOriginalNode(
          setTextRange(
            factory2.createYieldExpression(
              /*asteriskToken*/
              void 0,
              emitHelpers().createAwaitHelper(
                factory2.updateYieldExpression(
                  node,
                  node.asteriskToken,
                  setTextRange(
                    emitHelpers().createAsyncDelegatorHelper(
                      setTextRange(
                        emitHelpers().createAsyncValuesHelper(expression),
                        expression
                      )
                    ),
                    expression
                  )
                )
              )
            ),
            node
          ),
          node
        );
      }
      return setOriginalNode(
        setTextRange(
          factory2.createYieldExpression(
            /*asteriskToken*/
            void 0,
            createDownlevelAwait(
              node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero()
            )
          ),
          node
        ),
        node
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitReturnStatement(node) {
    if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
      return factory2.updateReturnStatement(node, createDownlevelAwait(
        node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero()
      ));
    }
    return visitEachChild(node, visitor, context);
  }
  function visitLabeledStatement(node) {
    if (enclosingFunctionFlags & 2 /* Async */) {
      const statement = unwrapInnermostStatementOfLabel(node);
      if (statement.kind === 249 /* ForOfStatement */ && statement.awaitModifier) {
        return visitForOfStatement(statement, node);
      }
      return factory2.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory2.liftToBlock), node);
    }
    return visitEachChild(node, visitor, context);
  }
  function chunkObjectLiteralElements(elements) {
    let chunkObject;
    const objects = [];
    for (const e of elements) {
      if (e.kind === 304 /* SpreadAssignment */) {
        if (chunkObject) {
          objects.push(factory2.createObjectLiteralExpression(chunkObject));
          chunkObject = void 0;
        }
        const target = e.expression;
        objects.push(visitNode(target, visitor, isExpression));
      } else {
        chunkObject = append(chunkObject, e.kind === 302 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike));
      }
    }
    if (chunkObject) {
      objects.push(factory2.createObjectLiteralExpression(chunkObject));
    }
    return objects;
  }
  function visitObjectLiteralExpression(node) {
    if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
      const objects = chunkObjectLiteralElements(node.properties);
      if (objects.length && objects[0].kind !== 209 /* ObjectLiteralExpression */) {
        objects.unshift(factory2.createObjectLiteralExpression());
      }
      let expression = objects[0];
      if (objects.length > 1) {
        for (let i = 1; i < objects.length; i++) {
          expression = emitHelpers().createAssignHelper([expression, objects[i]]);
        }
        return expression;
      } else {
        return emitHelpers().createAssignHelper(objects);
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitExpressionStatement(node) {
    return visitEachChild(node, visitorWithUnusedExpressionResult, context);
  }
  function visitParenthesizedExpression(node, expressionResultIsUnused2) {
    return visitEachChild(node, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, context);
  }
  function visitSourceFile(node) {
    const ancestorFacts = enterSubtree(
      2 /* SourceFileExcludes */,
      isEffectiveStrictModeSourceFile(node, compilerOptions) ? 0 /* StrictModeSourceFileIncludes */ : 1 /* SourceFileIncludes */
    );
    exportedVariableStatement = false;
    const visited = visitEachChild(node, visitor, context);
    const statement = concatenate(visited.statements, taggedTemplateStringDeclarations && [
      factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList(taggedTemplateStringDeclarations)
      )
    ]);
    const result = factory2.updateSourceFile(visited, setTextRange(factory2.createNodeArray(statement), node.statements));
    exitSubtree(ancestorFacts);
    return result;
  }
  function visitTaggedTemplateExpression(node) {
    return processTaggedTemplateExpression(
      context,
      node,
      visitor,
      currentSourceFile,
      recordTaggedTemplateString,
      0 /* LiftRestriction */
    );
  }
  function visitBinaryExpression(node, expressionResultIsUnused2) {
    if (isDestructuringAssignment(node) && containsObjectRestOrSpread(node.left)) {
      return flattenDestructuringAssignment(
        node,
        visitor,
        context,
        1 /* ObjectRest */,
        !expressionResultIsUnused2
      );
    }
    if (node.operatorToken.kind === 28 /* CommaToken */) {
      return factory2.updateBinaryExpression(
        node,
        visitNode(node.left, visitorWithUnusedExpressionResult, isExpression),
        node.operatorToken,
        visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression)
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCommaListExpression(node, expressionResultIsUnused2) {
    if (expressionResultIsUnused2) {
      return visitEachChild(node, visitorWithUnusedExpressionResult, context);
    }
    let result;
    for (let i = 0; i < node.elements.length; i++) {
      const element = node.elements[i];
      const visited = visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, isExpression);
      if (result || visited !== element) {
        result || (result = node.elements.slice(0, i));
        result.push(visited);
      }
    }
    const elements = result ? setTextRange(factory2.createNodeArray(result), node.elements) : node.elements;
    return factory2.updateCommaListExpression(node, elements);
  }
  function visitCatchClause(node) {
    if (node.variableDeclaration && isBindingPattern(node.variableDeclaration.name) && node.variableDeclaration.name.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
      const name = factory2.getGeneratedNameForNode(node.variableDeclaration.name);
      const updatedDecl = factory2.updateVariableDeclaration(
        node.variableDeclaration,
        node.variableDeclaration.name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        name
      );
      const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
      let block = visitNode(node.block, visitor, isBlock);
      if (some(visitedBindings)) {
        block = factory2.updateBlock(block, [
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            visitedBindings
          ),
          ...block.statements
        ]);
      }
      return factory2.updateCatchClause(
        node,
        factory2.updateVariableDeclaration(
          node.variableDeclaration,
          name,
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        ),
        block
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitVariableStatement(node) {
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      const savedExportedVariableStatement = exportedVariableStatement;
      exportedVariableStatement = true;
      const visited = visitEachChild(node, visitor, context);
      exportedVariableStatement = savedExportedVariableStatement;
      return visited;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitVariableDeclaration(node) {
    if (exportedVariableStatement) {
      const savedExportedVariableStatement = exportedVariableStatement;
      exportedVariableStatement = false;
      const visited = visitVariableDeclarationWorker(
        node,
        /*exportedVariableStatement*/
        true
      );
      exportedVariableStatement = savedExportedVariableStatement;
      return visited;
    }
    return visitVariableDeclarationWorker(
      node,
      /*exportedVariableStatement*/
      false
    );
  }
  function visitVariableDeclarationWorker(node, exportedVariableStatement2) {
    if (isBindingPattern(node.name) && node.name.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
      return flattenDestructuringBinding(
        node,
        visitor,
        context,
        1 /* ObjectRest */,
        /*rval*/
        void 0,
        exportedVariableStatement2
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitForStatement(node) {
    return factory2.updateForStatement(
      node,
      visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression),
      visitIterationBody(node.statement, visitor, context)
    );
  }
  function visitVoidExpression(node) {
    return visitEachChild(node, visitorWithUnusedExpressionResult, context);
  }
  function visitForOfStatement(node, outermostLabeledStatement) {
    const ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
    if (node.initializer.transformFlags & 65536 /* ContainsObjectRestOrSpread */ || isAssignmentPattern(node.initializer) && containsObjectRestOrSpread(node.initializer)) {
      node = transformForOfStatementWithObjectRest(node);
    }
    const result = node.awaitModifier ? transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : factory2.restoreEnclosingLabel(visitEachChild(node, visitor, context), outermostLabeledStatement);
    exitSubtree(ancestorFacts);
    return result;
  }
  function transformForOfStatementWithObjectRest(node) {
    const initializerWithoutParens = skipParentheses(node.initializer);
    if (isVariableDeclarationList(initializerWithoutParens) || isAssignmentPattern(initializerWithoutParens)) {
      let bodyLocation;
      let statementsLocation;
      const temp = factory2.createTempVariable(
        /*recordTempVariable*/
        void 0
      );
      const statements = [createForOfBindingStatement(factory2, initializerWithoutParens, temp)];
      if (isBlock(node.statement)) {
        addRange(statements, node.statement.statements);
        bodyLocation = node.statement;
        statementsLocation = node.statement.statements;
      } else if (node.statement) {
        append(statements, node.statement);
        bodyLocation = node.statement;
        statementsLocation = node.statement;
      }
      return factory2.updateForOfStatement(
        node,
        node.awaitModifier,
        setTextRange(
          factory2.createVariableDeclarationList(
            [
              setTextRange(factory2.createVariableDeclaration(temp), node.initializer)
            ],
            1 /* Let */
          ),
          node.initializer
        ),
        node.expression,
        setTextRange(
          factory2.createBlock(
            setTextRange(factory2.createNodeArray(statements), statementsLocation),
            /*multiLine*/
            true
          ),
          bodyLocation
        )
      );
    }
    return node;
  }
  function convertForOfStatementHead(node, boundValue, nonUserCode) {
    const value = factory2.createTempVariable(hoistVariableDeclaration);
    const iteratorValueExpression = factory2.createAssignment(value, boundValue);
    const iteratorValueStatement = factory2.createExpressionStatement(iteratorValueExpression);
    setSourceMapRange(iteratorValueStatement, node.expression);
    const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse());
    const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression);
    setSourceMapRange(exitNonUserCodeStatement, node.expression);
    const statements = [iteratorValueStatement, exitNonUserCodeStatement];
    const binding = createForOfBindingStatement(factory2, node.initializer, value);
    statements.push(visitNode(binding, visitor, isStatement));
    let bodyLocation;
    let statementsLocation;
    const statement = visitIterationBody(node.statement, visitor, context);
    if (isBlock(statement)) {
      addRange(statements, statement.statements);
      bodyLocation = statement;
      statementsLocation = statement.statements;
    } else {
      statements.push(statement);
    }
    return setTextRange(
      factory2.createBlock(
        setTextRange(factory2.createNodeArray(statements), statementsLocation),
        /*multiLine*/
        true
      ),
      bodyLocation
    );
  }
  function createDownlevelAwait(expression) {
    return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression(
      /*asteriskToken*/
      void 0,
      emitHelpers().createAwaitHelper(expression)
    ) : factory2.createAwaitExpression(expression);
  }
  function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
    const expression = visitNode(node.expression, visitor, isExpression);
    const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const nonUserCode = factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const done = factory2.createTempVariable(hoistVariableDeclaration);
    const errorRecord = factory2.createUniqueName("e");
    const catchVariable = factory2.getGeneratedNameForNode(errorRecord);
    const returnMethod = factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const callValues = setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
    const callNext = factory2.createCallExpression(
      factory2.createPropertyAccessExpression(iterator, "next"),
      /*typeArguments*/
      void 0,
      []
    );
    const getDone = factory2.createPropertyAccessExpression(result, "done");
    const getValue = factory2.createPropertyAccessExpression(result, "value");
    const callReturn = factory2.createFunctionCallCall(returnMethod, iterator, []);
    hoistVariableDeclaration(errorRecord);
    hoistVariableDeclaration(returnMethod);
    const initializer = ancestorFacts & 2 /* IterationContainer */ ? factory2.inlineExpressions([factory2.createAssignment(errorRecord, factory2.createVoidZero()), callValues]) : callValues;
    const forStatement = setEmitFlags(
      setTextRange(
        factory2.createForStatement(
          /*initializer*/
          setEmitFlags(
            setTextRange(
              factory2.createVariableDeclarationList([
                factory2.createVariableDeclaration(
                  nonUserCode,
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  factory2.createTrue()
                ),
                setTextRange(factory2.createVariableDeclaration(
                  iterator,
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  initializer
                ), node.expression),
                factory2.createVariableDeclaration(result)
              ]),
              node.expression
            ),
            4194304 /* NoHoisting */
          ),
          /*condition*/
          factory2.inlineExpressions([
            factory2.createAssignment(result, createDownlevelAwait(callNext)),
            factory2.createAssignment(done, getDone),
            factory2.createLogicalNot(done)
          ]),
          /*incrementor*/
          factory2.createAssignment(nonUserCode, factory2.createTrue()),
          /*statement*/
          convertForOfStatementHead(node, getValue, nonUserCode)
        ),
        /*location*/
        node
      ),
      512 /* NoTokenTrailingSourceMaps */
    );
    setOriginalNode(forStatement, node);
    return factory2.createTryStatement(
      factory2.createBlock([
        factory2.restoreEnclosingLabel(
          forStatement,
          outermostLabeledStatement
        )
      ]),
      factory2.createCatchClause(
        factory2.createVariableDeclaration(catchVariable),
        setEmitFlags(
          factory2.createBlock([
            factory2.createExpressionStatement(
              factory2.createAssignment(
                errorRecord,
                factory2.createObjectLiteralExpression([
                  factory2.createPropertyAssignment("error", catchVariable)
                ])
              )
            )
          ]),
          1 /* SingleLine */
        )
      ),
      factory2.createBlock([
        factory2.createTryStatement(
          /*tryBlock*/
          factory2.createBlock([
            setEmitFlags(
              factory2.createIfStatement(
                factory2.createLogicalAnd(
                  factory2.createLogicalAnd(
                    factory2.createLogicalNot(nonUserCode),
                    factory2.createLogicalNot(done)
                  ),
                  factory2.createAssignment(
                    returnMethod,
                    factory2.createPropertyAccessExpression(iterator, "return")
                  )
                ),
                factory2.createExpressionStatement(createDownlevelAwait(callReturn))
              ),
              1 /* SingleLine */
            )
          ]),
          /*catchClause*/
          void 0,
          /*finallyBlock*/
          setEmitFlags(
            factory2.createBlock([
              setEmitFlags(
                factory2.createIfStatement(
                  errorRecord,
                  factory2.createThrowStatement(
                    factory2.createPropertyAccessExpression(errorRecord, "error")
                  )
                ),
                1 /* SingleLine */
              )
            ]),
            1 /* SingleLine */
          )
        )
      ])
    );
  }
  function parameterVisitor(node) {
    Debug.assertNode(node, isParameter);
    return visitParameter(node);
  }
  function visitParameter(node) {
    if (parametersWithPrecedingObjectRestOrSpread == null ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) {
      return factory2.updateParameterDeclaration(
        node,
        /*modifiers*/
        void 0,
        node.dotDotDotToken,
        isBindingPattern(node.name) ? factory2.getGeneratedNameForNode(node) : node.name,
        /*questionToken*/
        void 0,
        /*type*/
        void 0,
        /*initializer*/
        void 0
      );
    }
    if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
      return factory2.updateParameterDeclaration(
        node,
        /*modifiers*/
        void 0,
        node.dotDotDotToken,
        factory2.getGeneratedNameForNode(node),
        /*questionToken*/
        void 0,
        /*type*/
        void 0,
        visitNode(node.initializer, visitor, isExpression)
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function collectParametersWithPrecedingObjectRestOrSpread(node) {
    let parameters;
    for (const parameter of node.parameters) {
      if (parameters) {
        parameters.add(parameter);
      } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
        parameters = /* @__PURE__ */ new Set();
      }
    }
    return parameters;
  }
  function visitConstructorDeclaration(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateConstructorDeclaration(
      node,
      node.modifiers,
      visitParameterList(node.parameters, parameterVisitor, context),
      transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function visitGetAccessorDeclaration(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateGetAccessorDeclaration(
      node,
      node.modifiers,
      visitNode(node.name, visitor, isPropertyName),
      visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function visitSetAccessorDeclaration(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateSetAccessorDeclaration(
      node,
      node.modifiers,
      visitNode(node.name, visitor, isPropertyName),
      visitParameterList(node.parameters, parameterVisitor, context),
      transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function visitMethodDeclaration(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateMethodDeclaration(
      node,
      enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifierLike) : node.modifiers,
      enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken,
      visitNode(node.name, visitor, isPropertyName),
      visitNode(
        /*node*/
        void 0,
        visitor,
        isQuestionToken
      ),
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function visitFunctionDeclaration(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateFunctionDeclaration(
      node,
      enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers,
      enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function visitArrowFunction(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateArrowFunction(
      node,
      node.modifiers,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      node.equalsGreaterThanToken,
      transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function visitFunctionExpression(node) {
    const savedEnclosingFunctionFlags = enclosingFunctionFlags;
    const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
    enclosingFunctionFlags = getFunctionFlags(node);
    parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
    const updated = factory2.updateFunctionExpression(
      node,
      enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers,
      enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function transformAsyncGeneratorFunctionBody(node) {
    resumeLexicalEnvironment();
    const statements = [];
    const statementOffset = factory2.copyPrologue(
      node.body.statements,
      statements,
      /*ensureUseStrict*/
      false,
      visitor
    );
    appendObjectRestAssignmentsIfNeeded(statements, node);
    const savedCapturedSuperProperties = capturedSuperProperties;
    const savedHasSuperElementAccess = hasSuperElementAccess;
    capturedSuperProperties = /* @__PURE__ */ new Set();
    hasSuperElementAccess = false;
    const returnStatement = factory2.createReturnStatement(
      emitHelpers().createAsyncGeneratorHelper(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          factory2.createToken(42 /* AsteriskToken */),
          node.name && factory2.getGeneratedNameForNode(node.name),
          /*typeParameters*/
          void 0,
          /*parameters*/
          [],
          /*type*/
          void 0,
          factory2.updateBlock(
            node.body,
            visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)
          )
        ),
        !!(hierarchyFacts & 1 /* HasLexicalThis */)
      )
    );
    const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */);
    if (emitSuperHelpers) {
      enableSubstitutionForAsyncMethodsWithSuper();
      const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties);
      substitutedSuperAccessors[getNodeId(variableStatement)] = true;
      insertStatementsAfterStandardPrologue(statements, [variableStatement]);
    }
    statements.push(returnStatement);
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    const block = factory2.updateBlock(node.body, statements);
    if (emitSuperHelpers && hasSuperElementAccess) {
      if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) {
        addEmitHelper(block, advancedAsyncSuperHelper);
      } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) {
        addEmitHelper(block, asyncSuperHelper);
      }
    }
    capturedSuperProperties = savedCapturedSuperProperties;
    hasSuperElementAccess = savedHasSuperElementAccess;
    return block;
  }
  function transformFunctionBody2(node) {
    resumeLexicalEnvironment();
    let statementOffset = 0;
    const statements = [];
    const body = visitNode(node.body, visitor, isConciseBody) ?? factory2.createBlock([]);
    if (isBlock(body)) {
      statementOffset = factory2.copyPrologue(
        body.statements,
        statements,
        /*ensureUseStrict*/
        false,
        visitor
      );
    }
    addRange(statements, appendObjectRestAssignmentsIfNeeded(
      /*statements*/
      void 0,
      node
    ));
    const leadingStatements = endLexicalEnvironment();
    if (statementOffset > 0 || some(statements) || some(leadingStatements)) {
      const block = factory2.converters.convertToFunctionBlock(
        body,
        /*multiLine*/
        true
      );
      insertStatementsAfterStandardPrologue(statements, leadingStatements);
      addRange(statements, block.statements.slice(statementOffset));
      return factory2.updateBlock(block, setTextRange(factory2.createNodeArray(statements), block.statements));
    }
    return body;
  }
  function appendObjectRestAssignmentsIfNeeded(statements, node) {
    let containsPrecedingObjectRestOrSpread = false;
    for (const parameter of node.parameters) {
      if (containsPrecedingObjectRestOrSpread) {
        if (isBindingPattern(parameter.name)) {
          if (parameter.name.elements.length > 0) {
            const declarations = flattenDestructuringBinding(
              parameter,
              visitor,
              context,
              0 /* All */,
              factory2.getGeneratedNameForNode(parameter)
            );
            if (some(declarations)) {
              const declarationList = factory2.createVariableDeclarationList(declarations);
              const statement = factory2.createVariableStatement(
                /*modifiers*/
                void 0,
                declarationList
              );
              setEmitFlags(statement, 2097152 /* CustomPrologue */);
              statements = append(statements, statement);
            }
          } else if (parameter.initializer) {
            const name = factory2.getGeneratedNameForNode(parameter);
            const initializer = visitNode(parameter.initializer, visitor, isExpression);
            const assignment = factory2.createAssignment(name, initializer);
            const statement = factory2.createExpressionStatement(assignment);
            setEmitFlags(statement, 2097152 /* CustomPrologue */);
            statements = append(statements, statement);
          }
        } else if (parameter.initializer) {
          const name = factory2.cloneNode(parameter.name);
          setTextRange(name, parameter.name);
          setEmitFlags(name, 96 /* NoSourceMap */);
          const initializer = visitNode(parameter.initializer, visitor, isExpression);
          addEmitFlags(initializer, 96 /* NoSourceMap */ | 3072 /* NoComments */);
          const assignment = factory2.createAssignment(name, initializer);
          setTextRange(assignment, parameter);
          setEmitFlags(assignment, 3072 /* NoComments */);
          const block = factory2.createBlock([factory2.createExpressionStatement(assignment)]);
          setTextRange(block, parameter);
          setEmitFlags(block, 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */);
          const typeCheck = factory2.createTypeCheck(factory2.cloneNode(parameter.name), "undefined");
          const statement = factory2.createIfStatement(typeCheck, block);
          startOnNewLine(statement);
          setTextRange(statement, parameter);
          setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2097152 /* CustomPrologue */ | 3072 /* NoComments */);
          statements = append(statements, statement);
        }
      } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */) {
        containsPrecedingObjectRestOrSpread = true;
        const declarations = flattenDestructuringBinding(
          parameter,
          visitor,
          context,
          1 /* ObjectRest */,
          factory2.getGeneratedNameForNode(parameter),
          /*hoistTempVariables*/
          false,
          /*skipInitializer*/
          true
        );
        if (some(declarations)) {
          const declarationList = factory2.createVariableDeclarationList(declarations);
          const statement = factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            declarationList
          );
          setEmitFlags(statement, 2097152 /* CustomPrologue */);
          statements = append(statements, statement);
        }
      }
    }
    return statements;
  }
  function enableSubstitutionForAsyncMethodsWithSuper() {
    if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
      enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
      context.enableSubstitution(212 /* CallExpression */);
      context.enableSubstitution(210 /* PropertyAccessExpression */);
      context.enableSubstitution(211 /* ElementAccessExpression */);
      context.enableEmitNotification(262 /* ClassDeclaration */);
      context.enableEmitNotification(173 /* MethodDeclaration */);
      context.enableEmitNotification(176 /* GetAccessor */);
      context.enableEmitNotification(177 /* SetAccessor */);
      context.enableEmitNotification(175 /* Constructor */);
      context.enableEmitNotification(242 /* VariableStatement */);
    }
  }
  function onEmitNode(hint, node, emitCallback) {
    if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
      const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */);
      if (superContainerFlags !== enclosingSuperContainerFlags) {
        const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
        enclosingSuperContainerFlags = superContainerFlags;
        previousOnEmitNode(hint, node, emitCallback);
        enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
        return;
      }
    } else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) {
      const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
      enclosingSuperContainerFlags = 0;
      previousOnEmitNode(hint, node, emitCallback);
      enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
      return;
    }
    previousOnEmitNode(hint, node, emitCallback);
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
      return substituteExpression(node);
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 210 /* PropertyAccessExpression */:
        return substitutePropertyAccessExpression(node);
      case 211 /* ElementAccessExpression */:
        return substituteElementAccessExpression(node);
      case 212 /* CallExpression */:
        return substituteCallExpression(node);
    }
    return node;
  }
  function substitutePropertyAccessExpression(node) {
    if (node.expression.kind === 108 /* SuperKeyword */) {
      return setTextRange(
        factory2.createPropertyAccessExpression(
          factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */),
          node.name
        ),
        node
      );
    }
    return node;
  }
  function substituteElementAccessExpression(node) {
    if (node.expression.kind === 108 /* SuperKeyword */) {
      return createSuperElementAccessInAsyncMethod(
        node.argumentExpression,
        node
      );
    }
    return node;
  }
  function substituteCallExpression(node) {
    const expression = node.expression;
    if (isSuperProperty(expression)) {
      const argumentExpression = isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression);
      return factory2.createCallExpression(
        factory2.createPropertyAccessExpression(argumentExpression, "call"),
        /*typeArguments*/
        void 0,
        [
          factory2.createThis(),
          ...node.arguments
        ]
      );
    }
    return node;
  }
  function isSuperContainer(node) {
    const kind = node.kind;
    return kind === 262 /* ClassDeclaration */ || kind === 175 /* Constructor */ || kind === 173 /* MethodDeclaration */ || kind === 176 /* GetAccessor */ || kind === 177 /* SetAccessor */;
  }
  function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
    if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */) {
      return setTextRange(
        factory2.createPropertyAccessExpression(
          factory2.createCallExpression(
            factory2.createIdentifier("_superIndex"),
            /*typeArguments*/
            void 0,
            [argumentExpression]
          ),
          "value"
        ),
        location
      );
    } else {
      return setTextRange(
        factory2.createCallExpression(
          factory2.createIdentifier("_superIndex"),
          /*typeArguments*/
          void 0,
          [argumentExpression]
        ),
        location
      );
    }
  }
}

// src/compiler/transformers/es2019.ts
function transformES2019(context) {
  const factory2 = context.factory;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 64 /* ContainsES2019 */) === 0) {
      return node;
    }
    switch (node.kind) {
      case 298 /* CatchClause */:
        return visitCatchClause(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitCatchClause(node) {
    if (!node.variableDeclaration) {
      return factory2.updateCatchClause(
        node,
        factory2.createVariableDeclaration(factory2.createTempVariable(
          /*recordTempVariable*/
          void 0
        )),
        visitNode(node.block, visitor, isBlock)
      );
    }
    return visitEachChild(node, visitor, context);
  }
}

// src/compiler/transformers/es2020.ts
function transformES2020(context) {
  const {
    factory: factory2,
    hoistVariableDeclaration
  } = context;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 32 /* ContainsES2020 */) === 0) {
      return node;
    }
    switch (node.kind) {
      case 212 /* CallExpression */: {
        const updated = visitNonOptionalCallExpression(
          node,
          /*captureThisArg*/
          false
        );
        Debug.assertNotNode(updated, isSyntheticReference);
        return updated;
      }
      case 210 /* PropertyAccessExpression */:
      case 211 /* ElementAccessExpression */:
        if (isOptionalChain(node)) {
          const updated = visitOptionalExpression(
            node,
            /*captureThisArg*/
            false,
            /*isDelete*/
            false
          );
          Debug.assertNotNode(updated, isSyntheticReference);
          return updated;
        }
        return visitEachChild(node, visitor, context);
      case 225 /* BinaryExpression */:
        if (node.operatorToken.kind === 61 /* QuestionQuestionToken */) {
          return transformNullishCoalescingExpression(node);
        }
        return visitEachChild(node, visitor, context);
      case 219 /* DeleteExpression */:
        return visitDeleteExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function flattenChain(chain) {
    Debug.assertNotNode(chain, isNonNullChain);
    const links = [chain];
    while (!chain.questionDotToken && !isTaggedTemplateExpression(chain)) {
      chain = cast(skipPartiallyEmittedExpressions(chain.expression), isOptionalChain);
      Debug.assertNotNode(chain, isNonNullChain);
      links.unshift(chain);
    }
    return { expression: chain.expression, chain: links };
  }
  function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
    const expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
    if (isSyntheticReference(expression)) {
      return factory2.createSyntheticReferenceExpression(factory2.updateParenthesizedExpression(node, expression.expression), expression.thisArg);
    }
    return factory2.updateParenthesizedExpression(node, expression);
  }
  function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
    if (isOptionalChain(node)) {
      return visitOptionalExpression(node, captureThisArg, isDelete);
    }
    let expression = visitNode(node.expression, visitor, isExpression);
    Debug.assertNotNode(expression, isSyntheticReference);
    let thisArg;
    if (captureThisArg) {
      if (!isSimpleCopiableExpression(expression)) {
        thisArg = factory2.createTempVariable(hoistVariableDeclaration);
        expression = factory2.createAssignment(thisArg, expression);
      } else {
        thisArg = expression;
      }
    }
    expression = node.kind === 210 /* PropertyAccessExpression */ ? factory2.updatePropertyAccessExpression(node, expression, visitNode(node.name, visitor, isIdentifier)) : factory2.updateElementAccessExpression(node, expression, visitNode(node.argumentExpression, visitor, isExpression));
    return thisArg ? factory2.createSyntheticReferenceExpression(expression, thisArg) : expression;
  }
  function visitNonOptionalCallExpression(node, captureThisArg) {
    if (isOptionalChain(node)) {
      return visitOptionalExpression(
        node,
        captureThisArg,
        /*isDelete*/
        false
      );
    }
    if (isParenthesizedExpression(node.expression) && isOptionalChain(skipParentheses(node.expression))) {
      const expression = visitNonOptionalParenthesizedExpression(
        node.expression,
        /*captureThisArg*/
        true,
        /*isDelete*/
        false
      );
      const args = visitNodes2(node.arguments, visitor, isExpression);
      if (isSyntheticReference(expression)) {
        return setTextRange(factory2.createFunctionCallCall(expression.expression, expression.thisArg, args), node);
      }
      return factory2.updateCallExpression(
        node,
        expression,
        /*typeArguments*/
        void 0,
        args
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitNonOptionalExpression(node, captureThisArg, isDelete) {
    switch (node.kind) {
      case 216 /* ParenthesizedExpression */:
        return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
      case 210 /* PropertyAccessExpression */:
      case 211 /* ElementAccessExpression */:
        return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
      case 212 /* CallExpression */:
        return visitNonOptionalCallExpression(node, captureThisArg);
      default:
        return visitNode(node, visitor, isExpression);
    }
  }
  function visitOptionalExpression(node, captureThisArg, isDelete) {
    const { expression, chain } = flattenChain(node);
    const left = visitNonOptionalExpression(
      skipPartiallyEmittedExpressions(expression),
      isCallChain(chain[0]),
      /*isDelete*/
      false
    );
    let leftThisArg = isSyntheticReference(left) ? left.thisArg : void 0;
    let capturedLeft = isSyntheticReference(left) ? left.expression : left;
    let leftExpression = factory2.restoreOuterExpressions(expression, capturedLeft, 8 /* PartiallyEmittedExpressions */);
    if (!isSimpleCopiableExpression(capturedLeft)) {
      capturedLeft = factory2.createTempVariable(hoistVariableDeclaration);
      leftExpression = factory2.createAssignment(capturedLeft, leftExpression);
    }
    let rightExpression = capturedLeft;
    let thisArg;
    for (let i = 0; i < chain.length; i++) {
      const segment = chain[i];
      switch (segment.kind) {
        case 210 /* PropertyAccessExpression */:
        case 211 /* ElementAccessExpression */:
          if (i === chain.length - 1 && captureThisArg) {
            if (!isSimpleCopiableExpression(rightExpression)) {
              thisArg = factory2.createTempVariable(hoistVariableDeclaration);
              rightExpression = factory2.createAssignment(thisArg, rightExpression);
            } else {
              thisArg = rightExpression;
            }
          }
          rightExpression = segment.kind === 210 /* PropertyAccessExpression */ ? factory2.createPropertyAccessExpression(rightExpression, visitNode(segment.name, visitor, isIdentifier)) : factory2.createElementAccessExpression(rightExpression, visitNode(segment.argumentExpression, visitor, isExpression));
          break;
        case 212 /* CallExpression */:
          if (i === 0 && leftThisArg) {
            if (!isGeneratedIdentifier(leftThisArg)) {
              leftThisArg = factory2.cloneNode(leftThisArg);
              addEmitFlags(leftThisArg, 3072 /* NoComments */);
            }
            rightExpression = factory2.createFunctionCallCall(
              rightExpression,
              leftThisArg.kind === 108 /* SuperKeyword */ ? factory2.createThis() : leftThisArg,
              visitNodes2(segment.arguments, visitor, isExpression)
            );
          } else {
            rightExpression = factory2.createCallExpression(
              rightExpression,
              /*typeArguments*/
              void 0,
              visitNodes2(segment.arguments, visitor, isExpression)
            );
          }
          break;
      }
      setOriginalNode(rightExpression, segment);
    }
    const target = isDelete ? factory2.createConditionalExpression(
      createNotNullCondition(
        leftExpression,
        capturedLeft,
        /*invert*/
        true
      ),
      /*questionToken*/
      void 0,
      factory2.createTrue(),
      /*colonToken*/
      void 0,
      factory2.createDeleteExpression(rightExpression)
    ) : factory2.createConditionalExpression(
      createNotNullCondition(
        leftExpression,
        capturedLeft,
        /*invert*/
        true
      ),
      /*questionToken*/
      void 0,
      factory2.createVoidZero(),
      /*colonToken*/
      void 0,
      rightExpression
    );
    setTextRange(target, node);
    return thisArg ? factory2.createSyntheticReferenceExpression(target, thisArg) : target;
  }
  function createNotNullCondition(left, right, invert) {
    return factory2.createBinaryExpression(
      factory2.createBinaryExpression(
        left,
        factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */),
        factory2.createNull()
      ),
      factory2.createToken(invert ? 57 /* BarBarToken */ : 56 /* AmpersandAmpersandToken */),
      factory2.createBinaryExpression(
        right,
        factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */),
        factory2.createVoidZero()
      )
    );
  }
  function transformNullishCoalescingExpression(node) {
    let left = visitNode(node.left, visitor, isExpression);
    let right = left;
    if (!isSimpleCopiableExpression(left)) {
      right = factory2.createTempVariable(hoistVariableDeclaration);
      left = factory2.createAssignment(right, left);
    }
    return setTextRange(factory2.createConditionalExpression(
      createNotNullCondition(left, right),
      /*questionToken*/
      void 0,
      right,
      /*colonToken*/
      void 0,
      visitNode(node.right, visitor, isExpression)
    ), node);
  }
  function visitDeleteExpression(node) {
    return isOptionalChain(skipParentheses(node.expression)) ? setOriginalNode(visitNonOptionalExpression(
      node.expression,
      /*captureThisArg*/
      false,
      /*isDelete*/
      true
    ), node) : factory2.updateDeleteExpression(node, visitNode(node.expression, visitor, isExpression));
  }
}

// src/compiler/transformers/es2021.ts
function transformES2021(context) {
  const {
    hoistVariableDeclaration,
    factory: factory2
  } = context;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 16 /* ContainsES2021 */) === 0) {
      return node;
    }
    if (isLogicalOrCoalescingAssignmentExpression(node)) {
      return transformLogicalAssignment(node);
    }
    return visitEachChild(node, visitor, context);
  }
  function transformLogicalAssignment(binaryExpression) {
    const operator = binaryExpression.operatorToken;
    const nonAssignmentOperator = getNonAssignmentOperatorForCompoundAssignment(operator.kind);
    let left = skipParentheses(visitNode(binaryExpression.left, visitor, isLeftHandSideExpression));
    let assignmentTarget = left;
    const right = skipParentheses(visitNode(binaryExpression.right, visitor, isExpression));
    if (isAccessExpression(left)) {
      const propertyAccessTargetSimpleCopiable = isSimpleCopiableExpression(left.expression);
      const propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createTempVariable(hoistVariableDeclaration);
      const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createAssignment(
        propertyAccessTarget,
        left.expression
      );
      if (isPropertyAccessExpression(left)) {
        assignmentTarget = factory2.createPropertyAccessExpression(
          propertyAccessTarget,
          left.name
        );
        left = factory2.createPropertyAccessExpression(
          propertyAccessTargetAssignment,
          left.name
        );
      } else {
        const elementAccessArgumentSimpleCopiable = isSimpleCopiableExpression(left.argumentExpression);
        const elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createTempVariable(hoistVariableDeclaration);
        assignmentTarget = factory2.createElementAccessExpression(
          propertyAccessTarget,
          elementAccessArgument
        );
        left = factory2.createElementAccessExpression(
          propertyAccessTargetAssignment,
          elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createAssignment(
            elementAccessArgument,
            left.argumentExpression
          )
        );
      }
    }
    return factory2.createBinaryExpression(
      left,
      nonAssignmentOperator,
      factory2.createParenthesizedExpression(
        factory2.createAssignment(
          assignmentTarget,
          right
        )
      )
    );
  }
}

// src/compiler/transformers/esnext.ts
function transformESNext(context) {
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
      return node;
    }
    switch (node.kind) {
      default:
        return visitEachChild(node, visitor, context);
    }
  }
}

// src/compiler/transformers/jsx.ts
function transformJsx(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers
  } = context;
  const compilerOptions = context.getCompilerOptions();
  let currentSourceFile;
  let currentFileState;
  return chainBundle(context, transformSourceFile);
  function getCurrentFileNameExpression() {
    if (currentFileState.filenameDeclaration) {
      return currentFileState.filenameDeclaration.name;
    }
    const declaration = factory2.createVariableDeclaration(
      factory2.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */),
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      factory2.createStringLiteral(currentSourceFile.fileName)
    );
    currentFileState.filenameDeclaration = declaration;
    return currentFileState.filenameDeclaration.name;
  }
  function getJsxFactoryCalleePrimitive(isStaticChildren) {
    return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx";
  }
  function getJsxFactoryCallee(isStaticChildren) {
    const type = getJsxFactoryCalleePrimitive(isStaticChildren);
    return getImplicitImportForName(type);
  }
  function getImplicitJsxFragmentReference() {
    return getImplicitImportForName("Fragment");
  }
  function getImplicitImportForName(name) {
    var _a, _b;
    const importSource = name === "createElement" ? currentFileState.importSpecifier : getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions);
    const existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) == null ? void 0 : _a.get(importSource)) == null ? void 0 : _b.get(name);
    if (existing) {
      return existing.name;
    }
    if (!currentFileState.utilizedImplicitRuntimeImports) {
      currentFileState.utilizedImplicitRuntimeImports = /* @__PURE__ */ new Map();
    }
    let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
    if (!specifierSourceImports) {
      specifierSourceImports = /* @__PURE__ */ new Map();
      currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
    }
    const generatedName = factory2.createUniqueName(`_${name}`, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */);
    const specifier = factory2.createImportSpecifier(
      /*isTypeOnly*/
      false,
      factory2.createIdentifier(name),
      generatedName
    );
    setIdentifierGeneratedImportReference(generatedName, specifier);
    specifierSourceImports.set(name, specifier);
    return generatedName;
  }
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    currentSourceFile = node;
    currentFileState = {};
    currentFileState.importSpecifier = getJSXImplicitImportBase(compilerOptions, node);
    let visited = visitEachChild(node, visitor, context);
    addEmitHelpers(visited, context.readEmitHelpers());
    let statements = visited.statements;
    if (currentFileState.filenameDeclaration) {
      statements = insertStatementAfterCustomPrologue(statements.slice(), factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */)
      ));
    }
    if (currentFileState.utilizedImplicitRuntimeImports) {
      for (const [importSource, importSpecifiersMap] of arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries())) {
        if (isExternalModule(node)) {
          const importStatement = factory2.createImportDeclaration(
            /*modifiers*/
            void 0,
            factory2.createImportClause(
              /*isTypeOnly*/
              false,
              /*name*/
              void 0,
              factory2.createNamedImports(arrayFrom(importSpecifiersMap.values()))
            ),
            factory2.createStringLiteral(importSource),
            /*assertClause*/
            void 0
          );
          setParentRecursive(
            importStatement,
            /*incremental*/
            false
          );
          statements = insertStatementAfterCustomPrologue(statements.slice(), importStatement);
        } else if (isExternalOrCommonJsModule(node)) {
          const requireStatement = factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList([
              factory2.createVariableDeclaration(
                factory2.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), (s) => factory2.createBindingElement(
                  /*dotDotDotToken*/
                  void 0,
                  s.propertyName,
                  s.name
                ))),
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                factory2.createCallExpression(
                  factory2.createIdentifier("require"),
                  /*typeArguments*/
                  void 0,
                  [factory2.createStringLiteral(importSource)]
                )
              )
            ], 2 /* Const */)
          );
          setParentRecursive(
            requireStatement,
            /*incremental*/
            false
          );
          statements = insertStatementAfterCustomPrologue(statements.slice(), requireStatement);
        } else {
        }
      }
    }
    if (statements !== visited.statements) {
      visited = factory2.updateSourceFile(visited, statements);
    }
    currentFileState = void 0;
    return visited;
  }
  function visitor(node) {
    if (node.transformFlags & 2 /* ContainsJsx */) {
      return visitorWorker(node);
    } else {
      return node;
    }
  }
  function visitorWorker(node) {
    switch (node.kind) {
      case 283 /* JsxElement */:
        return visitJsxElement(
          node,
          /*isChild*/
          false
        );
      case 284 /* JsxSelfClosingElement */:
        return visitJsxSelfClosingElement(
          node,
          /*isChild*/
          false
        );
      case 287 /* JsxFragment */:
        return visitJsxFragment(
          node,
          /*isChild*/
          false
        );
      case 293 /* JsxExpression */:
        return visitJsxExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function transformJsxChildToExpression(node) {
    switch (node.kind) {
      case 12 /* JsxText */:
        return visitJsxText(node);
      case 293 /* JsxExpression */:
        return visitJsxExpression(node);
      case 283 /* JsxElement */:
        return visitJsxElement(
          node,
          /*isChild*/
          true
        );
      case 284 /* JsxSelfClosingElement */:
        return visitJsxSelfClosingElement(
          node,
          /*isChild*/
          true
        );
      case 287 /* JsxFragment */:
        return visitJsxFragment(
          node,
          /*isChild*/
          true
        );
      default:
        return Debug.failBadSyntaxKind(node);
    }
  }
  function hasProto(obj) {
    return obj.properties.some((p) => isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__"));
  }
  function hasKeyAfterPropsSpread(node) {
    let spread = false;
    for (const elem of node.attributes.properties) {
      if (isJsxSpreadAttribute(elem) && (!isObjectLiteralExpression(elem.expression) || elem.expression.properties.some(isSpreadAssignment))) {
        spread = true;
      } else if (spread && isJsxAttribute(elem) && isIdentifier(elem.name) && elem.name.escapedText === "key") {
        return true;
      }
    }
    return false;
  }
  function shouldUseCreateElement(node) {
    return currentFileState.importSpecifier === void 0 || hasKeyAfterPropsSpread(node);
  }
  function visitJsxElement(node, isChild) {
    const tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
    return tagTransform(
      node.openingElement,
      node.children,
      isChild,
      /*location*/
      node
    );
  }
  function visitJsxSelfClosingElement(node, isChild) {
    const tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
    return tagTransform(
      node,
      /*children*/
      void 0,
      isChild,
      /*location*/
      node
    );
  }
  function visitJsxFragment(node, isChild) {
    const tagTransform = currentFileState.importSpecifier === void 0 ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX;
    return tagTransform(
      node.openingFragment,
      node.children,
      isChild,
      /*location*/
      node
    );
  }
  function convertJsxChildrenToChildrenPropObject(children) {
    const prop = convertJsxChildrenToChildrenPropAssignment(children);
    return prop && factory2.createObjectLiteralExpression([prop]);
  }
  function convertJsxChildrenToChildrenPropAssignment(children) {
    const nonWhitespaceChildren = getSemanticJsxChildren(children);
    if (length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) {
      const result2 = transformJsxChildToExpression(nonWhitespaceChildren[0]);
      return result2 && factory2.createPropertyAssignment("children", result2);
    }
    const result = mapDefined(children, transformJsxChildToExpression);
    return length(result) ? factory2.createPropertyAssignment("children", factory2.createArrayLiteralExpression(result)) : void 0;
  }
  function visitJsxOpeningLikeElementJSX(node, children, isChild, location) {
    const tagName = getTagName(node);
    const childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : void 0;
    const keyAttr = find(node.attributes.properties, (p) => !!p.name && isIdentifier(p.name) && p.name.escapedText === "key");
    const attrs = keyAttr ? filter(node.attributes.properties, (p) => p !== keyAttr) : node.attributes.properties;
    const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : factory2.createObjectLiteralExpression(childrenProp ? [childrenProp] : emptyArray);
    return visitJsxOpeningLikeElementOrFragmentJSX(
      tagName,
      objectProperties,
      keyAttr,
      children || emptyArray,
      isChild,
      location
    );
  }
  function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) {
    var _a;
    const nonWhitespaceChildren = getSemanticJsxChildren(children);
    const isStaticChildren = length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) == null ? void 0 : _a.dotDotDotToken);
    const args = [tagName, objectProperties];
    if (keyAttr) {
      args.push(transformJsxAttributeInitializer(keyAttr.initializer));
    }
    if (compilerOptions.jsx === 5 /* ReactJSXDev */) {
      const originalFile = getOriginalNode(currentSourceFile);
      if (originalFile && isSourceFile(originalFile)) {
        if (keyAttr === void 0) {
          args.push(factory2.createVoidZero());
        }
        args.push(isStaticChildren ? factory2.createTrue() : factory2.createFalse());
        const lineCol = getLineAndCharacterOfPosition(originalFile, location.pos);
        args.push(factory2.createObjectLiteralExpression([
          factory2.createPropertyAssignment("fileName", getCurrentFileNameExpression()),
          factory2.createPropertyAssignment("lineNumber", factory2.createNumericLiteral(lineCol.line + 1)),
          factory2.createPropertyAssignment("columnNumber", factory2.createNumericLiteral(lineCol.character + 1))
        ]));
        args.push(factory2.createThis());
      }
    }
    const element = setTextRange(
      factory2.createCallExpression(
        getJsxFactoryCallee(isStaticChildren),
        /*typeArguments*/
        void 0,
        args
      ),
      location
    );
    if (isChild) {
      startOnNewLine(element);
    }
    return element;
  }
  function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) {
    const tagName = getTagName(node);
    const attrs = node.attributes.properties;
    const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs) : factory2.createNull();
    const callee = currentFileState.importSpecifier === void 0 ? createJsxFactoryExpression(
      factory2,
      context.getEmitResolver().getJsxFactoryEntity(currentSourceFile),
      compilerOptions.reactNamespace,
      // TODO: GH#18217
      node
    ) : getImplicitImportForName("createElement");
    const element = createExpressionForJsxElement(
      factory2,
      callee,
      tagName,
      objectProperties,
      mapDefined(children, transformJsxChildToExpression),
      location
    );
    if (isChild) {
      startOnNewLine(element);
    }
    return element;
  }
  function visitJsxOpeningFragmentJSX(_node, children, isChild, location) {
    let childrenProps;
    if (children && children.length) {
      const result = convertJsxChildrenToChildrenPropObject(children);
      if (result) {
        childrenProps = result;
      }
    }
    return visitJsxOpeningLikeElementOrFragmentJSX(
      getImplicitJsxFragmentReference(),
      childrenProps || factory2.createObjectLiteralExpression([]),
      /*keyAttr*/
      void 0,
      children,
      isChild,
      location
    );
  }
  function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) {
    const element = createExpressionForJsxFragment(
      factory2,
      context.getEmitResolver().getJsxFactoryEntity(currentSourceFile),
      context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile),
      compilerOptions.reactNamespace,
      // TODO: GH#18217
      mapDefined(children, transformJsxChildToExpression),
      node,
      location
    );
    if (isChild) {
      startOnNewLine(element);
    }
    return element;
  }
  function transformJsxSpreadAttributeToProps(node) {
    if (isObjectLiteralExpression(node.expression) && !hasProto(node.expression)) {
      return node.expression.properties;
    }
    return factory2.createSpreadAssignment(Debug.checkDefined(visitNode(node.expression, visitor, isExpression)));
  }
  function transformJsxAttributesToObjectProps(attrs, children) {
    const target = getEmitScriptTarget(compilerOptions);
    return target && target >= 5 /* ES2018 */ ? factory2.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : transformJsxAttributesToExpression(attrs, children);
  }
  function transformJsxAttributesToProps(attrs, children) {
    const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread) => flatten(map(attrs2, (attr) => isSpread ? transformJsxSpreadAttributeToProps(attr) : transformJsxAttributeToObjectLiteralElement(attr)))));
    if (children) {
      props.push(children);
    }
    return props;
  }
  function transformJsxAttributesToExpression(attrs, children) {
    const expressions = [];
    let properties = [];
    for (const attr of attrs) {
      if (isJsxSpreadAttribute(attr)) {
        if (isObjectLiteralExpression(attr.expression) && !hasProto(attr.expression)) {
          for (const prop of attr.expression.properties) {
            if (isSpreadAssignment(prop)) {
              finishObjectLiteralIfNeeded();
              expressions.push(prop.expression);
              continue;
            }
            properties.push(prop);
          }
          continue;
        }
        finishObjectLiteralIfNeeded();
        expressions.push(Debug.checkDefined(visitNode(attr.expression, visitor, isExpression)));
        continue;
      }
      properties.push(transformJsxAttributeToObjectLiteralElement(attr));
    }
    if (children) {
      properties.push(children);
    }
    finishObjectLiteralIfNeeded();
    if (expressions.length && !isObjectLiteralExpression(expressions[0])) {
      expressions.unshift(factory2.createObjectLiteralExpression());
    }
    return singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions);
    function finishObjectLiteralIfNeeded() {
      if (properties.length) {
        expressions.push(factory2.createObjectLiteralExpression(properties));
        properties = [];
      }
    }
  }
  function transformJsxAttributeToObjectLiteralElement(node) {
    const name = getAttributeName(node);
    const expression = transformJsxAttributeInitializer(node.initializer);
    return factory2.createPropertyAssignment(name, expression);
  }
  function transformJsxAttributeInitializer(node) {
    if (node === void 0) {
      return factory2.createTrue();
    }
    if (node.kind === 11 /* StringLiteral */) {
      const singleQuote = node.singleQuote !== void 0 ? node.singleQuote : !isStringDoubleQuoted(node, currentSourceFile);
      const literal = factory2.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote);
      return setTextRange(literal, node);
    }
    if (node.kind === 293 /* JsxExpression */) {
      if (node.expression === void 0) {
        return factory2.createTrue();
      }
      return Debug.checkDefined(visitNode(node.expression, visitor, isExpression));
    }
    if (isJsxElement(node)) {
      return visitJsxElement(
        node,
        /*isChild*/
        false
      );
    }
    if (isJsxSelfClosingElement(node)) {
      return visitJsxSelfClosingElement(
        node,
        /*isChild*/
        false
      );
    }
    if (isJsxFragment(node)) {
      return visitJsxFragment(
        node,
        /*isChild*/
        false
      );
    }
    return Debug.failBadSyntaxKind(node);
  }
  function visitJsxText(node) {
    const fixed = fixupWhitespaceAndDecodeEntities(node.text);
    return fixed === void 0 ? void 0 : factory2.createStringLiteral(fixed);
  }
  function fixupWhitespaceAndDecodeEntities(text) {
    let acc;
    let firstNonWhitespace = 0;
    let lastNonWhitespace = -1;
    for (let i = 0; i < text.length; i++) {
      const c = text.charCodeAt(i);
      if (isLineBreak(c)) {
        if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
          acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
        }
        firstNonWhitespace = -1;
      } else if (!isWhiteSpaceSingleLine(c)) {
        lastNonWhitespace = i;
        if (firstNonWhitespace === -1) {
          firstNonWhitespace = i;
        }
      }
    }
    return firstNonWhitespace !== -1 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace)) : acc;
  }
  function addLineOfJsxText(acc, trimmedLine) {
    const decoded = decodeEntities(trimmedLine);
    return acc === void 0 ? decoded : acc + " " + decoded;
  }
  function decodeEntities(text) {
    return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, (match, _all, _number, _digits, decimal, hex, word) => {
      if (decimal) {
        return utf16EncodeAsString(parseInt(decimal, 10));
      } else if (hex) {
        return utf16EncodeAsString(parseInt(hex, 16));
      } else {
        const ch = entities.get(word);
        return ch ? utf16EncodeAsString(ch) : match;
      }
    });
  }
  function tryDecodeEntities(text) {
    const decoded = decodeEntities(text);
    return decoded === text ? void 0 : decoded;
  }
  function getTagName(node) {
    if (node.kind === 283 /* JsxElement */) {
      return getTagName(node.openingElement);
    } else {
      const tagName = node.tagName;
      if (isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText)) {
        return factory2.createStringLiteral(idText(tagName));
      } else if (isJsxNamespacedName(tagName)) {
        return factory2.createStringLiteral(idText(tagName.namespace) + ":" + idText(tagName.name));
      } else {
        return createExpressionFromEntityName(factory2, tagName);
      }
    }
  }
  function getAttributeName(node) {
    const name = node.name;
    if (isIdentifier(name)) {
      const text = idText(name);
      return /^[A-Za-z_]\w*$/.test(text) ? name : factory2.createStringLiteral(text);
    }
    return factory2.createStringLiteral(idText(name.namespace) + ":" + idText(name.name));
  }
  function visitJsxExpression(node) {
    const expression = visitNode(node.expression, visitor, isExpression);
    return node.dotDotDotToken ? factory2.createSpreadElement(expression) : expression;
  }
}
var entities = new Map(Object.entries({
  quot: 34,
  amp: 38,
  apos: 39,
  lt: 60,
  gt: 62,
  nbsp: 160,
  iexcl: 161,
  cent: 162,
  pound: 163,
  curren: 164,
  yen: 165,
  brvbar: 166,
  sect: 167,
  uml: 168,
  copy: 169,
  ordf: 170,
  laquo: 171,
  not: 172,
  shy: 173,
  reg: 174,
  macr: 175,
  deg: 176,
  plusmn: 177,
  sup2: 178,
  sup3: 179,
  acute: 180,
  micro: 181,
  para: 182,
  middot: 183,
  cedil: 184,
  sup1: 185,
  ordm: 186,
  raquo: 187,
  frac14: 188,
  frac12: 189,
  frac34: 190,
  iquest: 191,
  Agrave: 192,
  Aacute: 193,
  Acirc: 194,
  Atilde: 195,
  Auml: 196,
  Aring: 197,
  AElig: 198,
  Ccedil: 199,
  Egrave: 200,
  Eacute: 201,
  Ecirc: 202,
  Euml: 203,
  Igrave: 204,
  Iacute: 205,
  Icirc: 206,
  Iuml: 207,
  ETH: 208,
  Ntilde: 209,
  Ograve: 210,
  Oacute: 211,
  Ocirc: 212,
  Otilde: 213,
  Ouml: 214,
  times: 215,
  Oslash: 216,
  Ugrave: 217,
  Uacute: 218,
  Ucirc: 219,
  Uuml: 220,
  Yacute: 221,
  THORN: 222,
  szlig: 223,
  agrave: 224,
  aacute: 225,
  acirc: 226,
  atilde: 227,
  auml: 228,
  aring: 229,
  aelig: 230,
  ccedil: 231,
  egrave: 232,
  eacute: 233,
  ecirc: 234,
  euml: 235,
  igrave: 236,
  iacute: 237,
  icirc: 238,
  iuml: 239,
  eth: 240,
  ntilde: 241,
  ograve: 242,
  oacute: 243,
  ocirc: 244,
  otilde: 245,
  ouml: 246,
  divide: 247,
  oslash: 248,
  ugrave: 249,
  uacute: 250,
  ucirc: 251,
  uuml: 252,
  yacute: 253,
  thorn: 254,
  yuml: 255,
  OElig: 338,
  oelig: 339,
  Scaron: 352,
  scaron: 353,
  Yuml: 376,
  fnof: 402,
  circ: 710,
  tilde: 732,
  Alpha: 913,
  Beta: 914,
  Gamma: 915,
  Delta: 916,
  Epsilon: 917,
  Zeta: 918,
  Eta: 919,
  Theta: 920,
  Iota: 921,
  Kappa: 922,
  Lambda: 923,
  Mu: 924,
  Nu: 925,
  Xi: 926,
  Omicron: 927,
  Pi: 928,
  Rho: 929,
  Sigma: 931,
  Tau: 932,
  Upsilon: 933,
  Phi: 934,
  Chi: 935,
  Psi: 936,
  Omega: 937,
  alpha: 945,
  beta: 946,
  gamma: 947,
  delta: 948,
  epsilon: 949,
  zeta: 950,
  eta: 951,
  theta: 952,
  iota: 953,
  kappa: 954,
  lambda: 955,
  mu: 956,
  nu: 957,
  xi: 958,
  omicron: 959,
  pi: 960,
  rho: 961,
  sigmaf: 962,
  sigma: 963,
  tau: 964,
  upsilon: 965,
  phi: 966,
  chi: 967,
  psi: 968,
  omega: 969,
  thetasym: 977,
  upsih: 978,
  piv: 982,
  ensp: 8194,
  emsp: 8195,
  thinsp: 8201,
  zwnj: 8204,
  zwj: 8205,
  lrm: 8206,
  rlm: 8207,
  ndash: 8211,
  mdash: 8212,
  lsquo: 8216,
  rsquo: 8217,
  sbquo: 8218,
  ldquo: 8220,
  rdquo: 8221,
  bdquo: 8222,
  dagger: 8224,
  Dagger: 8225,
  bull: 8226,
  hellip: 8230,
  permil: 8240,
  prime: 8242,
  Prime: 8243,
  lsaquo: 8249,
  rsaquo: 8250,
  oline: 8254,
  frasl: 8260,
  euro: 8364,
  image: 8465,
  weierp: 8472,
  real: 8476,
  trade: 8482,
  alefsym: 8501,
  larr: 8592,
  uarr: 8593,
  rarr: 8594,
  darr: 8595,
  harr: 8596,
  crarr: 8629,
  lArr: 8656,
  uArr: 8657,
  rArr: 8658,
  dArr: 8659,
  hArr: 8660,
  forall: 8704,
  part: 8706,
  exist: 8707,
  empty: 8709,
  nabla: 8711,
  isin: 8712,
  notin: 8713,
  ni: 8715,
  prod: 8719,
  sum: 8721,
  minus: 8722,
  lowast: 8727,
  radic: 8730,
  prop: 8733,
  infin: 8734,
  ang: 8736,
  and: 8743,
  or: 8744,
  cap: 8745,
  cup: 8746,
  int: 8747,
  there4: 8756,
  sim: 8764,
  cong: 8773,
  asymp: 8776,
  ne: 8800,
  equiv: 8801,
  le: 8804,
  ge: 8805,
  sub: 8834,
  sup: 8835,
  nsub: 8836,
  sube: 8838,
  supe: 8839,
  oplus: 8853,
  otimes: 8855,
  perp: 8869,
  sdot: 8901,
  lceil: 8968,
  rceil: 8969,
  lfloor: 8970,
  rfloor: 8971,
  lang: 9001,
  rang: 9002,
  loz: 9674,
  spades: 9824,
  clubs: 9827,
  hearts: 9829,
  diams: 9830
}));

// src/compiler/transformers/es2016.ts
function transformES2016(context) {
  const {
    factory: factory2,
    hoistVariableDeclaration
  } = context;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 512 /* ContainsES2016 */) === 0) {
      return node;
    }
    switch (node.kind) {
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitBinaryExpression(node) {
    switch (node.operatorToken.kind) {
      case 68 /* AsteriskAsteriskEqualsToken */:
        return visitExponentiationAssignmentExpression(node);
      case 43 /* AsteriskAsteriskToken */:
        return visitExponentiationExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitExponentiationAssignmentExpression(node) {
    let target;
    let value;
    const left = visitNode(node.left, visitor, isExpression);
    const right = visitNode(node.right, visitor, isExpression);
    if (isElementAccessExpression(left)) {
      const expressionTemp = factory2.createTempVariable(hoistVariableDeclaration);
      const argumentExpressionTemp = factory2.createTempVariable(hoistVariableDeclaration);
      target = setTextRange(
        factory2.createElementAccessExpression(
          setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression),
          setTextRange(factory2.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)
        ),
        left
      );
      value = setTextRange(
        factory2.createElementAccessExpression(
          expressionTemp,
          argumentExpressionTemp
        ),
        left
      );
    } else if (isPropertyAccessExpression(left)) {
      const expressionTemp = factory2.createTempVariable(hoistVariableDeclaration);
      target = setTextRange(
        factory2.createPropertyAccessExpression(
          setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression),
          left.name
        ),
        left
      );
      value = setTextRange(
        factory2.createPropertyAccessExpression(
          expressionTemp,
          left.name
        ),
        left
      );
    } else {
      target = left;
      value = left;
    }
    return setTextRange(
      factory2.createAssignment(
        target,
        setTextRange(factory2.createGlobalMethodCall("Math", "pow", [value, right]), node)
      ),
      node
    );
  }
  function visitExponentiationExpression(node) {
    const left = visitNode(node.left, visitor, isExpression);
    const right = visitNode(node.right, visitor, isExpression);
    return setTextRange(factory2.createGlobalMethodCall("Math", "pow", [left, right]), node);
  }
}

// src/compiler/transformers/es2015.ts
function createSpreadSegment(kind, expression) {
  return { kind, expression };
}
function transformES2015(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    startLexicalEnvironment,
    resumeLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const compilerOptions = context.getCompilerOptions();
  const resolver = context.getEmitResolver();
  const previousOnSubstituteNode = context.onSubstituteNode;
  const previousOnEmitNode = context.onEmitNode;
  context.onEmitNode = onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  let currentSourceFile;
  let currentText;
  let hierarchyFacts;
  let taggedTemplateStringDeclarations;
  function recordTaggedTemplateString(temp) {
    taggedTemplateStringDeclarations = append(
      taggedTemplateStringDeclarations,
      factory2.createVariableDeclaration(temp)
    );
  }
  let convertedLoopState;
  let enabledSubstitutions;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    currentSourceFile = node;
    currentText = node.text;
    const visited = visitSourceFile(node);
    addEmitHelpers(visited, context.readEmitHelpers());
    currentSourceFile = void 0;
    currentText = void 0;
    taggedTemplateStringDeclarations = void 0;
    hierarchyFacts = 0 /* None */;
    return visited;
  }
  function enterSubtree(excludeFacts, includeFacts) {
    const ancestorFacts = hierarchyFacts;
    hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 32767 /* AncestorFactsMask */;
    return ancestorFacts;
  }
  function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
    hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -32768 /* SubtreeFactsMask */ | ancestorFacts;
  }
  function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
    return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 && node.kind === 252 /* ReturnStatement */ && !node.expression;
  }
  function isOrMayContainReturnCompletion(node) {
    return node.transformFlags & 4194304 /* ContainsHoistedDeclarationOrCompletion */ && (isReturnStatement(node) || isIfStatement(node) || isWithStatement(node) || isSwitchStatement(node) || isCaseBlock(node) || isCaseClause(node) || isDefaultClause(node) || isTryStatement(node) || isCatchClause(node) || isLabeledStatement(node) || isIterationStatement(
      node,
      /*lookInLabeledStatements*/
      false
    ) || isBlock(node));
  }
  function shouldVisitNode(node) {
    return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== void 0 || hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node) || isIterationStatement(
      node,
      /*lookInLabeledStatements*/
      false
    ) && shouldConvertIterationStatement(node) || (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */) !== 0;
  }
  function visitor(node) {
    return shouldVisitNode(node) ? visitorWorker(
      node,
      /*expressionResultIsUnused*/
      false
    ) : node;
  }
  function visitorWithUnusedExpressionResult(node) {
    return shouldVisitNode(node) ? visitorWorker(
      node,
      /*expressionResultIsUnused*/
      true
    ) : node;
  }
  function classWrapperStatementVisitor(node) {
    if (shouldVisitNode(node)) {
      const original = getOriginalNode(node);
      if (isPropertyDeclaration(original) && hasStaticModifier(original)) {
        const ancestorFacts = enterSubtree(
          32670 /* StaticInitializerExcludes */,
          16449 /* StaticInitializerIncludes */
        );
        const result = visitorWorker(
          node,
          /*expressionResultIsUnused*/
          false
        );
        exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
        return result;
      }
      return visitorWorker(
        node,
        /*expressionResultIsUnused*/
        false
      );
    }
    return node;
  }
  function callExpressionVisitor(node) {
    if (node.kind === 108 /* SuperKeyword */) {
      return visitSuperKeyword(
        /*isExpressionOfCall*/
        true
      );
    }
    return visitor(node);
  }
  function visitorWorker(node, expressionResultIsUnused2) {
    switch (node.kind) {
      case 126 /* StaticKeyword */:
        return void 0;
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 230 /* ClassExpression */:
        return visitClassExpression(node);
      case 168 /* Parameter */:
        return visitParameter(node);
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 218 /* ArrowFunction */:
        return visitArrowFunction(node);
      case 217 /* FunctionExpression */:
        return visitFunctionExpression(node);
      case 259 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 80 /* Identifier */:
        return visitIdentifier(node);
      case 260 /* VariableDeclarationList */:
        return visitVariableDeclarationList(node);
      case 254 /* SwitchStatement */:
        return visitSwitchStatement(node);
      case 268 /* CaseBlock */:
        return visitCaseBlock(node);
      case 240 /* Block */:
        return visitBlock(
          node,
          /*isFunctionBody*/
          false
        );
      case 251 /* BreakStatement */:
      case 250 /* ContinueStatement */:
        return visitBreakOrContinueStatement(node);
      case 255 /* LabeledStatement */:
        return visitLabeledStatement(node);
      case 245 /* DoStatement */:
      case 246 /* WhileStatement */:
        return visitDoOrWhileStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 247 /* ForStatement */:
        return visitForStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 248 /* ForInStatement */:
        return visitForInStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 249 /* ForOfStatement */:
        return visitForOfStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 243 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 209 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 298 /* CatchClause */:
        return visitCatchClause(node);
      case 303 /* ShorthandPropertyAssignment */:
        return visitShorthandPropertyAssignment(node);
      case 166 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      case 208 /* ArrayLiteralExpression */:
        return visitArrayLiteralExpression(node);
      case 212 /* CallExpression */:
        return visitCallExpression(node);
      case 213 /* NewExpression */:
        return visitNewExpression(node);
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node, expressionResultIsUnused2);
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(node, expressionResultIsUnused2);
      case 360 /* CommaListExpression */:
        return visitCommaListExpression(node, expressionResultIsUnused2);
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 16 /* TemplateHead */:
      case 17 /* TemplateMiddle */:
      case 18 /* TemplateTail */:
        return visitTemplateLiteral(node);
      case 11 /* StringLiteral */:
        return visitStringLiteral(node);
      case 9 /* NumericLiteral */:
        return visitNumericLiteral(node);
      case 214 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 227 /* TemplateExpression */:
        return visitTemplateExpression(node);
      case 228 /* YieldExpression */:
        return visitYieldExpression(node);
      case 229 /* SpreadElement */:
        return visitSpreadElement(node);
      case 108 /* SuperKeyword */:
        return visitSuperKeyword(
          /*isExpressionOfCall*/
          false
        );
      case 110 /* ThisKeyword */:
        return visitThisKeyword(node);
      case 235 /* MetaProperty */:
        return visitMetaProperty(node);
      case 173 /* MethodDeclaration */:
        return visitMethodDeclaration(node);
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        return visitAccessorDeclaration(node);
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 252 /* ReturnStatement */:
        return visitReturnStatement(node);
      case 221 /* VoidExpression */:
        return visitVoidExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitSourceFile(node) {
    const ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
    const prologue = [];
    const statements = [];
    startLexicalEnvironment();
    const statementOffset = factory2.copyPrologue(
      node.statements,
      prologue,
      /*ensureUseStrict*/
      false,
      visitor
    );
    addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset));
    if (taggedTemplateStringDeclarations) {
      statements.push(
        factory2.createVariableStatement(
          /*modifiers*/
          void 0,
          factory2.createVariableDeclarationList(taggedTemplateStringDeclarations)
        )
      );
    }
    factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
    insertCaptureThisForNodeIfNeeded(prologue, node);
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return factory2.updateSourceFile(
      node,
      setTextRange(factory2.createNodeArray(concatenate(prologue, statements)), node.statements)
    );
  }
  function visitSwitchStatement(node) {
    if (convertedLoopState !== void 0) {
      const savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
      convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
      const result = visitEachChild(node, visitor, context);
      convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
      return result;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCaseBlock(node) {
    const ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
    const updated = visitEachChild(node, visitor, context);
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return updated;
  }
  function returnCapturedThis(node) {
    return setOriginalNode(factory2.createReturnStatement(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node);
  }
  function visitReturnStatement(node) {
    if (convertedLoopState) {
      convertedLoopState.nonLocalJumps |= 8 /* Return */;
      if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
        node = returnCapturedThis(node);
      }
      return factory2.createReturnStatement(
        factory2.createObjectLiteralExpression(
          [
            factory2.createPropertyAssignment(
              factory2.createIdentifier("value"),
              node.expression ? Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) : factory2.createVoidZero()
            )
          ]
        )
      );
    } else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
      return returnCapturedThis(node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitThisKeyword(node) {
    if (hierarchyFacts & 2 /* ArrowFunction */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) {
      hierarchyFacts |= 65536 /* CapturedLexicalThis */;
    }
    if (convertedLoopState) {
      if (hierarchyFacts & 2 /* ArrowFunction */) {
        convertedLoopState.containsLexicalThis = true;
        return node;
      }
      return convertedLoopState.thisName || (convertedLoopState.thisName = factory2.createUniqueName("this"));
    }
    return node;
  }
  function visitVoidExpression(node) {
    return visitEachChild(node, visitorWithUnusedExpressionResult, context);
  }
  function visitIdentifier(node) {
    if (convertedLoopState) {
      if (resolver.isArgumentsLocalBinding(node)) {
        return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory2.createUniqueName("arguments"));
      }
    }
    if (node.flags & 128 /* IdentifierHasExtendedUnicodeEscape */) {
      return setOriginalNode(setTextRange(
        factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)),
        node
      ), node);
    }
    return node;
  }
  function visitBreakOrContinueStatement(node) {
    if (convertedLoopState) {
      const jump = node.kind === 251 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
      const canUseBreakOrContinue = node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label)) || !node.label && convertedLoopState.allowedNonLabeledJumps & jump;
      if (!canUseBreakOrContinue) {
        let labelMarker;
        const label = node.label;
        if (!label) {
          if (node.kind === 251 /* BreakStatement */) {
            convertedLoopState.nonLocalJumps |= 2 /* Break */;
            labelMarker = "break";
          } else {
            convertedLoopState.nonLocalJumps |= 4 /* Continue */;
            labelMarker = "continue";
          }
        } else {
          if (node.kind === 251 /* BreakStatement */) {
            labelMarker = `break-${label.escapedText}`;
            setLabeledJump(
              convertedLoopState,
              /*isBreak*/
              true,
              idText(label),
              labelMarker
            );
          } else {
            labelMarker = `continue-${label.escapedText}`;
            setLabeledJump(
              convertedLoopState,
              /*isBreak*/
              false,
              idText(label),
              labelMarker
            );
          }
        }
        let returnExpression = factory2.createStringLiteral(labelMarker);
        if (convertedLoopState.loopOutParameters.length) {
          const outParams = convertedLoopState.loopOutParameters;
          let expr;
          for (let i = 0; i < outParams.length; i++) {
            const copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
            if (i === 0) {
              expr = copyExpr;
            } else {
              expr = factory2.createBinaryExpression(expr, 28 /* CommaToken */, copyExpr);
            }
          }
          returnExpression = factory2.createBinaryExpression(expr, 28 /* CommaToken */, returnExpression);
        }
        return factory2.createReturnStatement(returnExpression);
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitClassDeclaration(node) {
    const variable = factory2.createVariableDeclaration(
      factory2.getLocalName(
        node,
        /*allowComments*/
        true
      ),
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      transformClassLikeDeclarationToExpression(node)
    );
    setOriginalNode(variable, node);
    const statements = [];
    const statement = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      factory2.createVariableDeclarationList([variable])
    );
    setOriginalNode(statement, node);
    setTextRange(statement, node);
    startOnNewLine(statement);
    statements.push(statement);
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      const exportStatement = hasSyntacticModifier(node, 1024 /* Default */) ? factory2.createExportDefault(factory2.getLocalName(node)) : factory2.createExternalModuleExport(factory2.getLocalName(node));
      setOriginalNode(exportStatement, statement);
      statements.push(exportStatement);
    }
    return singleOrMany(statements);
  }
  function visitClassExpression(node) {
    return transformClassLikeDeclarationToExpression(node);
  }
  function transformClassLikeDeclarationToExpression(node) {
    if (node.name) {
      enableSubstitutionsForBlockScopedBindings();
    }
    const extendsClauseElement = getClassExtendsHeritageElement(node);
    const classFunction = factory2.createFunctionExpression(
      /*modifiers*/
      void 0,
      /*asteriskToken*/
      void 0,
      /*name*/
      void 0,
      /*typeParameters*/
      void 0,
      extendsClauseElement ? [factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)
      )] : [],
      /*type*/
      void 0,
      transformClassBody(node, extendsClauseElement)
    );
    setEmitFlags(classFunction, getEmitFlags(node) & 131072 /* Indented */ | 1048576 /* ReuseTempVariableScope */);
    const inner = factory2.createPartiallyEmittedExpression(classFunction);
    setTextRangeEnd(inner, node.end);
    setEmitFlags(inner, 3072 /* NoComments */);
    const outer = factory2.createPartiallyEmittedExpression(inner);
    setTextRangeEnd(outer, skipTrivia(currentText, node.pos));
    setEmitFlags(outer, 3072 /* NoComments */);
    const result = factory2.createParenthesizedExpression(
      factory2.createCallExpression(
        outer,
        /*typeArguments*/
        void 0,
        extendsClauseElement ? [Debug.checkDefined(visitNode(extendsClauseElement.expression, visitor, isExpression))] : []
      )
    );
    addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
    return result;
  }
  function transformClassBody(node, extendsClauseElement) {
    const statements = [];
    const name = factory2.getInternalName(node);
    const constructorLikeName = isIdentifierANonContextualKeyword(name) ? factory2.getGeneratedNameForNode(name) : name;
    startLexicalEnvironment();
    addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
    addConstructor(statements, node, constructorLikeName, extendsClauseElement);
    addClassMembers(statements, node);
    const closingBraceLocation = createTokenRange(skipTrivia(currentText, node.members.end), 20 /* CloseBraceToken */);
    const outer = factory2.createPartiallyEmittedExpression(constructorLikeName);
    setTextRangeEnd(outer, closingBraceLocation.end);
    setEmitFlags(outer, 3072 /* NoComments */);
    const statement = factory2.createReturnStatement(outer);
    setTextRangePos(statement, closingBraceLocation.pos);
    setEmitFlags(statement, 3072 /* NoComments */ | 768 /* NoTokenSourceMaps */);
    statements.push(statement);
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    const block = factory2.createBlock(
      setTextRange(
        factory2.createNodeArray(statements),
        /*location*/
        node.members
      ),
      /*multiLine*/
      true
    );
    setEmitFlags(block, 3072 /* NoComments */);
    return block;
  }
  function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
    if (extendsClauseElement) {
      statements.push(
        setTextRange(
          factory2.createExpressionStatement(
            emitHelpers().createExtendsHelper(factory2.getInternalName(node))
          ),
          /*location*/
          extendsClauseElement
        )
      );
    }
  }
  function addConstructor(statements, node, name, extendsClauseElement) {
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const ancestorFacts = enterSubtree(32662 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
    const constructor = getFirstConstructorWithBody(node);
    const hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== void 0);
    const constructorFunction = factory2.createFunctionDeclaration(
      /*modifiers*/
      void 0,
      /*asteriskToken*/
      void 0,
      name,
      /*typeParameters*/
      void 0,
      transformConstructorParameters(constructor, hasSynthesizedSuper),
      /*type*/
      void 0,
      transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)
    );
    setTextRange(constructorFunction, constructor || node);
    if (extendsClauseElement) {
      setEmitFlags(constructorFunction, 16 /* CapturesThis */);
    }
    statements.push(constructorFunction);
    exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
    convertedLoopState = savedConvertedLoopState;
  }
  function transformConstructorParameters(constructor, hasSynthesizedSuper) {
    return visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : void 0, visitor, context) || [];
  }
  function createDefaultConstructorBody(node, isDerivedClass) {
    const statements = [];
    resumeLexicalEnvironment();
    factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment());
    if (isDerivedClass) {
      statements.push(factory2.createReturnStatement(createDefaultSuperCallOrThis()));
    }
    const statementsArray = factory2.createNodeArray(statements);
    setTextRange(statementsArray, node.members);
    const block = factory2.createBlock(
      statementsArray,
      /*multiLine*/
      true
    );
    setTextRange(block, node);
    setEmitFlags(block, 3072 /* NoComments */);
    return block;
  }
  function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
    const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */;
    if (!constructor)
      return createDefaultConstructorBody(node, isDerivedClass);
    const prologue = [];
    const statements = [];
    resumeLexicalEnvironment();
    const existingPrologue = takeWhile(constructor.body.statements, isPrologueDirective);
    const { superCall, superStatementIndex } = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue);
    const postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1;
    let statementOffset = postSuperStatementsStart;
    if (!hasSynthesizedSuper)
      statementOffset = factory2.copyStandardPrologue(
        constructor.body.statements,
        prologue,
        statementOffset,
        /*ensureUseStrict*/
        false
      );
    if (!hasSynthesizedSuper)
      statementOffset = factory2.copyCustomPrologue(
        constructor.body.statements,
        statements,
        statementOffset,
        visitor,
        /*filter*/
        void 0
      );
    let superCallExpression;
    if (hasSynthesizedSuper) {
      superCallExpression = createDefaultSuperCallOrThis();
    } else if (superCall) {
      superCallExpression = visitSuperCallInBody(superCall);
    }
    if (superCallExpression) {
      hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
    }
    addDefaultValueAssignmentsIfNeeded2(prologue, constructor);
    addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper);
    addRange(statements, visitNodes2(
      constructor.body.statements,
      visitor,
      isStatement,
      /*start*/
      statementOffset
    ));
    factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
    insertCaptureNewTargetIfNeeded(
      prologue,
      constructor,
      /*copyOnWrite*/
      false
    );
    if (isDerivedClass || superCallExpression) {
      if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 16384 /* ContainsLexicalThis */)) {
        const superCall2 = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression);
        const returnStatement = factory2.createReturnStatement(superCallExpression);
        setCommentRange(returnStatement, getCommentRange(superCall2));
        setEmitFlags(superCall2, 3072 /* NoComments */);
        statements.push(returnStatement);
      } else {
        if (superStatementIndex <= existingPrologue.length) {
          insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
        } else {
          insertCaptureThisForNode(prologue, constructor, createActualThis());
          if (superCallExpression) {
            insertSuperThisCaptureThisForNode(statements, superCallExpression);
          }
        }
        if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
          statements.push(factory2.createReturnStatement(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)));
        }
      }
    } else {
      insertCaptureThisForNodeIfNeeded(prologue, constructor);
    }
    const body = factory2.createBlock(
      setTextRange(
        factory2.createNodeArray(
          [
            ...existingPrologue,
            ...prologue,
            ...superStatementIndex <= existingPrologue.length ? emptyArray : visitNodes2(constructor.body.statements, visitor, isStatement, existingPrologue.length, superStatementIndex - existingPrologue.length),
            ...statements
          ]
        ),
        /*location*/
        constructor.body.statements
      ),
      /*multiLine*/
      true
    );
    setTextRange(body, constructor.body);
    return body;
  }
  function findSuperCallAndStatementIndex(originalBodyStatements, existingPrologue) {
    for (let i = existingPrologue.length; i < originalBodyStatements.length; i += 1) {
      const superCall = getSuperCallFromStatement(originalBodyStatements[i]);
      if (superCall) {
        return {
          superCall,
          superStatementIndex: i
        };
      }
    }
    return {
      superStatementIndex: -1
    };
  }
  function isSufficientlyCoveredByReturnStatements(statement) {
    if (statement.kind === 252 /* ReturnStatement */) {
      return true;
    } else if (statement.kind === 244 /* IfStatement */) {
      const ifStatement = statement;
      if (ifStatement.elseStatement) {
        return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
      }
    } else if (statement.kind === 240 /* Block */) {
      const lastStatement = lastOrUndefined(statement.statements);
      if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
        return true;
      }
    }
    return false;
  }
  function createActualThis() {
    return setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */);
  }
  function createDefaultSuperCallOrThis() {
    return factory2.createLogicalOr(
      factory2.createLogicalAnd(
        factory2.createStrictInequality(
          factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */),
          factory2.createNull()
        ),
        factory2.createFunctionApplyCall(
          factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */),
          createActualThis(),
          factory2.createIdentifier("arguments")
        )
      ),
      createActualThis()
    );
  }
  function visitParameter(node) {
    if (node.dotDotDotToken) {
      return void 0;
    } else if (isBindingPattern(node.name)) {
      return setOriginalNode(
        setTextRange(
          factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            factory2.getGeneratedNameForNode(node),
            /*questionToken*/
            void 0,
            /*type*/
            void 0,
            /*initializer*/
            void 0
          ),
          /*location*/
          node
        ),
        /*original*/
        node
      );
    } else if (node.initializer) {
      return setOriginalNode(
        setTextRange(
          factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            node.name,
            /*questionToken*/
            void 0,
            /*type*/
            void 0,
            /*initializer*/
            void 0
          ),
          /*location*/
          node
        ),
        /*original*/
        node
      );
    } else {
      return node;
    }
  }
  function hasDefaultValueOrBindingPattern(node) {
    return node.initializer !== void 0 || isBindingPattern(node.name);
  }
  function addDefaultValueAssignmentsIfNeeded2(statements, node) {
    if (!some(node.parameters, hasDefaultValueOrBindingPattern)) {
      return false;
    }
    let added = false;
    for (const parameter of node.parameters) {
      const { name, initializer, dotDotDotToken } = parameter;
      if (dotDotDotToken) {
        continue;
      }
      if (isBindingPattern(name)) {
        added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
      } else if (initializer) {
        insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
        added = true;
      }
    }
    return added;
  }
  function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
    if (name.elements.length > 0) {
      insertStatementAfterCustomPrologue(
        statements,
        setEmitFlags(
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList(
              flattenDestructuringBinding(
                parameter,
                visitor,
                context,
                0 /* All */,
                factory2.getGeneratedNameForNode(parameter)
              )
            )
          ),
          2097152 /* CustomPrologue */
        )
      );
      return true;
    } else if (initializer) {
      insertStatementAfterCustomPrologue(
        statements,
        setEmitFlags(
          factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.getGeneratedNameForNode(parameter),
              Debug.checkDefined(visitNode(initializer, visitor, isExpression))
            )
          ),
          2097152 /* CustomPrologue */
        )
      );
      return true;
    }
    return false;
  }
  function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
    initializer = Debug.checkDefined(visitNode(initializer, visitor, isExpression));
    const statement = factory2.createIfStatement(
      factory2.createTypeCheck(factory2.cloneNode(name), "undefined"),
      setEmitFlags(
        setTextRange(
          factory2.createBlock([
            factory2.createExpressionStatement(
              setEmitFlags(
                setTextRange(
                  factory2.createAssignment(
                    // TODO(rbuckton): Does this need to be parented?
                    setEmitFlags(setParent(setTextRange(factory2.cloneNode(name), name), name.parent), 96 /* NoSourceMap */),
                    setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */)
                  ),
                  parameter
                ),
                3072 /* NoComments */
              )
            )
          ]),
          parameter
        ),
        1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */
      )
    );
    startOnNewLine(statement);
    setTextRange(statement, parameter);
    setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2097152 /* CustomPrologue */ | 3072 /* NoComments */);
    insertStatementAfterCustomPrologue(statements, statement);
  }
  function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
    return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
  }
  function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
    const prologueStatements = [];
    const parameter = lastOrUndefined(node.parameters);
    if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
      return false;
    }
    const declarationName = parameter.name.kind === 80 /* Identifier */ ? setParent(setTextRange(factory2.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    setEmitFlags(declarationName, 96 /* NoSourceMap */);
    const expressionName = parameter.name.kind === 80 /* Identifier */ ? factory2.cloneNode(parameter.name) : declarationName;
    const restIndex = node.parameters.length - 1;
    const temp = factory2.createLoopVariable();
    prologueStatements.push(
      setEmitFlags(
        setTextRange(
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList([
              factory2.createVariableDeclaration(
                declarationName,
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                factory2.createArrayLiteralExpression([])
              )
            ])
          ),
          /*location*/
          parameter
        ),
        2097152 /* CustomPrologue */
      )
    );
    const forStatement = factory2.createForStatement(
      setTextRange(
        factory2.createVariableDeclarationList([
          factory2.createVariableDeclaration(
            temp,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            factory2.createNumericLiteral(restIndex)
          )
        ]),
        parameter
      ),
      setTextRange(
        factory2.createLessThan(
          temp,
          factory2.createPropertyAccessExpression(factory2.createIdentifier("arguments"), "length")
        ),
        parameter
      ),
      setTextRange(factory2.createPostfixIncrement(temp), parameter),
      factory2.createBlock([
        startOnNewLine(
          setTextRange(
            factory2.createExpressionStatement(
              factory2.createAssignment(
                factory2.createElementAccessExpression(
                  expressionName,
                  restIndex === 0 ? temp : factory2.createSubtract(temp, factory2.createNumericLiteral(restIndex))
                ),
                factory2.createElementAccessExpression(factory2.createIdentifier("arguments"), temp)
              )
            ),
            /*location*/
            parameter
          )
        )
      ])
    );
    setEmitFlags(forStatement, 2097152 /* CustomPrologue */);
    startOnNewLine(forStatement);
    prologueStatements.push(forStatement);
    if (parameter.name.kind !== 80 /* Identifier */) {
      prologueStatements.push(
        setEmitFlags(
          setTextRange(
            factory2.createVariableStatement(
              /*modifiers*/
              void 0,
              factory2.createVariableDeclarationList(
                flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName)
              )
            ),
            parameter
          ),
          2097152 /* CustomPrologue */
        )
      );
    }
    insertStatementsAfterCustomPrologue(statements, prologueStatements);
    return true;
  }
  function insertCaptureThisForNodeIfNeeded(statements, node) {
    if (hierarchyFacts & 65536 /* CapturedLexicalThis */ && node.kind !== 218 /* ArrowFunction */) {
      insertCaptureThisForNode(statements, node, factory2.createThis());
      return true;
    }
    return false;
  }
  function insertSuperThisCaptureThisForNode(statements, superExpression) {
    enableSubstitutionsForCapturedThis();
    const assignSuperExpression = factory2.createExpressionStatement(
      factory2.createBinaryExpression(
        factory2.createThis(),
        64 /* EqualsToken */,
        superExpression
      )
    );
    insertStatementAfterCustomPrologue(statements, assignSuperExpression);
    setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent);
  }
  function insertCaptureThisForNode(statements, node, initializer) {
    enableSubstitutionsForCapturedThis();
    const captureThisStatement = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      factory2.createVariableDeclarationList([
        factory2.createVariableDeclaration(
          factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */),
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          initializer
        )
      ])
    );
    setEmitFlags(captureThisStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */);
    setSourceMapRange(captureThisStatement, node);
    insertStatementAfterCustomPrologue(statements, captureThisStatement);
  }
  function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
    if (hierarchyFacts & 32768 /* NewTarget */) {
      let newTarget;
      switch (node.kind) {
        case 218 /* ArrowFunction */:
          return statements;
        case 173 /* MethodDeclaration */:
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
          newTarget = factory2.createVoidZero();
          break;
        case 175 /* Constructor */:
          newTarget = factory2.createPropertyAccessExpression(
            setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */),
            "constructor"
          );
          break;
        case 261 /* FunctionDeclaration */:
        case 217 /* FunctionExpression */:
          newTarget = factory2.createConditionalExpression(
            factory2.createLogicalAnd(
              setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */),
              factory2.createBinaryExpression(
                setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */),
                104 /* InstanceOfKeyword */,
                factory2.getLocalName(node)
              )
            ),
            /*questionToken*/
            void 0,
            factory2.createPropertyAccessExpression(
              setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */),
              "constructor"
            ),
            /*colonToken*/
            void 0,
            factory2.createVoidZero()
          );
          break;
        default:
          return Debug.failBadSyntaxKind(node);
      }
      const captureNewTargetStatement = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList([
          factory2.createVariableDeclaration(
            factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */),
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            newTarget
          )
        ])
      );
      setEmitFlags(captureNewTargetStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */);
      if (copyOnWrite) {
        statements = statements.slice();
      }
      insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
    }
    return statements;
  }
  function addClassMembers(statements, node) {
    for (const member of node.members) {
      switch (member.kind) {
        case 239 /* SemicolonClassElement */:
          statements.push(transformSemicolonClassElementToStatement(member));
          break;
        case 173 /* MethodDeclaration */:
          statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
          break;
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
          const accessors = getAllAccessorDeclarations(node.members, member);
          if (member === accessors.firstAccessor) {
            statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
          }
          break;
        case 175 /* Constructor */:
        case 174 /* ClassStaticBlockDeclaration */:
          break;
        default:
          Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
          break;
      }
    }
  }
  function transformSemicolonClassElementToStatement(member) {
    return setTextRange(factory2.createEmptyStatement(), member);
  }
  function transformClassMethodDeclarationToStatement(receiver, member, container) {
    const commentRange = getCommentRange(member);
    const sourceMapRange = getSourceMapRange(member);
    const memberFunction = transformFunctionLikeToExpression(
      member,
      /*location*/
      member,
      /*name*/
      void 0,
      container
    );
    const propertyName = visitNode(member.name, visitor, isPropertyName);
    Debug.assert(propertyName);
    let e;
    if (!isPrivateIdentifier(propertyName) && getUseDefineForClassFields(context.getCompilerOptions())) {
      const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory2.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName;
      e = factory2.createObjectDefinePropertyCall(receiver, name, factory2.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
    } else {
      const memberName = createMemberAccessForPropertyName(
        factory2,
        receiver,
        propertyName,
        /*location*/
        member.name
      );
      e = factory2.createAssignment(memberName, memberFunction);
    }
    setEmitFlags(memberFunction, 3072 /* NoComments */);
    setSourceMapRange(memberFunction, sourceMapRange);
    const statement = setTextRange(
      factory2.createExpressionStatement(e),
      /*location*/
      member
    );
    setOriginalNode(statement, member);
    setCommentRange(statement, commentRange);
    setEmitFlags(statement, 96 /* NoSourceMap */);
    return statement;
  }
  function transformAccessorsToStatement(receiver, accessors, container) {
    const statement = factory2.createExpressionStatement(transformAccessorsToExpression(
      receiver,
      accessors,
      container,
      /*startsOnNewLine*/
      false
    ));
    setEmitFlags(statement, 3072 /* NoComments */);
    setSourceMapRange(statement, getSourceMapRange(accessors.firstAccessor));
    return statement;
  }
  function transformAccessorsToExpression(receiver, { firstAccessor, getAccessor, setAccessor }, container, startsOnNewLine) {
    const target = setParent(setTextRange(factory2.cloneNode(receiver), receiver), receiver.parent);
    setEmitFlags(target, 3072 /* NoComments */ | 64 /* NoTrailingSourceMap */);
    setSourceMapRange(target, firstAccessor.name);
    const visitedAccessorName = visitNode(firstAccessor.name, visitor, isPropertyName);
    Debug.assert(visitedAccessorName);
    if (isPrivateIdentifier(visitedAccessorName)) {
      return Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
    }
    const propertyName = createExpressionForPropertyName(factory2, visitedAccessorName);
    setEmitFlags(propertyName, 3072 /* NoComments */ | 32 /* NoLeadingSourceMap */);
    setSourceMapRange(propertyName, firstAccessor.name);
    const properties = [];
    if (getAccessor) {
      const getterFunction = transformFunctionLikeToExpression(
        getAccessor,
        /*location*/
        void 0,
        /*name*/
        void 0,
        container
      );
      setSourceMapRange(getterFunction, getSourceMapRange(getAccessor));
      setEmitFlags(getterFunction, 1024 /* NoLeadingComments */);
      const getter = factory2.createPropertyAssignment("get", getterFunction);
      setCommentRange(getter, getCommentRange(getAccessor));
      properties.push(getter);
    }
    if (setAccessor) {
      const setterFunction = transformFunctionLikeToExpression(
        setAccessor,
        /*location*/
        void 0,
        /*name*/
        void 0,
        container
      );
      setSourceMapRange(setterFunction, getSourceMapRange(setAccessor));
      setEmitFlags(setterFunction, 1024 /* NoLeadingComments */);
      const setter = factory2.createPropertyAssignment("set", setterFunction);
      setCommentRange(setter, getCommentRange(setAccessor));
      properties.push(setter);
    }
    properties.push(
      factory2.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory2.createFalse() : factory2.createTrue()),
      factory2.createPropertyAssignment("configurable", factory2.createTrue())
    );
    const call = factory2.createCallExpression(
      factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"),
      /*typeArguments*/
      void 0,
      [
        target,
        propertyName,
        factory2.createObjectLiteralExpression(
          properties,
          /*multiLine*/
          true
        )
      ]
    );
    if (startsOnNewLine) {
      startOnNewLine(call);
    }
    return call;
  }
  function visitArrowFunction(node) {
    if (node.transformFlags & 16384 /* ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) {
      hierarchyFacts |= 65536 /* CapturedLexicalThis */;
    }
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
    const func = factory2.createFunctionExpression(
      /*modifiers*/
      void 0,
      /*asteriskToken*/
      void 0,
      /*name*/
      void 0,
      /*typeParameters*/
      void 0,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      transformFunctionBody2(node)
    );
    setTextRange(func, node);
    setOriginalNode(func, node);
    setEmitFlags(func, 16 /* CapturesThis */);
    exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
    convertedLoopState = savedConvertedLoopState;
    return func;
  }
  function visitFunctionExpression(node) {
    const ancestorFacts = getEmitFlags(node) & 524288 /* AsyncFunctionBody */ ? enterSubtree(32662 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) : enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const parameters = visitParameterList(node.parameters, visitor, context);
    const body = transformFunctionBody2(node);
    const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name;
    exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
    convertedLoopState = savedConvertedLoopState;
    return factory2.updateFunctionExpression(
      node,
      /*modifiers*/
      void 0,
      node.asteriskToken,
      name,
      /*typeParameters*/
      void 0,
      parameters,
      /*type*/
      void 0,
      body
    );
  }
  function visitFunctionDeclaration(node) {
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
    const parameters = visitParameterList(node.parameters, visitor, context);
    const body = transformFunctionBody2(node);
    const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name;
    exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
    convertedLoopState = savedConvertedLoopState;
    return factory2.updateFunctionDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      node.asteriskToken,
      name,
      /*typeParameters*/
      void 0,
      parameters,
      /*type*/
      void 0,
      body
    );
  }
  function transformFunctionLikeToExpression(node, location, name, container) {
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const ancestorFacts = container && isClassLike(container) && !isStatic(node) ? enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) : enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
    const parameters = visitParameterList(node.parameters, visitor, context);
    const body = transformFunctionBody2(node);
    if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 261 /* FunctionDeclaration */ || node.kind === 217 /* FunctionExpression */)) {
      name = factory2.getGeneratedNameForNode(node);
    }
    exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
    convertedLoopState = savedConvertedLoopState;
    return setOriginalNode(
      setTextRange(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          node.asteriskToken,
          name,
          /*typeParameters*/
          void 0,
          parameters,
          /*type*/
          void 0,
          body
        ),
        location
      ),
      /*original*/
      node
    );
  }
  function transformFunctionBody2(node) {
    let multiLine = false;
    let singleLine = false;
    let statementsLocation;
    let closeBraceLocation;
    const prologue = [];
    const statements = [];
    const body = node.body;
    let statementOffset;
    resumeLexicalEnvironment();
    if (isBlock(body)) {
      statementOffset = factory2.copyStandardPrologue(
        body.statements,
        prologue,
        0,
        /*ensureUseStrict*/
        false
      );
      statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedFunction);
      statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedVariableStatement);
    }
    multiLine = addDefaultValueAssignmentsIfNeeded2(statements, node) || multiLine;
    multiLine = addRestParameterIfNeeded(
      statements,
      node,
      /*inConstructorWithSynthesizedSuper*/
      false
    ) || multiLine;
    if (isBlock(body)) {
      statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor);
      statementsLocation = body.statements;
      addRange(statements, visitNodes2(body.statements, visitor, isStatement, statementOffset));
      if (!multiLine && body.multiLine) {
        multiLine = true;
      }
    } else {
      Debug.assert(node.kind === 218 /* ArrowFunction */);
      statementsLocation = moveRangeEnd(body, -1);
      const equalsGreaterThanToken = node.equalsGreaterThanToken;
      if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) {
        if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
          singleLine = true;
        } else {
          multiLine = true;
        }
      }
      const expression = visitNode(body, visitor, isExpression);
      const returnStatement = factory2.createReturnStatement(expression);
      setTextRange(returnStatement, body);
      moveSyntheticComments(returnStatement, body);
      setEmitFlags(returnStatement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2048 /* NoTrailingComments */);
      statements.push(returnStatement);
      closeBraceLocation = body;
    }
    factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
    insertCaptureNewTargetIfNeeded(
      prologue,
      node,
      /*copyOnWrite*/
      false
    );
    insertCaptureThisForNodeIfNeeded(prologue, node);
    if (some(prologue)) {
      multiLine = true;
    }
    statements.unshift(...prologue);
    if (isBlock(body) && arrayIsEqualTo(statements, body.statements)) {
      return body;
    }
    const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), multiLine);
    setTextRange(block, node.body);
    if (!multiLine && singleLine) {
      setEmitFlags(block, 1 /* SingleLine */);
    }
    if (closeBraceLocation) {
      setTokenSourceMapRange(block, 20 /* CloseBraceToken */, closeBraceLocation);
    }
    setOriginalNode(block, node.body);
    return block;
  }
  function visitBlock(node, isFunctionBody2) {
    if (isFunctionBody2) {
      return visitEachChild(node, visitor, context);
    }
    const ancestorFacts = hierarchyFacts & 256 /* IterationStatement */ ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */) : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
    const updated = visitEachChild(node, visitor, context);
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return updated;
  }
  function visitExpressionStatement(node) {
    return visitEachChild(node, visitorWithUnusedExpressionResult, context);
  }
  function visitParenthesizedExpression(node, expressionResultIsUnused2) {
    return visitEachChild(node, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, context);
  }
  function visitBinaryExpression(node, expressionResultIsUnused2) {
    if (isDestructuringAssignment(node)) {
      return flattenDestructuringAssignment(
        node,
        visitor,
        context,
        0 /* All */,
        !expressionResultIsUnused2
      );
    }
    if (node.operatorToken.kind === 28 /* CommaToken */) {
      return factory2.updateBinaryExpression(
        node,
        Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)),
        node.operatorToken,
        Debug.checkDefined(visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression))
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCommaListExpression(node, expressionResultIsUnused2) {
    if (expressionResultIsUnused2) {
      return visitEachChild(node, visitorWithUnusedExpressionResult, context);
    }
    let result;
    for (let i = 0; i < node.elements.length; i++) {
      const element = node.elements[i];
      const visited = visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, isExpression);
      if (result || visited !== element) {
        result || (result = node.elements.slice(0, i));
        Debug.assert(visited);
        result.push(visited);
      }
    }
    const elements = result ? setTextRange(factory2.createNodeArray(result), node.elements) : node.elements;
    return factory2.updateCommaListExpression(node, elements);
  }
  function isVariableStatementOfTypeScriptClassWrapper(node) {
    return node.declarationList.declarations.length === 1 && !!node.declarationList.declarations[0].initializer && !!(getInternalEmitFlags(node.declarationList.declarations[0].initializer) & 1 /* TypeScriptClassWrapper */);
  }
  function visitVariableStatement(node) {
    const ancestorFacts = enterSubtree(0 /* None */, hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
    let updated;
    if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
      let assignments;
      for (const decl of node.declarationList.declarations) {
        hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
        if (decl.initializer) {
          let assignment;
          if (isBindingPattern(decl.name)) {
            assignment = flattenDestructuringAssignment(
              decl,
              visitor,
              context,
              0 /* All */
            );
          } else {
            assignment = factory2.createBinaryExpression(decl.name, 64 /* EqualsToken */, Debug.checkDefined(visitNode(decl.initializer, visitor, isExpression)));
            setTextRange(assignment, decl);
          }
          assignments = append(assignments, assignment);
        }
      }
      if (assignments) {
        updated = setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(assignments)), node);
      } else {
        updated = void 0;
      }
    } else {
      updated = visitEachChild(node, visitor, context);
    }
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return updated;
  }
  function visitVariableDeclarationList(node) {
    if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 524288 /* ContainsBindingPattern */) {
      if (node.flags & 3 /* BlockScoped */) {
        enableSubstitutionsForBlockScopedBindings();
      }
      const declarations = visitNodes2(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, isVariableDeclaration);
      const declarationList = factory2.createVariableDeclarationList(declarations);
      setOriginalNode(declarationList, node);
      setTextRange(declarationList, node);
      setCommentRange(declarationList, node);
      if (node.transformFlags & 524288 /* ContainsBindingPattern */ && (isBindingPattern(node.declarations[0].name) || isBindingPattern(last(node.declarations).name))) {
        setSourceMapRange(declarationList, getRangeUnion(declarations));
      }
      return declarationList;
    }
    return visitEachChild(node, visitor, context);
  }
  function getRangeUnion(declarations) {
    let pos = -1, end = -1;
    for (const node of declarations) {
      pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
      end = Math.max(end, node.end);
    }
    return createRange(pos, end);
  }
  function shouldEmitExplicitInitializerForLetDeclaration(node) {
    const flags = resolver.getNodeCheckFlags(node);
    const isCapturedInFunction = flags & 16384 /* CapturedBlockScopedBinding */;
    const isDeclaredInLoop = flags & 32768 /* BlockScopedBindingInLoop */;
    const emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || isCapturedInFunction && isDeclaredInLoop && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0;
    const emitExplicitInitializer = !emittedAsTopLevel && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0 && (!resolver.isDeclarationWithCollidingName(node) || isDeclaredInLoop && !isCapturedInFunction && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0);
    return emitExplicitInitializer;
  }
  function visitVariableDeclarationInLetDeclarationList(node) {
    const name = node.name;
    if (isBindingPattern(name)) {
      return visitVariableDeclaration(node);
    }
    if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
      return factory2.updateVariableDeclaration(
        node,
        node.name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        factory2.createVoidZero()
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitVariableDeclaration(node) {
    const ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
    let updated;
    if (isBindingPattern(node.name)) {
      updated = flattenDestructuringBinding(
        node,
        visitor,
        context,
        0 /* All */,
        /*rval*/
        void 0,
        (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0
      );
    } else {
      updated = visitEachChild(node, visitor, context);
    }
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return updated;
  }
  function recordLabel(node) {
    convertedLoopState.labels.set(idText(node.label), true);
  }
  function resetLabel(node) {
    convertedLoopState.labels.set(idText(node.label), false);
  }
  function visitLabeledStatement(node) {
    if (convertedLoopState && !convertedLoopState.labels) {
      convertedLoopState.labels = /* @__PURE__ */ new Map();
    }
    const statement = unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
    return isIterationStatement(
      statement,
      /*lookInLabeledStatements*/
      false
    ) ? visitIterationStatement(
      statement,
      /*outermostLabeledStatement*/
      node
    ) : factory2.restoreEnclosingLabel(Debug.checkDefined(visitNode(statement, visitor, isStatement, factory2.liftToBlock)), node, convertedLoopState && resetLabel);
  }
  function visitIterationStatement(node, outermostLabeledStatement) {
    switch (node.kind) {
      case 245 /* DoStatement */:
      case 246 /* WhileStatement */:
        return visitDoOrWhileStatement(node, outermostLabeledStatement);
      case 247 /* ForStatement */:
        return visitForStatement(node, outermostLabeledStatement);
      case 248 /* ForInStatement */:
        return visitForInStatement(node, outermostLabeledStatement);
      case 249 /* ForOfStatement */:
        return visitForOfStatement(node, outermostLabeledStatement);
    }
  }
  function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
    const ancestorFacts = enterSubtree(excludeFacts, includeFacts);
    const updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return updated;
  }
  function visitDoOrWhileStatement(node, outermostLabeledStatement) {
    return visitIterationStatementWithFacts(
      0 /* DoOrWhileStatementExcludes */,
      1280 /* DoOrWhileStatementIncludes */,
      node,
      outermostLabeledStatement
    );
  }
  function visitForStatement(node, outermostLabeledStatement) {
    return visitIterationStatementWithFacts(
      5056 /* ForStatementExcludes */,
      3328 /* ForStatementIncludes */,
      node,
      outermostLabeledStatement
    );
  }
  function visitEachChildOfForStatement2(node) {
    return factory2.updateForStatement(
      node,
      visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression),
      Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock))
    );
  }
  function visitForInStatement(node, outermostLabeledStatement) {
    return visitIterationStatementWithFacts(
      3008 /* ForInOrForOfStatementExcludes */,
      5376 /* ForInOrForOfStatementIncludes */,
      node,
      outermostLabeledStatement
    );
  }
  function visitForOfStatement(node, outermostLabeledStatement) {
    return visitIterationStatementWithFacts(
      3008 /* ForInOrForOfStatementExcludes */,
      5376 /* ForInOrForOfStatementIncludes */,
      node,
      outermostLabeledStatement,
      compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray
    );
  }
  function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
    const statements = [];
    const initializer = node.initializer;
    if (isVariableDeclarationList(initializer)) {
      if (node.initializer.flags & 3 /* BlockScoped */) {
        enableSubstitutionsForBlockScopedBindings();
      }
      const firstOriginalDeclaration = firstOrUndefined(initializer.declarations);
      if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) {
        const declarations = flattenDestructuringBinding(
          firstOriginalDeclaration,
          visitor,
          context,
          0 /* All */,
          boundValue
        );
        const declarationList = setTextRange(factory2.createVariableDeclarationList(declarations), node.initializer);
        setOriginalNode(declarationList, node.initializer);
        setSourceMapRange(declarationList, createRange(declarations[0].pos, last(declarations).end));
        statements.push(
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            declarationList
          )
        );
      } else {
        statements.push(
          setTextRange(
            factory2.createVariableStatement(
              /*modifiers*/
              void 0,
              setOriginalNode(
                setTextRange(
                  factory2.createVariableDeclarationList([
                    factory2.createVariableDeclaration(
                      firstOriginalDeclaration ? firstOriginalDeclaration.name : factory2.createTempVariable(
                        /*recordTempVariable*/
                        void 0
                      ),
                      /*exclamationToken*/
                      void 0,
                      /*type*/
                      void 0,
                      boundValue
                    )
                  ]),
                  moveRangePos(initializer, -1)
                ),
                initializer
              )
            ),
            moveRangeEnd(initializer, -1)
          )
        );
      }
    } else {
      const assignment = factory2.createAssignment(initializer, boundValue);
      if (isDestructuringAssignment(assignment)) {
        statements.push(factory2.createExpressionStatement(visitBinaryExpression(
          assignment,
          /*expressionResultIsUnused*/
          true
        )));
      } else {
        setTextRangeEnd(assignment, initializer.end);
        statements.push(setTextRange(factory2.createExpressionStatement(Debug.checkDefined(visitNode(assignment, visitor, isExpression))), moveRangeEnd(initializer, -1)));
      }
    }
    if (convertedLoopBodyStatements) {
      return createSyntheticBlockForConvertedStatements(addRange(statements, convertedLoopBodyStatements));
    } else {
      const statement = visitNode(node.statement, visitor, isStatement, factory2.liftToBlock);
      Debug.assert(statement);
      if (isBlock(statement)) {
        return factory2.updateBlock(statement, setTextRange(factory2.createNodeArray(concatenate(statements, statement.statements)), statement.statements));
      } else {
        statements.push(statement);
        return createSyntheticBlockForConvertedStatements(statements);
      }
    }
  }
  function createSyntheticBlockForConvertedStatements(statements) {
    return setEmitFlags(
      factory2.createBlock(
        factory2.createNodeArray(statements),
        /*multiLine*/
        true
      ),
      96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */
    );
  }
  function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
    const expression = visitNode(node.expression, visitor, isExpression);
    Debug.assert(expression);
    const counter = factory2.createLoopVariable();
    const rhsReference = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    setEmitFlags(expression, 96 /* NoSourceMap */ | getEmitFlags(expression));
    const forStatement = setTextRange(
      factory2.createForStatement(
        /*initializer*/
        setEmitFlags(
          setTextRange(
            factory2.createVariableDeclarationList([
              setTextRange(factory2.createVariableDeclaration(
                counter,
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                factory2.createNumericLiteral(0)
              ), moveRangePos(node.expression, -1)),
              setTextRange(factory2.createVariableDeclaration(
                rhsReference,
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                expression
              ), node.expression)
            ]),
            node.expression
          ),
          4194304 /* NoHoisting */
        ),
        /*condition*/
        setTextRange(
          factory2.createLessThan(
            counter,
            factory2.createPropertyAccessExpression(rhsReference, "length")
          ),
          node.expression
        ),
        /*incrementor*/
        setTextRange(factory2.createPostfixIncrement(counter), node.expression),
        /*statement*/
        convertForOfStatementHead(
          node,
          factory2.createElementAccessExpression(rhsReference, counter),
          convertedLoopBodyStatements
        )
      ),
      /*location*/
      node
    );
    setEmitFlags(forStatement, 512 /* NoTokenTrailingSourceMaps */);
    setTextRange(forStatement, node);
    return factory2.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
  }
  function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
    const expression = visitNode(node.expression, visitor, isExpression);
    Debug.assert(expression);
    const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const errorRecord = factory2.createUniqueName("e");
    const catchVariable = factory2.getGeneratedNameForNode(errorRecord);
    const returnMethod = factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    const values = setTextRange(emitHelpers().createValuesHelper(expression), node.expression);
    const next = factory2.createCallExpression(
      factory2.createPropertyAccessExpression(iterator, "next"),
      /*typeArguments*/
      void 0,
      []
    );
    hoistVariableDeclaration(errorRecord);
    hoistVariableDeclaration(returnMethod);
    const initializer = ancestorFacts & 1024 /* IterationContainer */ ? factory2.inlineExpressions([factory2.createAssignment(errorRecord, factory2.createVoidZero()), values]) : values;
    const forStatement = setEmitFlags(
      setTextRange(
        factory2.createForStatement(
          /*initializer*/
          setEmitFlags(
            setTextRange(
              factory2.createVariableDeclarationList([
                setTextRange(factory2.createVariableDeclaration(
                  iterator,
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  initializer
                ), node.expression),
                factory2.createVariableDeclaration(
                  result,
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  next
                )
              ]),
              node.expression
            ),
            4194304 /* NoHoisting */
          ),
          /*condition*/
          factory2.createLogicalNot(factory2.createPropertyAccessExpression(result, "done")),
          /*incrementor*/
          factory2.createAssignment(result, next),
          /*statement*/
          convertForOfStatementHead(
            node,
            factory2.createPropertyAccessExpression(result, "value"),
            convertedLoopBodyStatements
          )
        ),
        /*location*/
        node
      ),
      512 /* NoTokenTrailingSourceMaps */
    );
    return factory2.createTryStatement(
      factory2.createBlock([
        factory2.restoreEnclosingLabel(
          forStatement,
          outermostLabeledStatement,
          convertedLoopState && resetLabel
        )
      ]),
      factory2.createCatchClause(
        factory2.createVariableDeclaration(catchVariable),
        setEmitFlags(
          factory2.createBlock([
            factory2.createExpressionStatement(
              factory2.createAssignment(
                errorRecord,
                factory2.createObjectLiteralExpression([
                  factory2.createPropertyAssignment("error", catchVariable)
                ])
              )
            )
          ]),
          1 /* SingleLine */
        )
      ),
      factory2.createBlock([
        factory2.createTryStatement(
          /*tryBlock*/
          factory2.createBlock([
            setEmitFlags(
              factory2.createIfStatement(
                factory2.createLogicalAnd(
                  factory2.createLogicalAnd(
                    result,
                    factory2.createLogicalNot(
                      factory2.createPropertyAccessExpression(result, "done")
                    )
                  ),
                  factory2.createAssignment(
                    returnMethod,
                    factory2.createPropertyAccessExpression(iterator, "return")
                  )
                ),
                factory2.createExpressionStatement(
                  factory2.createFunctionCallCall(returnMethod, iterator, [])
                )
              ),
              1 /* SingleLine */
            )
          ]),
          /*catchClause*/
          void 0,
          /*finallyBlock*/
          setEmitFlags(
            factory2.createBlock([
              setEmitFlags(
                factory2.createIfStatement(
                  errorRecord,
                  factory2.createThrowStatement(
                    factory2.createPropertyAccessExpression(errorRecord, "error")
                  )
                ),
                1 /* SingleLine */
              )
            ]),
            1 /* SingleLine */
          )
        )
      ])
    );
  }
  function visitObjectLiteralExpression(node) {
    const properties = node.properties;
    let numInitialProperties = -1, hasComputed = false;
    for (let i = 0; i < properties.length; i++) {
      const property = properties[i];
      if (property.transformFlags & 1048576 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */ || (hasComputed = Debug.checkDefined(property.name).kind === 166 /* ComputedPropertyName */)) {
        numInitialProperties = i;
        break;
      }
    }
    if (numInitialProperties < 0) {
      return visitEachChild(node, visitor, context);
    }
    const temp = factory2.createTempVariable(hoistVariableDeclaration);
    const expressions = [];
    const assignment = factory2.createAssignment(
      temp,
      setEmitFlags(
        factory2.createObjectLiteralExpression(
          visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties),
          node.multiLine
        ),
        hasComputed ? 131072 /* Indented */ : 0
      )
    );
    if (node.multiLine) {
      startOnNewLine(assignment);
    }
    expressions.push(assignment);
    addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
    expressions.push(node.multiLine ? startOnNewLine(setParent(setTextRange(factory2.cloneNode(temp), temp), temp.parent)) : temp);
    return factory2.inlineExpressions(expressions);
  }
  function shouldConvertPartOfIterationStatement(node) {
    return (resolver.getNodeCheckFlags(node) & 8192 /* ContainsCapturedBlockScopeBinding */) !== 0;
  }
  function shouldConvertInitializerOfForStatement(node) {
    return isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
  }
  function shouldConvertConditionOfForStatement(node) {
    return isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
  }
  function shouldConvertIncrementorOfForStatement(node) {
    return isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
  }
  function shouldConvertIterationStatement(node) {
    return shouldConvertBodyOfIterationStatement(node) || shouldConvertInitializerOfForStatement(node);
  }
  function shouldConvertBodyOfIterationStatement(node) {
    return (resolver.getNodeCheckFlags(node) & 4096 /* LoopWithCapturedBlockScopedBinding */) !== 0;
  }
  function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
    if (!state.hoistedLocalVariables) {
      state.hoistedLocalVariables = [];
    }
    visit(node.name);
    function visit(node2) {
      if (node2.kind === 80 /* Identifier */) {
        state.hoistedLocalVariables.push(node2);
      } else {
        for (const element of node2.elements) {
          if (!isOmittedExpression(element)) {
            visit(element.name);
          }
        }
      }
    }
  }
  function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
    if (!shouldConvertIterationStatement(node)) {
      let saveAllowedNonLabeledJumps;
      if (convertedLoopState) {
        saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
        convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
      }
      const result = convert ? convert(
        node,
        outermostLabeledStatement,
        /*convertedLoopBodyStatements*/
        void 0,
        ancestorFacts
      ) : factory2.restoreEnclosingLabel(
        isForStatement(node) ? visitEachChildOfForStatement2(node) : visitEachChild(node, visitor, context),
        outermostLabeledStatement,
        convertedLoopState && resetLabel
      );
      if (convertedLoopState) {
        convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
      }
      return result;
    }
    const currentState = createConvertedLoopState(node);
    const statements = [];
    const outerConvertedLoopState = convertedLoopState;
    convertedLoopState = currentState;
    const initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : void 0;
    const bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : void 0;
    convertedLoopState = outerConvertedLoopState;
    if (initializerFunction)
      statements.push(initializerFunction.functionDeclaration);
    if (bodyFunction)
      statements.push(bodyFunction.functionDeclaration);
    addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
    if (initializerFunction) {
      statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
    }
    let loop;
    if (bodyFunction) {
      if (convert) {
        loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
      } else {
        const clone2 = convertIterationStatementCore(node, initializerFunction, factory2.createBlock(
          bodyFunction.part,
          /*multiLine*/
          true
        ));
        loop = factory2.restoreEnclosingLabel(clone2, outermostLabeledStatement, convertedLoopState && resetLabel);
      }
    } else {
      const clone2 = convertIterationStatementCore(node, initializerFunction, Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock)));
      loop = factory2.restoreEnclosingLabel(clone2, outermostLabeledStatement, convertedLoopState && resetLabel);
    }
    statements.push(loop);
    return statements;
  }
  function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
    switch (node.kind) {
      case 247 /* ForStatement */:
        return convertForStatement(node, initializerFunction, convertedLoopBody);
      case 248 /* ForInStatement */:
        return convertForInStatement(node, convertedLoopBody);
      case 249 /* ForOfStatement */:
        return convertForOfStatement(node, convertedLoopBody);
      case 245 /* DoStatement */:
        return convertDoStatement(node, convertedLoopBody);
      case 246 /* WhileStatement */:
        return convertWhileStatement(node, convertedLoopBody);
      default:
        return Debug.failBadSyntaxKind(node, "IterationStatement expected");
    }
  }
  function convertForStatement(node, initializerFunction, convertedLoopBody) {
    const shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
    const shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
    return factory2.updateForStatement(
      node,
      visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, isForInitializer),
      visitNode(shouldConvertCondition ? void 0 : node.condition, visitor, isExpression),
      visitNode(shouldConvertIncrementor ? void 0 : node.incrementor, visitorWithUnusedExpressionResult, isExpression),
      convertedLoopBody
    );
  }
  function convertForOfStatement(node, convertedLoopBody) {
    return factory2.updateForOfStatement(
      node,
      /*awaitModifier*/
      void 0,
      Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)),
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      convertedLoopBody
    );
  }
  function convertForInStatement(node, convertedLoopBody) {
    return factory2.updateForInStatement(
      node,
      Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)),
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      convertedLoopBody
    );
  }
  function convertDoStatement(node, convertedLoopBody) {
    return factory2.updateDoStatement(
      node,
      convertedLoopBody,
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression))
    );
  }
  function convertWhileStatement(node, convertedLoopBody) {
    return factory2.updateWhileStatement(
      node,
      Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
      convertedLoopBody
    );
  }
  function createConvertedLoopState(node) {
    let loopInitializer;
    switch (node.kind) {
      case 247 /* ForStatement */:
      case 248 /* ForInStatement */:
      case 249 /* ForOfStatement */:
        const initializer = node.initializer;
        if (initializer && initializer.kind === 260 /* VariableDeclarationList */) {
          loopInitializer = initializer;
        }
        break;
    }
    const loopParameters = [];
    const loopOutParameters = [];
    if (loopInitializer && getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */) {
      const hasCapturedBindingsInForHead = shouldConvertInitializerOfForStatement(node) || shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node);
      for (const decl of loopInitializer.declarations) {
        processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead);
      }
    }
    const currentState = { loopParameters, loopOutParameters };
    if (convertedLoopState) {
      if (convertedLoopState.argumentsName) {
        currentState.argumentsName = convertedLoopState.argumentsName;
      }
      if (convertedLoopState.thisName) {
        currentState.thisName = convertedLoopState.thisName;
      }
      if (convertedLoopState.hoistedLocalVariables) {
        currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
      }
    }
    return currentState;
  }
  function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
    let extraVariableDeclarations;
    if (state.argumentsName) {
      if (outerState) {
        outerState.argumentsName = state.argumentsName;
      } else {
        (extraVariableDeclarations || (extraVariableDeclarations = [])).push(
          factory2.createVariableDeclaration(
            state.argumentsName,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            factory2.createIdentifier("arguments")
          )
        );
      }
    }
    if (state.thisName) {
      if (outerState) {
        outerState.thisName = state.thisName;
      } else {
        (extraVariableDeclarations || (extraVariableDeclarations = [])).push(
          factory2.createVariableDeclaration(
            state.thisName,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            factory2.createIdentifier("this")
          )
        );
      }
    }
    if (state.hoistedLocalVariables) {
      if (outerState) {
        outerState.hoistedLocalVariables = state.hoistedLocalVariables;
      } else {
        if (!extraVariableDeclarations) {
          extraVariableDeclarations = [];
        }
        for (const identifier of state.hoistedLocalVariables) {
          extraVariableDeclarations.push(factory2.createVariableDeclaration(identifier));
        }
      }
    }
    if (state.loopOutParameters.length) {
      if (!extraVariableDeclarations) {
        extraVariableDeclarations = [];
      }
      for (const outParam of state.loopOutParameters) {
        extraVariableDeclarations.push(factory2.createVariableDeclaration(outParam.outParamName));
      }
    }
    if (state.conditionVariable) {
      if (!extraVariableDeclarations) {
        extraVariableDeclarations = [];
      }
      extraVariableDeclarations.push(factory2.createVariableDeclaration(
        state.conditionVariable,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        factory2.createFalse()
      ));
    }
    if (extraVariableDeclarations) {
      statements.push(factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList(extraVariableDeclarations)
      ));
    }
  }
  function createOutVariable(p) {
    return factory2.createVariableDeclaration(
      p.originalName,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      p.outParamName
    );
  }
  function createFunctionForInitializerOfForStatement(node, currentState) {
    const functionName = factory2.createUniqueName("_loop_init");
    const containsYield = (node.initializer.transformFlags & 1048576 /* ContainsYield */) !== 0;
    let emitFlags = 0 /* None */;
    if (currentState.containsLexicalThis)
      emitFlags |= 16 /* CapturesThis */;
    if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
      emitFlags |= 524288 /* AsyncFunctionBody */;
    const statements = [];
    statements.push(factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      node.initializer
    ));
    copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
    const functionDeclaration = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      setEmitFlags(
        factory2.createVariableDeclarationList([
          factory2.createVariableDeclaration(
            functionName,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            setEmitFlags(
              factory2.createFunctionExpression(
                /*modifiers*/
                void 0,
                containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0,
                /*name*/
                void 0,
                /*typeParameters*/
                void 0,
                /*parameters*/
                void 0,
                /*type*/
                void 0,
                Debug.checkDefined(visitNode(
                  factory2.createBlock(
                    statements,
                    /*multiLine*/
                    true
                  ),
                  visitor,
                  isBlock
                ))
              ),
              emitFlags
            )
          )
        ]),
        4194304 /* NoHoisting */
      )
    );
    const part = factory2.createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable));
    return { functionName, containsYield, functionDeclaration, part };
  }
  function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
    const functionName = factory2.createUniqueName("_loop");
    startLexicalEnvironment();
    const statement = visitNode(node.statement, visitor, isStatement, factory2.liftToBlock);
    const lexicalEnvironment = endLexicalEnvironment();
    const statements = [];
    if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
      currentState.conditionVariable = factory2.createUniqueName("inc");
      if (node.incrementor) {
        statements.push(factory2.createIfStatement(
          currentState.conditionVariable,
          factory2.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))),
          factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue()))
        ));
      } else {
        statements.push(factory2.createIfStatement(
          factory2.createLogicalNot(currentState.conditionVariable),
          factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue()))
        ));
      }
      if (shouldConvertConditionOfForStatement(node)) {
        statements.push(factory2.createIfStatement(
          factory2.createPrefixUnaryExpression(54 /* ExclamationToken */, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))),
          Debug.checkDefined(visitNode(factory2.createBreakStatement(), visitor, isStatement))
        ));
      }
    }
    Debug.assert(statement);
    if (isBlock(statement)) {
      addRange(statements, statement.statements);
    } else {
      statements.push(statement);
    }
    copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
    insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
    const loopBody = factory2.createBlock(
      statements,
      /*multiLine*/
      true
    );
    if (isBlock(statement))
      setOriginalNode(loopBody, statement);
    const containsYield = (node.statement.transformFlags & 1048576 /* ContainsYield */) !== 0;
    let emitFlags = 1048576 /* ReuseTempVariableScope */;
    if (currentState.containsLexicalThis)
      emitFlags |= 16 /* CapturesThis */;
    if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
      emitFlags |= 524288 /* AsyncFunctionBody */;
    const functionDeclaration = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      setEmitFlags(
        factory2.createVariableDeclarationList(
          [
            factory2.createVariableDeclaration(
              functionName,
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              setEmitFlags(
                factory2.createFunctionExpression(
                  /*modifiers*/
                  void 0,
                  containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0,
                  /*name*/
                  void 0,
                  /*typeParameters*/
                  void 0,
                  currentState.loopParameters,
                  /*type*/
                  void 0,
                  loopBody
                ),
                emitFlags
              )
            )
          ]
        ),
        4194304 /* NoHoisting */
      )
    );
    const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
    return { functionName, containsYield, functionDeclaration, part };
  }
  function copyOutParameter(outParam, copyDirection) {
    const source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
    const target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
    return factory2.createBinaryExpression(target, 64 /* EqualsToken */, source);
  }
  function copyOutParameters(outParams, partFlags, copyDirection, statements) {
    for (const outParam of outParams) {
      if (outParam.flags & partFlags) {
        statements.push(factory2.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
      }
    }
  }
  function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
    const call = factory2.createCallExpression(
      initFunctionExpressionName,
      /*typeArguments*/
      void 0,
      []
    );
    const callResult = containsYield ? factory2.createYieldExpression(
      factory2.createToken(42 /* AsteriskToken */),
      setEmitFlags(call, 8388608 /* Iterator */)
    ) : call;
    return factory2.createExpressionStatement(callResult);
  }
  function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
    const statements = [];
    const isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues;
    const call = factory2.createCallExpression(
      loopFunctionExpressionName,
      /*typeArguments*/
      void 0,
      map(state.loopParameters, (p) => p.name)
    );
    const callResult = containsYield ? factory2.createYieldExpression(
      factory2.createToken(42 /* AsteriskToken */),
      setEmitFlags(call, 8388608 /* Iterator */)
    ) : call;
    if (isSimpleLoop) {
      statements.push(factory2.createExpressionStatement(callResult));
      copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
    } else {
      const loopResultName = factory2.createUniqueName("state");
      const stateVariable = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList(
          [factory2.createVariableDeclaration(
            loopResultName,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            callResult
          )]
        )
      );
      statements.push(stateVariable);
      copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
      if (state.nonLocalJumps & 8 /* Return */) {
        let returnStatement;
        if (outerState) {
          outerState.nonLocalJumps |= 8 /* Return */;
          returnStatement = factory2.createReturnStatement(loopResultName);
        } else {
          returnStatement = factory2.createReturnStatement(factory2.createPropertyAccessExpression(loopResultName, "value"));
        }
        statements.push(
          factory2.createIfStatement(
            factory2.createTypeCheck(loopResultName, "object"),
            returnStatement
          )
        );
      }
      if (state.nonLocalJumps & 2 /* Break */) {
        statements.push(
          factory2.createIfStatement(
            factory2.createStrictEquality(
              loopResultName,
              factory2.createStringLiteral("break")
            ),
            factory2.createBreakStatement()
          )
        );
      }
      if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
        const caseClauses = [];
        processLabeledJumps(
          state.labeledNonLocalBreaks,
          /*isBreak*/
          true,
          loopResultName,
          outerState,
          caseClauses
        );
        processLabeledJumps(
          state.labeledNonLocalContinues,
          /*isBreak*/
          false,
          loopResultName,
          outerState,
          caseClauses
        );
        statements.push(
          factory2.createSwitchStatement(
            loopResultName,
            factory2.createCaseBlock(caseClauses)
          )
        );
      }
    }
    return statements;
  }
  function setLabeledJump(state, isBreak, labelText, labelMarker) {
    if (isBreak) {
      if (!state.labeledNonLocalBreaks) {
        state.labeledNonLocalBreaks = /* @__PURE__ */ new Map();
      }
      state.labeledNonLocalBreaks.set(labelText, labelMarker);
    } else {
      if (!state.labeledNonLocalContinues) {
        state.labeledNonLocalContinues = /* @__PURE__ */ new Map();
      }
      state.labeledNonLocalContinues.set(labelText, labelMarker);
    }
  }
  function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
    if (!table) {
      return;
    }
    table.forEach((labelMarker, labelText) => {
      const statements = [];
      if (!outerLoop || outerLoop.labels && outerLoop.labels.get(labelText)) {
        const label = factory2.createIdentifier(labelText);
        statements.push(isBreak ? factory2.createBreakStatement(label) : factory2.createContinueStatement(label));
      } else {
        setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
        statements.push(factory2.createReturnStatement(loopResultName));
      }
      caseClauses.push(factory2.createCaseClause(factory2.createStringLiteral(labelMarker), statements));
    });
  }
  function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead) {
    const name = decl.name;
    if (isBindingPattern(name)) {
      for (const element of name.elements) {
        if (!isOmittedExpression(element)) {
          processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForHead);
        }
      }
    } else {
      loopParameters.push(factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        name
      ));
      const checkFlags = resolver.getNodeCheckFlags(decl);
      if (checkFlags & 262144 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) {
        const outParamName = factory2.createUniqueName("out_" + idText(name));
        let flags = 0 /* None */;
        if (checkFlags & 262144 /* NeedsLoopOutParameter */) {
          flags |= 1 /* Body */;
        }
        if (isForStatement(container)) {
          if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
            flags |= 2 /* Initializer */;
          }
          if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) {
            flags |= 1 /* Body */;
          }
        }
        loopOutParameters.push({ flags, originalName: name, outParamName });
      }
    }
  }
  function addObjectLiteralMembers(expressions, node, receiver, start2) {
    const properties = node.properties;
    const numProperties = properties.length;
    for (let i = start2; i < numProperties; i++) {
      const property = properties[i];
      switch (property.kind) {
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
          const accessors = getAllAccessorDeclarations(node.properties, property);
          if (property === accessors.firstAccessor) {
            expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
          }
          break;
        case 173 /* MethodDeclaration */:
          expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
          break;
        case 302 /* PropertyAssignment */:
          expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
          break;
        case 303 /* ShorthandPropertyAssignment */:
          expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
          break;
        default:
          Debug.failBadSyntaxKind(node);
          break;
      }
    }
  }
  function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
    const expression = factory2.createAssignment(
      createMemberAccessForPropertyName(
        factory2,
        receiver,
        Debug.checkDefined(visitNode(property.name, visitor, isPropertyName))
      ),
      Debug.checkDefined(visitNode(property.initializer, visitor, isExpression))
    );
    setTextRange(expression, property);
    if (startsOnNewLine) {
      startOnNewLine(expression);
    }
    return expression;
  }
  function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
    const expression = factory2.createAssignment(
      createMemberAccessForPropertyName(
        factory2,
        receiver,
        Debug.checkDefined(visitNode(property.name, visitor, isPropertyName))
      ),
      factory2.cloneNode(property.name)
    );
    setTextRange(expression, property);
    if (startsOnNewLine) {
      startOnNewLine(expression);
    }
    return expression;
  }
  function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
    const expression = factory2.createAssignment(
      createMemberAccessForPropertyName(
        factory2,
        receiver,
        Debug.checkDefined(visitNode(method.name, visitor, isPropertyName))
      ),
      transformFunctionLikeToExpression(
        method,
        /*location*/
        method,
        /*name*/
        void 0,
        container
      )
    );
    setTextRange(expression, method);
    if (startsOnNewLine) {
      startOnNewLine(expression);
    }
    return expression;
  }
  function visitCatchClause(node) {
    const ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
    let updated;
    Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
    if (isBindingPattern(node.variableDeclaration.name)) {
      const temp = factory2.createTempVariable(
        /*recordTempVariable*/
        void 0
      );
      const newVariableDeclaration = factory2.createVariableDeclaration(temp);
      setTextRange(newVariableDeclaration, node.variableDeclaration);
      const vars = flattenDestructuringBinding(
        node.variableDeclaration,
        visitor,
        context,
        0 /* All */,
        temp
      );
      const list = factory2.createVariableDeclarationList(vars);
      setTextRange(list, node.variableDeclaration);
      const destructure = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        list
      );
      updated = factory2.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
    } else {
      updated = visitEachChild(node, visitor, context);
    }
    exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
    return updated;
  }
  function addStatementToStartOfBlock(block, statement) {
    const transformedStatements = visitNodes2(block.statements, visitor, isStatement);
    return factory2.updateBlock(block, [statement, ...transformedStatements]);
  }
  function visitMethodDeclaration(node) {
    Debug.assert(!isComputedPropertyName(node.name));
    const functionExpression = transformFunctionLikeToExpression(
      node,
      /*location*/
      moveRangePos(node, -1),
      /*name*/
      void 0,
      /*container*/
      void 0
    );
    setEmitFlags(functionExpression, 1024 /* NoLeadingComments */ | getEmitFlags(functionExpression));
    return setTextRange(
      factory2.createPropertyAssignment(
        node.name,
        functionExpression
      ),
      /*location*/
      node
    );
  }
  function visitAccessorDeclaration(node) {
    Debug.assert(!isComputedPropertyName(node.name));
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, 65 /* FunctionIncludes */);
    let updated;
    const parameters = visitParameterList(node.parameters, visitor, context);
    const body = transformFunctionBody2(node);
    if (node.kind === 176 /* GetAccessor */) {
      updated = factory2.updateGetAccessorDeclaration(node, node.modifiers, node.name, parameters, node.type, body);
    } else {
      updated = factory2.updateSetAccessorDeclaration(node, node.modifiers, node.name, parameters, body);
    }
    exitSubtree(ancestorFacts, 98304 /* FunctionSubtreeExcludes */, 0 /* None */);
    convertedLoopState = savedConvertedLoopState;
    return updated;
  }
  function visitShorthandPropertyAssignment(node) {
    return setTextRange(
      factory2.createPropertyAssignment(
        node.name,
        visitIdentifier(factory2.cloneNode(node.name))
      ),
      /*location*/
      node
    );
  }
  function visitComputedPropertyName(node) {
    return visitEachChild(node, visitor, context);
  }
  function visitYieldExpression(node) {
    return visitEachChild(node, visitor, context);
  }
  function visitArrayLiteralExpression(node) {
    if (some(node.elements, isSpreadElement)) {
      return transformAndSpreadElements(
        node.elements,
        /*isArgumentList*/
        false,
        !!node.multiLine,
        /*hasTrailingComma*/
        !!node.elements.hasTrailingComma
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCallExpression(node) {
    if (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */) {
      return visitTypeScriptClassWrapper(node);
    }
    const expression = skipOuterExpressions(node.expression);
    if (expression.kind === 108 /* SuperKeyword */ || isSuperProperty(expression) || some(node.arguments, isSpreadElement)) {
      return visitCallExpressionWithPotentialCapturedThisAssignment(
        node,
        /*assignToCapturedThis*/
        true
      );
    }
    return factory2.updateCallExpression(
      node,
      Debug.checkDefined(visitNode(node.expression, callExpressionVisitor, isExpression)),
      /*typeArguments*/
      void 0,
      visitNodes2(node.arguments, visitor, isExpression)
    );
  }
  function visitTypeScriptClassWrapper(node) {
    const body = cast(cast(skipOuterExpressions(node.expression), isArrowFunction).body, isBlock);
    const isVariableStatementWithInitializer = (stmt) => isVariableStatement(stmt) && !!first(stmt.declarationList.declarations).initializer;
    const savedConvertedLoopState = convertedLoopState;
    convertedLoopState = void 0;
    const bodyStatements = visitNodes2(body.statements, classWrapperStatementVisitor, isStatement);
    convertedLoopState = savedConvertedLoopState;
    const classStatements = filter(bodyStatements, isVariableStatementWithInitializer);
    const remainingStatements = filter(bodyStatements, (stmt) => !isVariableStatementWithInitializer(stmt));
    const varStatement = cast(first(classStatements), isVariableStatement);
    const variable = varStatement.declarationList.declarations[0];
    const initializer = skipOuterExpressions(variable.initializer);
    let aliasAssignment = tryCast(initializer, isAssignmentExpression);
    if (!aliasAssignment && isBinaryExpression(initializer) && initializer.operatorToken.kind === 28 /* CommaToken */) {
      aliasAssignment = tryCast(initializer.left, isAssignmentExpression);
    }
    const call = cast(aliasAssignment ? skipOuterExpressions(aliasAssignment.right) : initializer, isCallExpression);
    const func = cast(skipOuterExpressions(call.expression), isFunctionExpression);
    const funcStatements = func.body.statements;
    let classBodyStart = 0;
    let classBodyEnd = -1;
    const statements = [];
    if (aliasAssignment) {
      const extendsCall = tryCast(funcStatements[classBodyStart], isExpressionStatement);
      if (extendsCall) {
        statements.push(extendsCall);
        classBodyStart++;
      }
      statements.push(funcStatements[classBodyStart]);
      classBodyStart++;
      statements.push(
        factory2.createExpressionStatement(
          factory2.createAssignment(
            aliasAssignment.left,
            cast(variable.name, isIdentifier)
          )
        )
      );
    }
    while (!isReturnStatement(elementAt(funcStatements, classBodyEnd))) {
      classBodyEnd--;
    }
    addRange(statements, funcStatements, classBodyStart, classBodyEnd);
    if (classBodyEnd < -1) {
      addRange(statements, funcStatements, classBodyEnd + 1);
    }
    const returnStatement = tryCast(elementAt(funcStatements, classBodyEnd), isReturnStatement);
    for (const statement of remainingStatements) {
      if (isReturnStatement(statement) && (returnStatement == null ? void 0 : returnStatement.expression) && !isIdentifier(returnStatement.expression)) {
        statements.push(returnStatement);
      } else {
        statements.push(statement);
      }
    }
    addRange(
      statements,
      classStatements,
      /*start*/
      1
    );
    return factory2.restoreOuterExpressions(
      node.expression,
      factory2.restoreOuterExpressions(
        variable.initializer,
        factory2.restoreOuterExpressions(
          aliasAssignment && aliasAssignment.right,
          factory2.updateCallExpression(
            call,
            factory2.restoreOuterExpressions(
              call.expression,
              factory2.updateFunctionExpression(
                func,
                /*modifiers*/
                void 0,
                /*asteriskToken*/
                void 0,
                /*name*/
                void 0,
                /*typeParameters*/
                void 0,
                func.parameters,
                /*type*/
                void 0,
                factory2.updateBlock(
                  func.body,
                  statements
                )
              )
            ),
            /*typeArguments*/
            void 0,
            call.arguments
          )
        )
      )
    );
  }
  function visitSuperCallInBody(node) {
    return visitCallExpressionWithPotentialCapturedThisAssignment(
      node,
      /*assignToCapturedThis*/
      false
    );
  }
  function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
    if (node.transformFlags & 32768 /* ContainsRestOrSpread */ || node.expression.kind === 108 /* SuperKeyword */ || isSuperProperty(skipOuterExpressions(node.expression))) {
      const { target, thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration);
      if (node.expression.kind === 108 /* SuperKeyword */) {
        setEmitFlags(thisArg, 8 /* NoSubstitution */);
      }
      let resultingCall;
      if (node.transformFlags & 32768 /* ContainsRestOrSpread */) {
        resultingCall = factory2.createFunctionApplyCall(
          Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)),
          node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)),
          transformAndSpreadElements(
            node.arguments,
            /*isArgumentList*/
            true,
            /*multiLine*/
            false,
            /*hasTrailingComma*/
            false
          )
        );
      } else {
        resultingCall = setTextRange(
          factory2.createFunctionCallCall(
            Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)),
            node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)),
            visitNodes2(node.arguments, visitor, isExpression)
          ),
          node
        );
      }
      if (node.expression.kind === 108 /* SuperKeyword */) {
        const initializer = factory2.createLogicalOr(
          resultingCall,
          createActualThis()
        );
        resultingCall = assignToCapturedThis ? factory2.createAssignment(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer) : initializer;
      }
      return setOriginalNode(resultingCall, node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitNewExpression(node) {
    if (some(node.arguments, isSpreadElement)) {
      const { target, thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration);
      return factory2.createNewExpression(
        factory2.createFunctionApplyCall(
          Debug.checkDefined(visitNode(target, visitor, isExpression)),
          thisArg,
          transformAndSpreadElements(
            factory2.createNodeArray([factory2.createVoidZero(), ...node.arguments]),
            /*isArgumentList*/
            true,
            /*multiLine*/
            false,
            /*hasTrailingComma*/
            false
          )
        ),
        /*typeArguments*/
        void 0,
        []
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function transformAndSpreadElements(elements, isArgumentList, multiLine, hasTrailingComma) {
    const numElements = elements.length;
    const segments = flatten(
      // As we visit each element, we return one of two functions to use as the "key":
      // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]`
      // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]`
      spanMap(
        elements,
        partitionSpread,
        (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements)
      )
    );
    if (segments.length === 1) {
      const firstSegment = segments[0];
      if (isArgumentList && !compilerOptions.downlevelIteration || isPackedArrayLiteral(firstSegment.expression) || isCallToHelper(firstSegment.expression, "___spreadArray")) {
        return firstSegment.expression;
      }
    }
    const helpers = emitHelpers();
    const startsWithSpread = segments[0].kind !== 0 /* None */;
    let expression = startsWithSpread ? factory2.createArrayLiteralExpression() : segments[0].expression;
    for (let i = startsWithSpread ? 0 : 1; i < segments.length; i++) {
      const segment = segments[i];
      expression = helpers.createSpreadArrayHelper(
        expression,
        segment.expression,
        segment.kind === 1 /* UnpackedSpread */ && !isArgumentList
      );
    }
    return expression;
  }
  function partitionSpread(node) {
    return isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads;
  }
  function visitSpanOfSpreads(chunk) {
    return map(chunk, visitExpressionOfSpread);
  }
  function visitExpressionOfSpread(node) {
    Debug.assertNode(node, isSpreadElement);
    let expression = visitNode(node.expression, visitor, isExpression);
    Debug.assert(expression);
    const isCallToReadHelper = isCallToHelper(expression, "___read");
    let kind = isCallToReadHelper || isPackedArrayLiteral(expression) ? 2 /* PackedSpread */ : 1 /* UnpackedSpread */;
    if (compilerOptions.downlevelIteration && kind === 1 /* UnpackedSpread */ && !isArrayLiteralExpression(expression) && !isCallToReadHelper) {
      expression = emitHelpers().createReadHelper(
        expression,
        /*count*/
        void 0
      );
      kind = 2 /* PackedSpread */;
    }
    return createSpreadSegment(kind, expression);
  }
  function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
    const expression = factory2.createArrayLiteralExpression(
      visitNodes2(factory2.createNodeArray(chunk, hasTrailingComma), visitor, isExpression),
      multiLine
    );
    return createSpreadSegment(0 /* None */, expression);
  }
  function visitSpreadElement(node) {
    return visitNode(node.expression, visitor, isExpression);
  }
  function visitTemplateLiteral(node) {
    return setTextRange(factory2.createStringLiteral(node.text), node);
  }
  function visitStringLiteral(node) {
    if (node.hasExtendedUnicodeEscape) {
      return setTextRange(factory2.createStringLiteral(node.text), node);
    }
    return node;
  }
  function visitNumericLiteral(node) {
    if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
      return setTextRange(factory2.createNumericLiteral(node.text), node);
    }
    return node;
  }
  function visitTaggedTemplateExpression(node) {
    return processTaggedTemplateExpression(
      context,
      node,
      visitor,
      currentSourceFile,
      recordTaggedTemplateString,
      1 /* All */
    );
  }
  function visitTemplateExpression(node) {
    let expression = factory2.createStringLiteral(node.head.text);
    for (const span of node.templateSpans) {
      const args = [Debug.checkDefined(visitNode(span.expression, visitor, isExpression))];
      if (span.literal.text.length > 0) {
        args.push(factory2.createStringLiteral(span.literal.text));
      }
      expression = factory2.createCallExpression(
        factory2.createPropertyAccessExpression(expression, "concat"),
        /*typeArguments*/
        void 0,
        args
      );
    }
    return setTextRange(expression, node);
  }
  function visitSuperKeyword(isExpressionOfCall) {
    return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype") : factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
  }
  function visitMetaProperty(node) {
    if (node.keywordToken === 105 /* NewKeyword */ && node.name.escapedText === "target") {
      hierarchyFacts |= 32768 /* NewTarget */;
      return factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */);
    }
    return node;
  }
  function onEmitNode(hint, node, emitCallback) {
    if (enabledSubstitutions & 1 /* CapturedThis */ && isFunctionLike(node)) {
      const ancestorFacts = enterSubtree(
        32670 /* FunctionExcludes */,
        getEmitFlags(node) & 16 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */
      );
      previousOnEmitNode(hint, node, emitCallback);
      exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
      return;
    }
    previousOnEmitNode(hint, node, emitCallback);
  }
  function enableSubstitutionsForBlockScopedBindings() {
    if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
      enabledSubstitutions |= 2 /* BlockScopedBindings */;
      context.enableSubstitution(80 /* Identifier */);
    }
  }
  function enableSubstitutionsForCapturedThis() {
    if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
      enabledSubstitutions |= 1 /* CapturedThis */;
      context.enableSubstitution(110 /* ThisKeyword */);
      context.enableEmitNotification(175 /* Constructor */);
      context.enableEmitNotification(173 /* MethodDeclaration */);
      context.enableEmitNotification(176 /* GetAccessor */);
      context.enableEmitNotification(177 /* SetAccessor */);
      context.enableEmitNotification(218 /* ArrowFunction */);
      context.enableEmitNotification(217 /* FunctionExpression */);
      context.enableEmitNotification(261 /* FunctionDeclaration */);
    }
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    }
    if (isIdentifier(node)) {
      return substituteIdentifier(node);
    }
    return node;
  }
  function substituteIdentifier(node) {
    if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !isInternalName(node)) {
      const original = getParseTreeNode(node, isIdentifier);
      if (original && isNameOfDeclarationWithCollidingName(original)) {
        return setTextRange(factory2.getGeneratedNameForNode(original), node);
      }
    }
    return node;
  }
  function isNameOfDeclarationWithCollidingName(node) {
    switch (node.parent.kind) {
      case 207 /* BindingElement */:
      case 262 /* ClassDeclaration */:
      case 265 /* EnumDeclaration */:
      case 259 /* VariableDeclaration */:
        return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent);
    }
    return false;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return substituteExpressionIdentifier(node);
      case 110 /* ThisKeyword */:
        return substituteThisKeyword(node);
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !isInternalName(node)) {
      const declaration = resolver.getReferencedDeclarationWithCollidingName(node);
      if (declaration && !(isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
        return setTextRange(factory2.getGeneratedNameForNode(getNameOfDeclaration(declaration)), node);
      }
    }
    return node;
  }
  function isPartOfClassBody(declaration, node) {
    let currentNode = getParseTreeNode(node);
    if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
      return false;
    }
    const blockScope = getEnclosingBlockScopeContainer(declaration);
    while (currentNode) {
      if (currentNode === blockScope || currentNode === declaration) {
        return false;
      }
      if (isClassElement(currentNode) && currentNode.parent === declaration) {
        return true;
      }
      currentNode = currentNode.parent;
    }
    return false;
  }
  function substituteThisKeyword(node) {
    if (enabledSubstitutions & 1 /* CapturedThis */ && hierarchyFacts & 16 /* CapturesThis */) {
      return setTextRange(factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node);
    }
    return node;
  }
  function getClassMemberPrefix(node, member) {
    return isStatic(member) ? factory2.getInternalName(node) : factory2.createPropertyAccessExpression(factory2.getInternalName(node), "prototype");
  }
  function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
    if (!constructor || !hasExtendsClause) {
      return false;
    }
    if (some(constructor.parameters)) {
      return false;
    }
    const statement = firstOrUndefined(constructor.body.statements);
    if (!statement || !nodeIsSynthesized(statement) || statement.kind !== 243 /* ExpressionStatement */) {
      return false;
    }
    const statementExpression = statement.expression;
    if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== 212 /* CallExpression */) {
      return false;
    }
    const callTarget = statementExpression.expression;
    if (!nodeIsSynthesized(callTarget) || callTarget.kind !== 108 /* SuperKeyword */) {
      return false;
    }
    const callArgument = singleOrUndefined(statementExpression.arguments);
    if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== 229 /* SpreadElement */) {
      return false;
    }
    const expression = callArgument.expression;
    return isIdentifier(expression) && expression.escapedText === "arguments";
  }
}

// src/compiler/transformers/es5.ts
function transformES5(context) {
  const { factory: factory2 } = context;
  const compilerOptions = context.getCompilerOptions();
  let previousOnEmitNode;
  let noSubstitution;
  if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
    previousOnEmitNode = context.onEmitNode;
    context.onEmitNode = onEmitNode;
    context.enableEmitNotification(285 /* JsxOpeningElement */);
    context.enableEmitNotification(286 /* JsxClosingElement */);
    context.enableEmitNotification(284 /* JsxSelfClosingElement */);
    noSubstitution = [];
  }
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onSubstituteNode = onSubstituteNode;
  context.enableSubstitution(210 /* PropertyAccessExpression */);
  context.enableSubstitution(302 /* PropertyAssignment */);
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    return node;
  }
  function onEmitNode(hint, node, emitCallback) {
    switch (node.kind) {
      case 285 /* JsxOpeningElement */:
      case 286 /* JsxClosingElement */:
      case 284 /* JsxSelfClosingElement */:
        const tagName = node.tagName;
        noSubstitution[getOriginalNodeId(tagName)] = true;
        break;
    }
    previousOnEmitNode(hint, node, emitCallback);
  }
  function onSubstituteNode(hint, node) {
    if (node.id && noSubstitution && noSubstitution[node.id]) {
      return previousOnSubstituteNode(hint, node);
    }
    node = previousOnSubstituteNode(hint, node);
    if (isPropertyAccessExpression(node)) {
      return substitutePropertyAccessExpression(node);
    } else if (isPropertyAssignment(node)) {
      return substitutePropertyAssignment(node);
    }
    return node;
  }
  function substitutePropertyAccessExpression(node) {
    if (isPrivateIdentifier(node.name)) {
      return node;
    }
    const literalName = trySubstituteReservedName(node.name);
    if (literalName) {
      return setTextRange(factory2.createElementAccessExpression(node.expression, literalName), node);
    }
    return node;
  }
  function substitutePropertyAssignment(node) {
    const literalName = isIdentifier(node.name) && trySubstituteReservedName(node.name);
    if (literalName) {
      return factory2.updatePropertyAssignment(node, literalName, node.initializer);
    }
    return node;
  }
  function trySubstituteReservedName(name) {
    const token = identifierToKeywordKind(name);
    if (token !== void 0 && token >= 83 /* FirstReservedWord */ && token <= 118 /* LastReservedWord */) {
      return setTextRange(factory2.createStringLiteralFromNode(name), name);
    }
    return void 0;
  }
}

// src/compiler/transformers/generators.ts
function getInstructionName(instruction) {
  switch (instruction) {
    case 2 /* Return */:
      return "return";
    case 3 /* Break */:
      return "break";
    case 4 /* Yield */:
      return "yield";
    case 5 /* YieldStar */:
      return "yield*";
    case 7 /* Endfinally */:
      return "endfinally";
    default:
      return void 0;
  }
}
function transformGenerators(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    resumeLexicalEnvironment,
    endLexicalEnvironment,
    hoistFunctionDeclaration,
    hoistVariableDeclaration
  } = context;
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const resolver = context.getEmitResolver();
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onSubstituteNode = onSubstituteNode;
  let renamedCatchVariables;
  let renamedCatchVariableDeclarations;
  let inGeneratorFunctionBody;
  let inStatementContainingYield;
  let blocks;
  let blockOffsets;
  let blockActions;
  let blockStack;
  let labelOffsets;
  let labelExpressions;
  let nextLabelId = 1;
  let operations;
  let operationArguments;
  let operationLocations;
  let state;
  let blockIndex = 0;
  let labelNumber = 0;
  let labelNumbers;
  let lastOperationWasAbrupt;
  let lastOperationWasCompletion;
  let clauses;
  let statements;
  let exceptionBlockStack;
  let currentExceptionBlock;
  let withBlockStack;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile || (node.transformFlags & 2048 /* ContainsGenerator */) === 0) {
      return node;
    }
    const visited = visitEachChild(node, visitor, context);
    addEmitHelpers(visited, context.readEmitHelpers());
    return visited;
  }
  function visitor(node) {
    const transformFlags = node.transformFlags;
    if (inStatementContainingYield) {
      return visitJavaScriptInStatementContainingYield(node);
    } else if (inGeneratorFunctionBody) {
      return visitJavaScriptInGeneratorFunctionBody(node);
    } else if (isFunctionLikeDeclaration(node) && node.asteriskToken) {
      return visitGenerator(node);
    } else if (transformFlags & 2048 /* ContainsGenerator */) {
      return visitEachChild(node, visitor, context);
    } else {
      return node;
    }
  }
  function visitJavaScriptInStatementContainingYield(node) {
    switch (node.kind) {
      case 245 /* DoStatement */:
        return visitDoStatement(node);
      case 246 /* WhileStatement */:
        return visitWhileStatement(node);
      case 254 /* SwitchStatement */:
        return visitSwitchStatement(node);
      case 255 /* LabeledStatement */:
        return visitLabeledStatement(node);
      default:
        return visitJavaScriptInGeneratorFunctionBody(node);
    }
  }
  function visitJavaScriptInGeneratorFunctionBody(node) {
    switch (node.kind) {
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 217 /* FunctionExpression */:
        return visitFunctionExpression(node);
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        return visitAccessorDeclaration(node);
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 247 /* ForStatement */:
        return visitForStatement(node);
      case 248 /* ForInStatement */:
        return visitForInStatement(node);
      case 251 /* BreakStatement */:
        return visitBreakStatement(node);
      case 250 /* ContinueStatement */:
        return visitContinueStatement(node);
      case 252 /* ReturnStatement */:
        return visitReturnStatement(node);
      default:
        if (node.transformFlags & 1048576 /* ContainsYield */) {
          return visitJavaScriptContainingYield(node);
        } else if (node.transformFlags & (2048 /* ContainsGenerator */ | 4194304 /* ContainsHoistedDeclarationOrCompletion */)) {
          return visitEachChild(node, visitor, context);
        } else {
          return node;
        }
    }
  }
  function visitJavaScriptContainingYield(node) {
    switch (node.kind) {
      case 225 /* BinaryExpression */:
        return visitBinaryExpression(node);
      case 360 /* CommaListExpression */:
        return visitCommaListExpression(node);
      case 226 /* ConditionalExpression */:
        return visitConditionalExpression(node);
      case 228 /* YieldExpression */:
        return visitYieldExpression(node);
      case 208 /* ArrayLiteralExpression */:
        return visitArrayLiteralExpression(node);
      case 209 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 211 /* ElementAccessExpression */:
        return visitElementAccessExpression(node);
      case 212 /* CallExpression */:
        return visitCallExpression(node);
      case 213 /* NewExpression */:
        return visitNewExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitGenerator(node) {
    switch (node.kind) {
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 217 /* FunctionExpression */:
        return visitFunctionExpression(node);
      default:
        return Debug.failBadSyntaxKind(node);
    }
  }
  function visitFunctionDeclaration(node) {
    if (node.asteriskToken) {
      node = setOriginalNode(
        setTextRange(
          factory2.createFunctionDeclaration(
            node.modifiers,
            /*asteriskToken*/
            void 0,
            node.name,
            /*typeParameters*/
            void 0,
            visitParameterList(node.parameters, visitor, context),
            /*type*/
            void 0,
            transformGeneratorFunctionBody(node.body)
          ),
          /*location*/
          node
        ),
        node
      );
    } else {
      const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
      const savedInStatementContainingYield = inStatementContainingYield;
      inGeneratorFunctionBody = false;
      inStatementContainingYield = false;
      node = visitEachChild(node, visitor, context);
      inGeneratorFunctionBody = savedInGeneratorFunctionBody;
      inStatementContainingYield = savedInStatementContainingYield;
    }
    if (inGeneratorFunctionBody) {
      hoistFunctionDeclaration(node);
      return void 0;
    } else {
      return node;
    }
  }
  function visitFunctionExpression(node) {
    if (node.asteriskToken) {
      node = setOriginalNode(
        setTextRange(
          factory2.createFunctionExpression(
            /*modifiers*/
            void 0,
            /*asteriskToken*/
            void 0,
            node.name,
            /*typeParameters*/
            void 0,
            visitParameterList(node.parameters, visitor, context),
            /*type*/
            void 0,
            transformGeneratorFunctionBody(node.body)
          ),
          /*location*/
          node
        ),
        node
      );
    } else {
      const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
      const savedInStatementContainingYield = inStatementContainingYield;
      inGeneratorFunctionBody = false;
      inStatementContainingYield = false;
      node = visitEachChild(node, visitor, context);
      inGeneratorFunctionBody = savedInGeneratorFunctionBody;
      inStatementContainingYield = savedInStatementContainingYield;
    }
    return node;
  }
  function visitAccessorDeclaration(node) {
    const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
    const savedInStatementContainingYield = inStatementContainingYield;
    inGeneratorFunctionBody = false;
    inStatementContainingYield = false;
    node = visitEachChild(node, visitor, context);
    inGeneratorFunctionBody = savedInGeneratorFunctionBody;
    inStatementContainingYield = savedInStatementContainingYield;
    return node;
  }
  function transformGeneratorFunctionBody(body) {
    const statements2 = [];
    const savedInGeneratorFunctionBody = inGeneratorFunctionBody;
    const savedInStatementContainingYield = inStatementContainingYield;
    const savedBlocks = blocks;
    const savedBlockOffsets = blockOffsets;
    const savedBlockActions = blockActions;
    const savedBlockStack = blockStack;
    const savedLabelOffsets = labelOffsets;
    const savedLabelExpressions = labelExpressions;
    const savedNextLabelId = nextLabelId;
    const savedOperations = operations;
    const savedOperationArguments = operationArguments;
    const savedOperationLocations = operationLocations;
    const savedState = state;
    inGeneratorFunctionBody = true;
    inStatementContainingYield = false;
    blocks = void 0;
    blockOffsets = void 0;
    blockActions = void 0;
    blockStack = void 0;
    labelOffsets = void 0;
    labelExpressions = void 0;
    nextLabelId = 1;
    operations = void 0;
    operationArguments = void 0;
    operationLocations = void 0;
    state = factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    resumeLexicalEnvironment();
    const statementOffset = factory2.copyPrologue(
      body.statements,
      statements2,
      /*ensureUseStrict*/
      false,
      visitor
    );
    transformAndEmitStatements(body.statements, statementOffset);
    const buildResult = build2();
    insertStatementsAfterStandardPrologue(statements2, endLexicalEnvironment());
    statements2.push(factory2.createReturnStatement(buildResult));
    inGeneratorFunctionBody = savedInGeneratorFunctionBody;
    inStatementContainingYield = savedInStatementContainingYield;
    blocks = savedBlocks;
    blockOffsets = savedBlockOffsets;
    blockActions = savedBlockActions;
    blockStack = savedBlockStack;
    labelOffsets = savedLabelOffsets;
    labelExpressions = savedLabelExpressions;
    nextLabelId = savedNextLabelId;
    operations = savedOperations;
    operationArguments = savedOperationArguments;
    operationLocations = savedOperationLocations;
    state = savedState;
    return setTextRange(factory2.createBlock(statements2, body.multiLine), body);
  }
  function visitVariableStatement(node) {
    if (node.transformFlags & 1048576 /* ContainsYield */) {
      transformAndEmitVariableDeclarationList(node.declarationList);
      return void 0;
    } else {
      if (getEmitFlags(node) & 2097152 /* CustomPrologue */) {
        return node;
      }
      for (const variable of node.declarationList.declarations) {
        hoistVariableDeclaration(variable.name);
      }
      const variables = getInitializedVariables(node.declarationList);
      if (variables.length === 0) {
        return void 0;
      }
      return setSourceMapRange(
        factory2.createExpressionStatement(
          factory2.inlineExpressions(
            map(variables, transformInitializedVariable)
          )
        ),
        node
      );
    }
  }
  function visitBinaryExpression(node) {
    const assoc = getExpressionAssociativity(node);
    switch (assoc) {
      case 0 /* Left */:
        return visitLeftAssociativeBinaryExpression(node);
      case 1 /* Right */:
        return visitRightAssociativeBinaryExpression(node);
      default:
        return Debug.assertNever(assoc);
    }
  }
  function visitRightAssociativeBinaryExpression(node) {
    const { left, right } = node;
    if (containsYield(right)) {
      let target;
      switch (left.kind) {
        case 210 /* PropertyAccessExpression */:
          target = factory2.updatePropertyAccessExpression(
            left,
            cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))),
            left.name
          );
          break;
        case 211 /* ElementAccessExpression */:
          target = factory2.updateElementAccessExpression(
            left,
            cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))),
            cacheExpression(Debug.checkDefined(visitNode(left.argumentExpression, visitor, isExpression)))
          );
          break;
        default:
          target = Debug.checkDefined(visitNode(left, visitor, isExpression));
          break;
      }
      const operator = node.operatorToken.kind;
      if (isCompoundAssignment(operator)) {
        return setTextRange(
          factory2.createAssignment(
            target,
            setTextRange(
              factory2.createBinaryExpression(
                cacheExpression(target),
                getNonAssignmentOperatorForCompoundAssignment(operator),
                Debug.checkDefined(visitNode(right, visitor, isExpression))
              ),
              node
            )
          ),
          node
        );
      } else {
        return factory2.updateBinaryExpression(node, target, node.operatorToken, Debug.checkDefined(visitNode(right, visitor, isExpression)));
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitLeftAssociativeBinaryExpression(node) {
    if (containsYield(node.right)) {
      if (isLogicalOperator(node.operatorToken.kind)) {
        return visitLogicalBinaryExpression(node);
      } else if (node.operatorToken.kind === 28 /* CommaToken */) {
        return visitCommaExpression(node);
      }
      return factory2.updateBinaryExpression(
        node,
        cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))),
        node.operatorToken,
        Debug.checkDefined(visitNode(node.right, visitor, isExpression))
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCommaExpression(node) {
    let pendingExpressions = [];
    visit(node.left);
    visit(node.right);
    return factory2.inlineExpressions(pendingExpressions);
    function visit(node2) {
      if (isBinaryExpression(node2) && node2.operatorToken.kind === 28 /* CommaToken */) {
        visit(node2.left);
        visit(node2.right);
      } else {
        if (containsYield(node2) && pendingExpressions.length > 0) {
          emitWorker(1 /* Statement */, [factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))]);
          pendingExpressions = [];
        }
        pendingExpressions.push(Debug.checkDefined(visitNode(node2, visitor, isExpression)));
      }
    }
  }
  function visitCommaListExpression(node) {
    let pendingExpressions = [];
    for (const elem of node.elements) {
      if (isBinaryExpression(elem) && elem.operatorToken.kind === 28 /* CommaToken */) {
        pendingExpressions.push(visitCommaExpression(elem));
      } else {
        if (containsYield(elem) && pendingExpressions.length > 0) {
          emitWorker(1 /* Statement */, [factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions))]);
          pendingExpressions = [];
        }
        pendingExpressions.push(Debug.checkDefined(visitNode(elem, visitor, isExpression)));
      }
    }
    return factory2.inlineExpressions(pendingExpressions);
  }
  function visitLogicalBinaryExpression(node) {
    const resultLabel = defineLabel();
    const resultLocal = declareLocal();
    emitAssignment(
      resultLocal,
      Debug.checkDefined(visitNode(node.left, visitor, isExpression)),
      /*location*/
      node.left
    );
    if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
      emitBreakWhenFalse(
        resultLabel,
        resultLocal,
        /*location*/
        node.left
      );
    } else {
      emitBreakWhenTrue(
        resultLabel,
        resultLocal,
        /*location*/
        node.left
      );
    }
    emitAssignment(
      resultLocal,
      Debug.checkDefined(visitNode(node.right, visitor, isExpression)),
      /*location*/
      node.right
    );
    markLabel(resultLabel);
    return resultLocal;
  }
  function visitConditionalExpression(node) {
    if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
      const whenFalseLabel = defineLabel();
      const resultLabel = defineLabel();
      const resultLocal = declareLocal();
      emitBreakWhenFalse(
        whenFalseLabel,
        Debug.checkDefined(visitNode(node.condition, visitor, isExpression)),
        /*location*/
        node.condition
      );
      emitAssignment(
        resultLocal,
        Debug.checkDefined(visitNode(node.whenTrue, visitor, isExpression)),
        /*location*/
        node.whenTrue
      );
      emitBreak(resultLabel);
      markLabel(whenFalseLabel);
      emitAssignment(
        resultLocal,
        Debug.checkDefined(visitNode(node.whenFalse, visitor, isExpression)),
        /*location*/
        node.whenFalse
      );
      markLabel(resultLabel);
      return resultLocal;
    }
    return visitEachChild(node, visitor, context);
  }
  function visitYieldExpression(node) {
    const resumeLabel = defineLabel();
    const expression = visitNode(node.expression, visitor, isExpression);
    if (node.asteriskToken) {
      const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression;
      emitYieldStar(
        iterator,
        /*location*/
        node
      );
    } else {
      emitYield(
        expression,
        /*location*/
        node
      );
    }
    markLabel(resumeLabel);
    return createGeneratorResume(
      /*location*/
      node
    );
  }
  function visitArrayLiteralExpression(node) {
    return visitElements(
      node.elements,
      /*leadingElement*/
      void 0,
      /*location*/
      void 0,
      node.multiLine
    );
  }
  function visitElements(elements, leadingElement, location, multiLine) {
    const numInitialElements = countInitialNodesWithoutYield(elements);
    let temp;
    if (numInitialElements > 0) {
      temp = declareLocal();
      const initialElements = visitNodes2(elements, visitor, isExpression, 0, numInitialElements);
      emitAssignment(
        temp,
        factory2.createArrayLiteralExpression(
          leadingElement ? [leadingElement, ...initialElements] : initialElements
        )
      );
      leadingElement = void 0;
    }
    const expressions = reduceLeft(elements, reduceElement, [], numInitialElements);
    return temp ? factory2.createArrayConcatCall(temp, [factory2.createArrayLiteralExpression(expressions, multiLine)]) : setTextRange(
      factory2.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions] : expressions, multiLine),
      location
    );
    function reduceElement(expressions2, element) {
      if (containsYield(element) && expressions2.length > 0) {
        const hasAssignedTemp = temp !== void 0;
        if (!temp) {
          temp = declareLocal();
        }
        emitAssignment(
          temp,
          hasAssignedTemp ? factory2.createArrayConcatCall(
            temp,
            [factory2.createArrayLiteralExpression(expressions2, multiLine)]
          ) : factory2.createArrayLiteralExpression(
            leadingElement ? [leadingElement, ...expressions2] : expressions2,
            multiLine
          )
        );
        leadingElement = void 0;
        expressions2 = [];
      }
      expressions2.push(Debug.checkDefined(visitNode(element, visitor, isExpression)));
      return expressions2;
    }
  }
  function visitObjectLiteralExpression(node) {
    const properties = node.properties;
    const multiLine = node.multiLine;
    const numInitialProperties = countInitialNodesWithoutYield(properties);
    const temp = declareLocal();
    emitAssignment(
      temp,
      factory2.createObjectLiteralExpression(
        visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties),
        multiLine
      )
    );
    const expressions = reduceLeft(properties, reduceProperty, [], numInitialProperties);
    expressions.push(multiLine ? startOnNewLine(setParent(setTextRange(factory2.cloneNode(temp), temp), temp.parent)) : temp);
    return factory2.inlineExpressions(expressions);
    function reduceProperty(expressions2, property) {
      if (containsYield(property) && expressions2.length > 0) {
        emitStatement(factory2.createExpressionStatement(factory2.inlineExpressions(expressions2)));
        expressions2 = [];
      }
      const expression = createExpressionForObjectLiteralElementLike(factory2, node, property, temp);
      const visited = visitNode(expression, visitor, isExpression);
      if (visited) {
        if (multiLine) {
          startOnNewLine(visited);
        }
        expressions2.push(visited);
      }
      return expressions2;
    }
  }
  function visitElementAccessExpression(node) {
    if (containsYield(node.argumentExpression)) {
      return factory2.updateElementAccessExpression(
        node,
        cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))),
        Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression))
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCallExpression(node) {
    if (!isImportCall(node) && forEach(node.arguments, containsYield)) {
      const { target, thisArg } = factory2.createCallBinding(
        node.expression,
        hoistVariableDeclaration,
        languageVersion,
        /*cacheIdentifiers*/
        true
      );
      return setOriginalNode(
        setTextRange(
          factory2.createFunctionApplyCall(
            cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))),
            thisArg,
            visitElements(node.arguments)
          ),
          node
        ),
        node
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitNewExpression(node) {
    if (forEach(node.arguments, containsYield)) {
      const { target, thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration);
      return setOriginalNode(
        setTextRange(
          factory2.createNewExpression(
            factory2.createFunctionApplyCall(
              cacheExpression(Debug.checkDefined(visitNode(target, visitor, isExpression))),
              thisArg,
              visitElements(
                node.arguments,
                /*leadingElement*/
                factory2.createVoidZero()
              )
            ),
            /*typeArguments*/
            void 0,
            []
          ),
          node
        ),
        node
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function transformAndEmitStatements(statements2, start2 = 0) {
    const numStatements = statements2.length;
    for (let i = start2; i < numStatements; i++) {
      transformAndEmitStatement(statements2[i]);
    }
  }
  function transformAndEmitEmbeddedStatement(node) {
    if (isBlock(node)) {
      transformAndEmitStatements(node.statements);
    } else {
      transformAndEmitStatement(node);
    }
  }
  function transformAndEmitStatement(node) {
    const savedInStatementContainingYield = inStatementContainingYield;
    if (!inStatementContainingYield) {
      inStatementContainingYield = containsYield(node);
    }
    transformAndEmitStatementWorker(node);
    inStatementContainingYield = savedInStatementContainingYield;
  }
  function transformAndEmitStatementWorker(node) {
    switch (node.kind) {
      case 240 /* Block */:
        return transformAndEmitBlock(node);
      case 243 /* ExpressionStatement */:
        return transformAndEmitExpressionStatement(node);
      case 244 /* IfStatement */:
        return transformAndEmitIfStatement(node);
      case 245 /* DoStatement */:
        return transformAndEmitDoStatement(node);
      case 246 /* WhileStatement */:
        return transformAndEmitWhileStatement(node);
      case 247 /* ForStatement */:
        return transformAndEmitForStatement(node);
      case 248 /* ForInStatement */:
        return transformAndEmitForInStatement(node);
      case 250 /* ContinueStatement */:
        return transformAndEmitContinueStatement(node);
      case 251 /* BreakStatement */:
        return transformAndEmitBreakStatement(node);
      case 252 /* ReturnStatement */:
        return transformAndEmitReturnStatement(node);
      case 253 /* WithStatement */:
        return transformAndEmitWithStatement(node);
      case 254 /* SwitchStatement */:
        return transformAndEmitSwitchStatement(node);
      case 255 /* LabeledStatement */:
        return transformAndEmitLabeledStatement(node);
      case 256 /* ThrowStatement */:
        return transformAndEmitThrowStatement(node);
      case 257 /* TryStatement */:
        return transformAndEmitTryStatement(node);
      default:
        return emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function transformAndEmitBlock(node) {
    if (containsYield(node)) {
      transformAndEmitStatements(node.statements);
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function transformAndEmitExpressionStatement(node) {
    emitStatement(visitNode(node, visitor, isStatement));
  }
  function transformAndEmitVariableDeclarationList(node) {
    for (const variable of node.declarations) {
      const name = factory2.cloneNode(variable.name);
      setCommentRange(name, variable.name);
      hoistVariableDeclaration(name);
    }
    const variables = getInitializedVariables(node);
    const numVariables = variables.length;
    let variablesWritten = 0;
    let pendingExpressions = [];
    while (variablesWritten < numVariables) {
      for (let i = variablesWritten; i < numVariables; i++) {
        const variable = variables[i];
        if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
          break;
        }
        pendingExpressions.push(transformInitializedVariable(variable));
      }
      if (pendingExpressions.length) {
        emitStatement(factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions)));
        variablesWritten += pendingExpressions.length;
        pendingExpressions = [];
      }
    }
    return void 0;
  }
  function transformInitializedVariable(node) {
    return setSourceMapRange(
      factory2.createAssignment(
        setSourceMapRange(factory2.cloneNode(node.name), node.name),
        Debug.checkDefined(visitNode(node.initializer, visitor, isExpression))
      ),
      node
    );
  }
  function transformAndEmitIfStatement(node) {
    if (containsYield(node)) {
      if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
        const endLabel = defineLabel();
        const elseLabel = node.elseStatement ? defineLabel() : void 0;
        emitBreakWhenFalse(
          node.elseStatement ? elseLabel : endLabel,
          Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
          /*location*/
          node.expression
        );
        transformAndEmitEmbeddedStatement(node.thenStatement);
        if (node.elseStatement) {
          emitBreak(endLabel);
          markLabel(elseLabel);
          transformAndEmitEmbeddedStatement(node.elseStatement);
        }
        markLabel(endLabel);
      } else {
        emitStatement(visitNode(node, visitor, isStatement));
      }
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function transformAndEmitDoStatement(node) {
    if (containsYield(node)) {
      const conditionLabel = defineLabel();
      const loopLabel = defineLabel();
      beginLoopBlock(
        /*continueLabel*/
        conditionLabel
      );
      markLabel(loopLabel);
      transformAndEmitEmbeddedStatement(node.statement);
      markLabel(conditionLabel);
      emitBreakWhenTrue(loopLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)));
      endLoopBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function visitDoStatement(node) {
    if (inStatementContainingYield) {
      beginScriptLoopBlock();
      node = visitEachChild(node, visitor, context);
      endLoopBlock();
      return node;
    } else {
      return visitEachChild(node, visitor, context);
    }
  }
  function transformAndEmitWhileStatement(node) {
    if (containsYield(node)) {
      const loopLabel = defineLabel();
      const endLabel = beginLoopBlock(loopLabel);
      markLabel(loopLabel);
      emitBreakWhenFalse(endLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)));
      transformAndEmitEmbeddedStatement(node.statement);
      emitBreak(loopLabel);
      endLoopBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function visitWhileStatement(node) {
    if (inStatementContainingYield) {
      beginScriptLoopBlock();
      node = visitEachChild(node, visitor, context);
      endLoopBlock();
      return node;
    } else {
      return visitEachChild(node, visitor, context);
    }
  }
  function transformAndEmitForStatement(node) {
    if (containsYield(node)) {
      const conditionLabel = defineLabel();
      const incrementLabel = defineLabel();
      const endLabel = beginLoopBlock(incrementLabel);
      if (node.initializer) {
        const initializer = node.initializer;
        if (isVariableDeclarationList(initializer)) {
          transformAndEmitVariableDeclarationList(initializer);
        } else {
          emitStatement(
            setTextRange(
              factory2.createExpressionStatement(
                Debug.checkDefined(visitNode(initializer, visitor, isExpression))
              ),
              initializer
            )
          );
        }
      }
      markLabel(conditionLabel);
      if (node.condition) {
        emitBreakWhenFalse(endLabel, Debug.checkDefined(visitNode(node.condition, visitor, isExpression)));
      }
      transformAndEmitEmbeddedStatement(node.statement);
      markLabel(incrementLabel);
      if (node.incrementor) {
        emitStatement(
          setTextRange(
            factory2.createExpressionStatement(
              Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))
            ),
            node.incrementor
          )
        );
      }
      emitBreak(conditionLabel);
      endLoopBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function visitForStatement(node) {
    if (inStatementContainingYield) {
      beginScriptLoopBlock();
    }
    const initializer = node.initializer;
    if (initializer && isVariableDeclarationList(initializer)) {
      for (const variable of initializer.declarations) {
        hoistVariableDeclaration(variable.name);
      }
      const variables = getInitializedVariables(initializer);
      node = factory2.updateForStatement(
        node,
        variables.length > 0 ? factory2.inlineExpressions(map(variables, transformInitializedVariable)) : void 0,
        visitNode(node.condition, visitor, isExpression),
        visitNode(node.incrementor, visitor, isExpression),
        visitIterationBody(node.statement, visitor, context)
      );
    } else {
      node = visitEachChild(node, visitor, context);
    }
    if (inStatementContainingYield) {
      endLoopBlock();
    }
    return node;
  }
  function transformAndEmitForInStatement(node) {
    if (containsYield(node)) {
      const obj = declareLocal();
      const keysArray = declareLocal();
      const key = declareLocal();
      const keysIndex = factory2.createLoopVariable();
      const initializer = node.initializer;
      hoistVariableDeclaration(keysIndex);
      emitAssignment(obj, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)));
      emitAssignment(keysArray, factory2.createArrayLiteralExpression());
      emitStatement(
        factory2.createForInStatement(
          key,
          obj,
          factory2.createExpressionStatement(
            factory2.createCallExpression(
              factory2.createPropertyAccessExpression(keysArray, "push"),
              /*typeArguments*/
              void 0,
              [key]
            )
          )
        )
      );
      emitAssignment(keysIndex, factory2.createNumericLiteral(0));
      const conditionLabel = defineLabel();
      const incrementLabel = defineLabel();
      const endLoopLabel = beginLoopBlock(incrementLabel);
      markLabel(conditionLabel);
      emitBreakWhenFalse(endLoopLabel, factory2.createLessThan(keysIndex, factory2.createPropertyAccessExpression(keysArray, "length")));
      emitAssignment(key, factory2.createElementAccessExpression(keysArray, keysIndex));
      emitBreakWhenFalse(incrementLabel, factory2.createBinaryExpression(key, 103 /* InKeyword */, obj));
      let variable;
      if (isVariableDeclarationList(initializer)) {
        for (const variable2 of initializer.declarations) {
          hoistVariableDeclaration(variable2.name);
        }
        variable = factory2.cloneNode(initializer.declarations[0].name);
      } else {
        variable = Debug.checkDefined(visitNode(initializer, visitor, isExpression));
        Debug.assert(isLeftHandSideExpression(variable));
      }
      emitAssignment(variable, key);
      transformAndEmitEmbeddedStatement(node.statement);
      markLabel(incrementLabel);
      emitStatement(factory2.createExpressionStatement(factory2.createPostfixIncrement(keysIndex)));
      emitBreak(conditionLabel);
      endLoopBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function visitForInStatement(node) {
    if (inStatementContainingYield) {
      beginScriptLoopBlock();
    }
    const initializer = node.initializer;
    if (isVariableDeclarationList(initializer)) {
      for (const variable of initializer.declarations) {
        hoistVariableDeclaration(variable.name);
      }
      node = factory2.updateForInStatement(
        node,
        initializer.declarations[0].name,
        Debug.checkDefined(visitNode(node.expression, visitor, isExpression)),
        Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock))
      );
    } else {
      node = visitEachChild(node, visitor, context);
    }
    if (inStatementContainingYield) {
      endLoopBlock();
    }
    return node;
  }
  function transformAndEmitContinueStatement(node) {
    const label = findContinueTarget(node.label ? idText(node.label) : void 0);
    if (label > 0) {
      emitBreak(
        label,
        /*location*/
        node
      );
    } else {
      emitStatement(node);
    }
  }
  function visitContinueStatement(node) {
    if (inStatementContainingYield) {
      const label = findContinueTarget(node.label && idText(node.label));
      if (label > 0) {
        return createInlineBreak(
          label,
          /*location*/
          node
        );
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function transformAndEmitBreakStatement(node) {
    const label = findBreakTarget(node.label ? idText(node.label) : void 0);
    if (label > 0) {
      emitBreak(
        label,
        /*location*/
        node
      );
    } else {
      emitStatement(node);
    }
  }
  function visitBreakStatement(node) {
    if (inStatementContainingYield) {
      const label = findBreakTarget(node.label && idText(node.label));
      if (label > 0) {
        return createInlineBreak(
          label,
          /*location*/
          node
        );
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function transformAndEmitReturnStatement(node) {
    emitReturn(
      visitNode(node.expression, visitor, isExpression),
      /*location*/
      node
    );
  }
  function visitReturnStatement(node) {
    return createInlineReturn(
      visitNode(node.expression, visitor, isExpression),
      /*location*/
      node
    );
  }
  function transformAndEmitWithStatement(node) {
    if (containsYield(node)) {
      beginWithBlock(cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))));
      transformAndEmitEmbeddedStatement(node.statement);
      endWithBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function transformAndEmitSwitchStatement(node) {
    if (containsYield(node.caseBlock)) {
      const caseBlock = node.caseBlock;
      const numClauses = caseBlock.clauses.length;
      const endLabel = beginSwitchBlock();
      const expression = cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isExpression)));
      const clauseLabels = [];
      let defaultClauseIndex = -1;
      for (let i = 0; i < numClauses; i++) {
        const clause = caseBlock.clauses[i];
        clauseLabels.push(defineLabel());
        if (clause.kind === 296 /* DefaultClause */ && defaultClauseIndex === -1) {
          defaultClauseIndex = i;
        }
      }
      let clausesWritten = 0;
      let pendingClauses = [];
      while (clausesWritten < numClauses) {
        let defaultClausesSkipped = 0;
        for (let i = clausesWritten; i < numClauses; i++) {
          const clause = caseBlock.clauses[i];
          if (clause.kind === 295 /* CaseClause */) {
            if (containsYield(clause.expression) && pendingClauses.length > 0) {
              break;
            }
            pendingClauses.push(
              factory2.createCaseClause(
                Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)),
                [
                  createInlineBreak(
                    clauseLabels[i],
                    /*location*/
                    clause.expression
                  )
                ]
              )
            );
          } else {
            defaultClausesSkipped++;
          }
        }
        if (pendingClauses.length) {
          emitStatement(factory2.createSwitchStatement(expression, factory2.createCaseBlock(pendingClauses)));
          clausesWritten += pendingClauses.length;
          pendingClauses = [];
        }
        if (defaultClausesSkipped > 0) {
          clausesWritten += defaultClausesSkipped;
          defaultClausesSkipped = 0;
        }
      }
      if (defaultClauseIndex >= 0) {
        emitBreak(clauseLabels[defaultClauseIndex]);
      } else {
        emitBreak(endLabel);
      }
      for (let i = 0; i < numClauses; i++) {
        markLabel(clauseLabels[i]);
        transformAndEmitStatements(caseBlock.clauses[i].statements);
      }
      endSwitchBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function visitSwitchStatement(node) {
    if (inStatementContainingYield) {
      beginScriptSwitchBlock();
    }
    node = visitEachChild(node, visitor, context);
    if (inStatementContainingYield) {
      endSwitchBlock();
    }
    return node;
  }
  function transformAndEmitLabeledStatement(node) {
    if (containsYield(node)) {
      beginLabeledBlock(idText(node.label));
      transformAndEmitEmbeddedStatement(node.statement);
      endLabeledBlock();
    } else {
      emitStatement(visitNode(node, visitor, isStatement));
    }
  }
  function visitLabeledStatement(node) {
    if (inStatementContainingYield) {
      beginScriptLabeledBlock(idText(node.label));
    }
    node = visitEachChild(node, visitor, context);
    if (inStatementContainingYield) {
      endLabeledBlock();
    }
    return node;
  }
  function transformAndEmitThrowStatement(node) {
    emitThrow(
      Debug.checkDefined(visitNode(node.expression ?? factory2.createVoidZero(), visitor, isExpression)),
      /*location*/
      node
    );
  }
  function transformAndEmitTryStatement(node) {
    if (containsYield(node)) {
      beginExceptionBlock();
      transformAndEmitEmbeddedStatement(node.tryBlock);
      if (node.catchClause) {
        beginCatchBlock(node.catchClause.variableDeclaration);
        transformAndEmitEmbeddedStatement(node.catchClause.block);
      }
      if (node.finallyBlock) {
        beginFinallyBlock();
        transformAndEmitEmbeddedStatement(node.finallyBlock);
      }
      endExceptionBlock();
    } else {
      emitStatement(visitEachChild(node, visitor, context));
    }
  }
  function containsYield(node) {
    return !!node && (node.transformFlags & 1048576 /* ContainsYield */) !== 0;
  }
  function countInitialNodesWithoutYield(nodes) {
    const numNodes = nodes.length;
    for (let i = 0; i < numNodes; i++) {
      if (containsYield(nodes[i])) {
        return i;
      }
    }
    return -1;
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    }
    return node;
  }
  function substituteExpression(node) {
    if (isIdentifier(node)) {
      return substituteExpressionIdentifier(node);
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    if (!isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(idText(node))) {
      const original = getOriginalNode(node);
      if (isIdentifier(original) && original.parent) {
        const declaration = resolver.getReferencedValueDeclaration(original);
        if (declaration) {
          const name = renamedCatchVariableDeclarations[getOriginalNodeId(declaration)];
          if (name) {
            const clone2 = setParent(setTextRange(factory2.cloneNode(name), name), name.parent);
            setSourceMapRange(clone2, node);
            setCommentRange(clone2, node);
            return clone2;
          }
        }
      }
    }
    return node;
  }
  function cacheExpression(node) {
    if (isGeneratedIdentifier(node) || getEmitFlags(node) & 8192 /* HelperName */) {
      return node;
    }
    const temp = factory2.createTempVariable(hoistVariableDeclaration);
    emitAssignment(
      temp,
      node,
      /*location*/
      node
    );
    return temp;
  }
  function declareLocal(name) {
    const temp = name ? factory2.createUniqueName(name) : factory2.createTempVariable(
      /*recordTempVariable*/
      void 0
    );
    hoistVariableDeclaration(temp);
    return temp;
  }
  function defineLabel() {
    if (!labelOffsets) {
      labelOffsets = [];
    }
    const label = nextLabelId;
    nextLabelId++;
    labelOffsets[label] = -1;
    return label;
  }
  function markLabel(label) {
    Debug.assert(labelOffsets !== void 0, "No labels were defined.");
    labelOffsets[label] = operations ? operations.length : 0;
  }
  function beginBlock(block) {
    if (!blocks) {
      blocks = [];
      blockActions = [];
      blockOffsets = [];
      blockStack = [];
    }
    const index = blockActions.length;
    blockActions[index] = 0 /* Open */;
    blockOffsets[index] = operations ? operations.length : 0;
    blocks[index] = block;
    blockStack.push(block);
    return index;
  }
  function endBlock() {
    const block = peekBlock();
    if (block === void 0)
      return Debug.fail("beginBlock was never called.");
    const index = blockActions.length;
    blockActions[index] = 1 /* Close */;
    blockOffsets[index] = operations ? operations.length : 0;
    blocks[index] = block;
    blockStack.pop();
    return block;
  }
  function peekBlock() {
    return lastOrUndefined(blockStack);
  }
  function peekBlockKind() {
    const block = peekBlock();
    return block && block.kind;
  }
  function beginWithBlock(expression) {
    const startLabel = defineLabel();
    const endLabel = defineLabel();
    markLabel(startLabel);
    beginBlock({
      kind: 1 /* With */,
      expression,
      startLabel,
      endLabel
    });
  }
  function endWithBlock() {
    Debug.assert(peekBlockKind() === 1 /* With */);
    const block = endBlock();
    markLabel(block.endLabel);
  }
  function beginExceptionBlock() {
    const startLabel = defineLabel();
    const endLabel = defineLabel();
    markLabel(startLabel);
    beginBlock({
      kind: 0 /* Exception */,
      state: 0 /* Try */,
      startLabel,
      endLabel
    });
    emitNop();
    return endLabel;
  }
  function beginCatchBlock(variable) {
    Debug.assert(peekBlockKind() === 0 /* Exception */);
    let name;
    if (isGeneratedIdentifier(variable.name)) {
      name = variable.name;
      hoistVariableDeclaration(variable.name);
    } else {
      const text = idText(variable.name);
      name = declareLocal(text);
      if (!renamedCatchVariables) {
        renamedCatchVariables = /* @__PURE__ */ new Map();
        renamedCatchVariableDeclarations = [];
        context.enableSubstitution(80 /* Identifier */);
      }
      renamedCatchVariables.set(text, true);
      renamedCatchVariableDeclarations[getOriginalNodeId(variable)] = name;
    }
    const exception = peekBlock();
    Debug.assert(exception.state < 1 /* Catch */);
    const endLabel = exception.endLabel;
    emitBreak(endLabel);
    const catchLabel = defineLabel();
    markLabel(catchLabel);
    exception.state = 1 /* Catch */;
    exception.catchVariable = name;
    exception.catchLabel = catchLabel;
    emitAssignment(name, factory2.createCallExpression(
      factory2.createPropertyAccessExpression(state, "sent"),
      /*typeArguments*/
      void 0,
      []
    ));
    emitNop();
  }
  function beginFinallyBlock() {
    Debug.assert(peekBlockKind() === 0 /* Exception */);
    const exception = peekBlock();
    Debug.assert(exception.state < 2 /* Finally */);
    const endLabel = exception.endLabel;
    emitBreak(endLabel);
    const finallyLabel = defineLabel();
    markLabel(finallyLabel);
    exception.state = 2 /* Finally */;
    exception.finallyLabel = finallyLabel;
  }
  function endExceptionBlock() {
    Debug.assert(peekBlockKind() === 0 /* Exception */);
    const exception = endBlock();
    const state2 = exception.state;
    if (state2 < 2 /* Finally */) {
      emitBreak(exception.endLabel);
    } else {
      emitEndfinally();
    }
    markLabel(exception.endLabel);
    emitNop();
    exception.state = 3 /* Done */;
  }
  function beginScriptLoopBlock() {
    beginBlock({
      kind: 3 /* Loop */,
      isScript: true,
      breakLabel: -1,
      continueLabel: -1
    });
  }
  function beginLoopBlock(continueLabel) {
    const breakLabel = defineLabel();
    beginBlock({
      kind: 3 /* Loop */,
      isScript: false,
      breakLabel,
      continueLabel
    });
    return breakLabel;
  }
  function endLoopBlock() {
    Debug.assert(peekBlockKind() === 3 /* Loop */);
    const block = endBlock();
    const breakLabel = block.breakLabel;
    if (!block.isScript) {
      markLabel(breakLabel);
    }
  }
  function beginScriptSwitchBlock() {
    beginBlock({
      kind: 2 /* Switch */,
      isScript: true,
      breakLabel: -1
    });
  }
  function beginSwitchBlock() {
    const breakLabel = defineLabel();
    beginBlock({
      kind: 2 /* Switch */,
      isScript: false,
      breakLabel
    });
    return breakLabel;
  }
  function endSwitchBlock() {
    Debug.assert(peekBlockKind() === 2 /* Switch */);
    const block = endBlock();
    const breakLabel = block.breakLabel;
    if (!block.isScript) {
      markLabel(breakLabel);
    }
  }
  function beginScriptLabeledBlock(labelText) {
    beginBlock({
      kind: 4 /* Labeled */,
      isScript: true,
      labelText,
      breakLabel: -1
    });
  }
  function beginLabeledBlock(labelText) {
    const breakLabel = defineLabel();
    beginBlock({
      kind: 4 /* Labeled */,
      isScript: false,
      labelText,
      breakLabel
    });
  }
  function endLabeledBlock() {
    Debug.assert(peekBlockKind() === 4 /* Labeled */);
    const block = endBlock();
    if (!block.isScript) {
      markLabel(block.breakLabel);
    }
  }
  function supportsUnlabeledBreak(block) {
    return block.kind === 2 /* Switch */ || block.kind === 3 /* Loop */;
  }
  function supportsLabeledBreakOrContinue(block) {
    return block.kind === 4 /* Labeled */;
  }
  function supportsUnlabeledContinue(block) {
    return block.kind === 3 /* Loop */;
  }
  function hasImmediateContainingLabeledBlock(labelText, start2) {
    for (let j = start2; j >= 0; j--) {
      const containingBlock = blockStack[j];
      if (supportsLabeledBreakOrContinue(containingBlock)) {
        if (containingBlock.labelText === labelText) {
          return true;
        }
      } else {
        break;
      }
    }
    return false;
  }
  function findBreakTarget(labelText) {
    if (blockStack) {
      if (labelText) {
        for (let i = blockStack.length - 1; i >= 0; i--) {
          const block = blockStack[i];
          if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
            return block.breakLabel;
          } else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
            return block.breakLabel;
          }
        }
      } else {
        for (let i = blockStack.length - 1; i >= 0; i--) {
          const block = blockStack[i];
          if (supportsUnlabeledBreak(block)) {
            return block.breakLabel;
          }
        }
      }
    }
    return 0;
  }
  function findContinueTarget(labelText) {
    if (blockStack) {
      if (labelText) {
        for (let i = blockStack.length - 1; i >= 0; i--) {
          const block = blockStack[i];
          if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
            return block.continueLabel;
          }
        }
      } else {
        for (let i = blockStack.length - 1; i >= 0; i--) {
          const block = blockStack[i];
          if (supportsUnlabeledContinue(block)) {
            return block.continueLabel;
          }
        }
      }
    }
    return 0;
  }
  function createLabel(label) {
    if (label !== void 0 && label > 0) {
      if (labelExpressions === void 0) {
        labelExpressions = [];
      }
      const expression = factory2.createNumericLiteral(-1);
      if (labelExpressions[label] === void 0) {
        labelExpressions[label] = [expression];
      } else {
        labelExpressions[label].push(expression);
      }
      return expression;
    }
    return factory2.createOmittedExpression();
  }
  function createInstruction(instruction) {
    const literal = factory2.createNumericLiteral(instruction);
    addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
    return literal;
  }
  function createInlineBreak(label, location) {
    Debug.assertLessThan(0, label, "Invalid label");
    return setTextRange(
      factory2.createReturnStatement(
        factory2.createArrayLiteralExpression([
          createInstruction(3 /* Break */),
          createLabel(label)
        ])
      ),
      location
    );
  }
  function createInlineReturn(expression, location) {
    return setTextRange(
      factory2.createReturnStatement(
        factory2.createArrayLiteralExpression(
          expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)]
        )
      ),
      location
    );
  }
  function createGeneratorResume(location) {
    return setTextRange(
      factory2.createCallExpression(
        factory2.createPropertyAccessExpression(state, "sent"),
        /*typeArguments*/
        void 0,
        []
      ),
      location
    );
  }
  function emitNop() {
    emitWorker(0 /* Nop */);
  }
  function emitStatement(node) {
    if (node) {
      emitWorker(1 /* Statement */, [node]);
    } else {
      emitNop();
    }
  }
  function emitAssignment(left, right, location) {
    emitWorker(2 /* Assign */, [left, right], location);
  }
  function emitBreak(label, location) {
    emitWorker(3 /* Break */, [label], location);
  }
  function emitBreakWhenTrue(label, condition, location) {
    emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
  }
  function emitBreakWhenFalse(label, condition, location) {
    emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
  }
  function emitYieldStar(expression, location) {
    emitWorker(7 /* YieldStar */, [expression], location);
  }
  function emitYield(expression, location) {
    emitWorker(6 /* Yield */, [expression], location);
  }
  function emitReturn(expression, location) {
    emitWorker(8 /* Return */, [expression], location);
  }
  function emitThrow(expression, location) {
    emitWorker(9 /* Throw */, [expression], location);
  }
  function emitEndfinally() {
    emitWorker(10 /* Endfinally */);
  }
  function emitWorker(code, args, location) {
    if (operations === void 0) {
      operations = [];
      operationArguments = [];
      operationLocations = [];
    }
    if (labelOffsets === void 0) {
      markLabel(defineLabel());
    }
    const operationIndex = operations.length;
    operations[operationIndex] = code;
    operationArguments[operationIndex] = args;
    operationLocations[operationIndex] = location;
  }
  function build2() {
    blockIndex = 0;
    labelNumber = 0;
    labelNumbers = void 0;
    lastOperationWasAbrupt = false;
    lastOperationWasCompletion = false;
    clauses = void 0;
    statements = void 0;
    exceptionBlockStack = void 0;
    currentExceptionBlock = void 0;
    withBlockStack = void 0;
    const buildResult = buildStatements();
    return emitHelpers().createGeneratorHelper(
      setEmitFlags(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          /*asteriskToken*/
          void 0,
          /*name*/
          void 0,
          /*typeParameters*/
          void 0,
          [factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            state
          )],
          /*type*/
          void 0,
          factory2.createBlock(
            buildResult,
            /*multiLine*/
            buildResult.length > 0
          )
        ),
        1048576 /* ReuseTempVariableScope */
      )
    );
  }
  function buildStatements() {
    if (operations) {
      for (let operationIndex = 0; operationIndex < operations.length; operationIndex++) {
        writeOperation(operationIndex);
      }
      flushFinalLabel(operations.length);
    } else {
      flushFinalLabel(0);
    }
    if (clauses) {
      const labelExpression = factory2.createPropertyAccessExpression(state, "label");
      const switchStatement = factory2.createSwitchStatement(labelExpression, factory2.createCaseBlock(clauses));
      return [startOnNewLine(switchStatement)];
    }
    if (statements) {
      return statements;
    }
    return [];
  }
  function flushLabel() {
    if (!statements) {
      return;
    }
    appendLabel(
      /*markLabelEnd*/
      !lastOperationWasAbrupt
    );
    lastOperationWasAbrupt = false;
    lastOperationWasCompletion = false;
    labelNumber++;
  }
  function flushFinalLabel(operationIndex) {
    if (isFinalLabelReachable(operationIndex)) {
      tryEnterLabel(operationIndex);
      withBlockStack = void 0;
      writeReturn(
        /*expression*/
        void 0,
        /*operationLocation*/
        void 0
      );
    }
    if (statements && clauses) {
      appendLabel(
        /*markLabelEnd*/
        false
      );
    }
    updateLabelExpressions();
  }
  function isFinalLabelReachable(operationIndex) {
    if (!lastOperationWasCompletion) {
      return true;
    }
    if (!labelOffsets || !labelExpressions) {
      return false;
    }
    for (let label = 0; label < labelOffsets.length; label++) {
      if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
        return true;
      }
    }
    return false;
  }
  function appendLabel(markLabelEnd) {
    if (!clauses) {
      clauses = [];
    }
    if (statements) {
      if (withBlockStack) {
        for (let i = withBlockStack.length - 1; i >= 0; i--) {
          const withBlock = withBlockStack[i];
          statements = [factory2.createWithStatement(withBlock.expression, factory2.createBlock(statements))];
        }
      }
      if (currentExceptionBlock) {
        const { startLabel, catchLabel, finallyLabel, endLabel } = currentExceptionBlock;
        statements.unshift(
          factory2.createExpressionStatement(
            factory2.createCallExpression(
              factory2.createPropertyAccessExpression(factory2.createPropertyAccessExpression(state, "trys"), "push"),
              /*typeArguments*/
              void 0,
              [
                factory2.createArrayLiteralExpression([
                  createLabel(startLabel),
                  createLabel(catchLabel),
                  createLabel(finallyLabel),
                  createLabel(endLabel)
                ])
              ]
            )
          )
        );
        currentExceptionBlock = void 0;
      }
      if (markLabelEnd) {
        statements.push(
          factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.createPropertyAccessExpression(state, "label"),
              factory2.createNumericLiteral(labelNumber + 1)
            )
          )
        );
      }
    }
    clauses.push(
      factory2.createCaseClause(
        factory2.createNumericLiteral(labelNumber),
        statements || []
      )
    );
    statements = void 0;
  }
  function tryEnterLabel(operationIndex) {
    if (!labelOffsets) {
      return;
    }
    for (let label = 0; label < labelOffsets.length; label++) {
      if (labelOffsets[label] === operationIndex) {
        flushLabel();
        if (labelNumbers === void 0) {
          labelNumbers = [];
        }
        if (labelNumbers[labelNumber] === void 0) {
          labelNumbers[labelNumber] = [label];
        } else {
          labelNumbers[labelNumber].push(label);
        }
      }
    }
  }
  function updateLabelExpressions() {
    if (labelExpressions !== void 0 && labelNumbers !== void 0) {
      for (let labelNumber2 = 0; labelNumber2 < labelNumbers.length; labelNumber2++) {
        const labels = labelNumbers[labelNumber2];
        if (labels !== void 0) {
          for (const label of labels) {
            const expressions = labelExpressions[label];
            if (expressions !== void 0) {
              for (const expression of expressions) {
                expression.text = String(labelNumber2);
              }
            }
          }
        }
      }
    }
  }
  function tryEnterOrLeaveBlock(operationIndex) {
    if (blocks) {
      for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
        const block = blocks[blockIndex];
        const blockAction = blockActions[blockIndex];
        switch (block.kind) {
          case 0 /* Exception */:
            if (blockAction === 0 /* Open */) {
              if (!exceptionBlockStack) {
                exceptionBlockStack = [];
              }
              if (!statements) {
                statements = [];
              }
              exceptionBlockStack.push(currentExceptionBlock);
              currentExceptionBlock = block;
            } else if (blockAction === 1 /* Close */) {
              currentExceptionBlock = exceptionBlockStack.pop();
            }
            break;
          case 1 /* With */:
            if (blockAction === 0 /* Open */) {
              if (!withBlockStack) {
                withBlockStack = [];
              }
              withBlockStack.push(block);
            } else if (blockAction === 1 /* Close */) {
              withBlockStack.pop();
            }
            break;
        }
      }
    }
  }
  function writeOperation(operationIndex) {
    tryEnterLabel(operationIndex);
    tryEnterOrLeaveBlock(operationIndex);
    if (lastOperationWasAbrupt) {
      return;
    }
    lastOperationWasAbrupt = false;
    lastOperationWasCompletion = false;
    const opcode = operations[operationIndex];
    if (opcode === 0 /* Nop */) {
      return;
    } else if (opcode === 10 /* Endfinally */) {
      return writeEndfinally();
    }
    const args = operationArguments[operationIndex];
    if (opcode === 1 /* Statement */) {
      return writeStatement(args[0]);
    }
    const location = operationLocations[operationIndex];
    switch (opcode) {
      case 2 /* Assign */:
        return writeAssign(args[0], args[1], location);
      case 3 /* Break */:
        return writeBreak(args[0], location);
      case 4 /* BreakWhenTrue */:
        return writeBreakWhenTrue(args[0], args[1], location);
      case 5 /* BreakWhenFalse */:
        return writeBreakWhenFalse(args[0], args[1], location);
      case 6 /* Yield */:
        return writeYield(args[0], location);
      case 7 /* YieldStar */:
        return writeYieldStar(args[0], location);
      case 8 /* Return */:
        return writeReturn(args[0], location);
      case 9 /* Throw */:
        return writeThrow(args[0], location);
    }
  }
  function writeStatement(statement) {
    if (statement) {
      if (!statements) {
        statements = [statement];
      } else {
        statements.push(statement);
      }
    }
  }
  function writeAssign(left, right, operationLocation) {
    writeStatement(setTextRange(factory2.createExpressionStatement(factory2.createAssignment(left, right)), operationLocation));
  }
  function writeThrow(expression, operationLocation) {
    lastOperationWasAbrupt = true;
    lastOperationWasCompletion = true;
    writeStatement(setTextRange(factory2.createThrowStatement(expression), operationLocation));
  }
  function writeReturn(expression, operationLocation) {
    lastOperationWasAbrupt = true;
    lastOperationWasCompletion = true;
    writeStatement(
      setEmitFlags(
        setTextRange(
          factory2.createReturnStatement(
            factory2.createArrayLiteralExpression(
              expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)]
            )
          ),
          operationLocation
        ),
        768 /* NoTokenSourceMaps */
      )
    );
  }
  function writeBreak(label, operationLocation) {
    lastOperationWasAbrupt = true;
    writeStatement(
      setEmitFlags(
        setTextRange(
          factory2.createReturnStatement(
            factory2.createArrayLiteralExpression([
              createInstruction(3 /* Break */),
              createLabel(label)
            ])
          ),
          operationLocation
        ),
        768 /* NoTokenSourceMaps */
      )
    );
  }
  function writeBreakWhenTrue(label, condition, operationLocation) {
    writeStatement(
      setEmitFlags(
        factory2.createIfStatement(
          condition,
          setEmitFlags(
            setTextRange(
              factory2.createReturnStatement(
                factory2.createArrayLiteralExpression([
                  createInstruction(3 /* Break */),
                  createLabel(label)
                ])
              ),
              operationLocation
            ),
            768 /* NoTokenSourceMaps */
          )
        ),
        1 /* SingleLine */
      )
    );
  }
  function writeBreakWhenFalse(label, condition, operationLocation) {
    writeStatement(
      setEmitFlags(
        factory2.createIfStatement(
          factory2.createLogicalNot(condition),
          setEmitFlags(
            setTextRange(
              factory2.createReturnStatement(
                factory2.createArrayLiteralExpression([
                  createInstruction(3 /* Break */),
                  createLabel(label)
                ])
              ),
              operationLocation
            ),
            768 /* NoTokenSourceMaps */
          )
        ),
        1 /* SingleLine */
      )
    );
  }
  function writeYield(expression, operationLocation) {
    lastOperationWasAbrupt = true;
    writeStatement(
      setEmitFlags(
        setTextRange(
          factory2.createReturnStatement(
            factory2.createArrayLiteralExpression(
              expression ? [createInstruction(4 /* Yield */), expression] : [createInstruction(4 /* Yield */)]
            )
          ),
          operationLocation
        ),
        768 /* NoTokenSourceMaps */
      )
    );
  }
  function writeYieldStar(expression, operationLocation) {
    lastOperationWasAbrupt = true;
    writeStatement(
      setEmitFlags(
        setTextRange(
          factory2.createReturnStatement(
            factory2.createArrayLiteralExpression([
              createInstruction(5 /* YieldStar */),
              expression
            ])
          ),
          operationLocation
        ),
        768 /* NoTokenSourceMaps */
      )
    );
  }
  function writeEndfinally() {
    lastOperationWasAbrupt = true;
    writeStatement(
      factory2.createReturnStatement(
        factory2.createArrayLiteralExpression([
          createInstruction(7 /* Endfinally */)
        ])
      )
    );
  }
}

// src/compiler/transformers/module/module.ts
function transformModule(context) {
  function getTransformModuleDelegate(moduleKind2) {
    switch (moduleKind2) {
      case 2 /* AMD */:
        return transformAMDModule;
      case 3 /* UMD */:
        return transformUMDModule;
      default:
        return transformCommonJSModule;
    }
  }
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    startLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const compilerOptions = context.getCompilerOptions();
  const resolver = context.getEmitResolver();
  const host = context.getEmitHost();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const moduleKind = getEmitModuleKind(compilerOptions);
  const previousOnSubstituteNode = context.onSubstituteNode;
  const previousOnEmitNode = context.onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.enableSubstitution(212 /* CallExpression */);
  context.enableSubstitution(214 /* TaggedTemplateExpression */);
  context.enableSubstitution(80 /* Identifier */);
  context.enableSubstitution(225 /* BinaryExpression */);
  context.enableSubstitution(303 /* ShorthandPropertyAssignment */);
  context.enableEmitNotification(311 /* SourceFile */);
  const moduleInfoMap = [];
  let currentSourceFile;
  let currentModuleInfo;
  const noSubstitution = [];
  let needUMDDynamicImportHelper;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* ContainsDynamicImport */ || isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && outFile(compilerOptions))) {
      return node;
    }
    currentSourceFile = node;
    currentModuleInfo = collectExternalModuleInfo(context, node, resolver, compilerOptions);
    moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo;
    const transformModule2 = getTransformModuleDelegate(moduleKind);
    const updated = transformModule2(node);
    currentSourceFile = void 0;
    currentModuleInfo = void 0;
    needUMDDynamicImportHelper = false;
    return updated;
  }
  function shouldEmitUnderscoreUnderscoreESModule() {
    if (!currentModuleInfo.exportEquals && isExternalModule(currentSourceFile)) {
      return true;
    }
    return false;
  }
  function transformCommonJSModule(node) {
    startLexicalEnvironment();
    const statements = [];
    const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || !compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile);
    const statementOffset = factory2.copyPrologue(node.statements, statements, ensureUseStrict && !isJsonSourceFile(node), topLevelVisitor);
    if (shouldEmitUnderscoreUnderscoreESModule()) {
      append(statements, createUnderscoreUnderscoreESModule());
    }
    if (length(currentModuleInfo.exportedNames)) {
      const chunkSize = 50;
      for (let i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) {
        append(
          statements,
          factory2.createExpressionStatement(
            reduceLeft(
              currentModuleInfo.exportedNames.slice(i, i + chunkSize),
              (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev),
              factory2.createVoidZero()
            )
          )
        );
      }
    }
    append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement));
    addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset));
    addExportEqualsIfNeeded(
      statements,
      /*emitAsReturn*/
      false
    );
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    const updated = factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray(statements), node.statements));
    addEmitHelpers(updated, context.readEmitHelpers());
    return updated;
  }
  function transformAMDModule(node) {
    const define = factory2.createIdentifier("define");
    const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions);
    const jsonSourceFile = isJsonSourceFile(node) && node;
    const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies(
      node,
      /*includeNonAmdDependencies*/
      true
    );
    const updated = factory2.updateSourceFile(
      node,
      setTextRange(
        factory2.createNodeArray([
          factory2.createExpressionStatement(
            factory2.createCallExpression(
              define,
              /*typeArguments*/
              void 0,
              [
                // Add the module name (if provided).
                ...moduleName ? [moduleName] : [],
                // Add the dependency array argument:
                //
                //     ["require", "exports", module1", "module2", ...]
                factory2.createArrayLiteralExpression(jsonSourceFile ? emptyArray : [
                  factory2.createStringLiteral("require"),
                  factory2.createStringLiteral("exports"),
                  ...aliasedModuleNames,
                  ...unaliasedModuleNames
                ]),
                // Add the module body function argument:
                //
                //     function (require, exports, module1, module2) ...
                jsonSourceFile ? jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory2.createObjectLiteralExpression() : factory2.createFunctionExpression(
                  /*modifiers*/
                  void 0,
                  /*asteriskToken*/
                  void 0,
                  /*name*/
                  void 0,
                  /*typeParameters*/
                  void 0,
                  [
                    factory2.createParameterDeclaration(
                      /*modifiers*/
                      void 0,
                      /*dotDotDotToken*/
                      void 0,
                      "require"
                    ),
                    factory2.createParameterDeclaration(
                      /*modifiers*/
                      void 0,
                      /*dotDotDotToken*/
                      void 0,
                      "exports"
                    ),
                    ...importAliasNames
                  ],
                  /*type*/
                  void 0,
                  transformAsynchronousModuleBody(node)
                )
              ]
            )
          )
        ]),
        /*location*/
        node.statements
      )
    );
    addEmitHelpers(updated, context.readEmitHelpers());
    return updated;
  }
  function transformUMDModule(node) {
    const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies(
      node,
      /*includeNonAmdDependencies*/
      false
    );
    const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions);
    const umdHeader = factory2.createFunctionExpression(
      /*modifiers*/
      void 0,
      /*asteriskToken*/
      void 0,
      /*name*/
      void 0,
      /*typeParameters*/
      void 0,
      [factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        "factory"
      )],
      /*type*/
      void 0,
      setTextRange(
        factory2.createBlock(
          [
            factory2.createIfStatement(
              factory2.createLogicalAnd(
                factory2.createTypeCheck(factory2.createIdentifier("module"), "object"),
                factory2.createTypeCheck(factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), "object")
              ),
              factory2.createBlock([
                factory2.createVariableStatement(
                  /*modifiers*/
                  void 0,
                  [
                    factory2.createVariableDeclaration(
                      "v",
                      /*exclamationToken*/
                      void 0,
                      /*type*/
                      void 0,
                      factory2.createCallExpression(
                        factory2.createIdentifier("factory"),
                        /*typeArguments*/
                        void 0,
                        [
                          factory2.createIdentifier("require"),
                          factory2.createIdentifier("exports")
                        ]
                      )
                    )
                  ]
                ),
                setEmitFlags(
                  factory2.createIfStatement(
                    factory2.createStrictInequality(
                      factory2.createIdentifier("v"),
                      factory2.createIdentifier("undefined")
                    ),
                    factory2.createExpressionStatement(
                      factory2.createAssignment(
                        factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"),
                        factory2.createIdentifier("v")
                      )
                    )
                  ),
                  1 /* SingleLine */
                )
              ]),
              factory2.createIfStatement(
                factory2.createLogicalAnd(
                  factory2.createTypeCheck(factory2.createIdentifier("define"), "function"),
                  factory2.createPropertyAccessExpression(factory2.createIdentifier("define"), "amd")
                ),
                factory2.createBlock([
                  factory2.createExpressionStatement(
                    factory2.createCallExpression(
                      factory2.createIdentifier("define"),
                      /*typeArguments*/
                      void 0,
                      [
                        // Add the module name (if provided).
                        ...moduleName ? [moduleName] : [],
                        factory2.createArrayLiteralExpression([
                          factory2.createStringLiteral("require"),
                          factory2.createStringLiteral("exports"),
                          ...aliasedModuleNames,
                          ...unaliasedModuleNames
                        ]),
                        factory2.createIdentifier("factory")
                      ]
                    )
                  )
                ])
              )
            )
          ],
          /*multiLine*/
          true
        ),
        /*location*/
        void 0
      )
    );
    const updated = factory2.updateSourceFile(
      node,
      setTextRange(
        factory2.createNodeArray([
          factory2.createExpressionStatement(
            factory2.createCallExpression(
              umdHeader,
              /*typeArguments*/
              void 0,
              [
                // Add the module body function argument:
                //
                //     function (require, exports) ...
                factory2.createFunctionExpression(
                  /*modifiers*/
                  void 0,
                  /*asteriskToken*/
                  void 0,
                  /*name*/
                  void 0,
                  /*typeParameters*/
                  void 0,
                  [
                    factory2.createParameterDeclaration(
                      /*modifiers*/
                      void 0,
                      /*dotDotDotToken*/
                      void 0,
                      "require"
                    ),
                    factory2.createParameterDeclaration(
                      /*modifiers*/
                      void 0,
                      /*dotDotDotToken*/
                      void 0,
                      "exports"
                    ),
                    ...importAliasNames
                  ],
                  /*type*/
                  void 0,
                  transformAsynchronousModuleBody(node)
                )
              ]
            )
          )
        ]),
        /*location*/
        node.statements
      )
    );
    addEmitHelpers(updated, context.readEmitHelpers());
    return updated;
  }
  function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
    const aliasedModuleNames = [];
    const unaliasedModuleNames = [];
    const importAliasNames = [];
    for (const amdDependency of node.amdDependencies) {
      if (amdDependency.name) {
        aliasedModuleNames.push(factory2.createStringLiteral(amdDependency.path));
        importAliasNames.push(factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          amdDependency.name
        ));
      } else {
        unaliasedModuleNames.push(factory2.createStringLiteral(amdDependency.path));
      }
    }
    for (const importNode of currentModuleInfo.externalImports) {
      const externalModuleName = getExternalModuleNameLiteral(factory2, importNode, currentSourceFile, host, resolver, compilerOptions);
      const importAliasName = getLocalNameForExternalImport(factory2, importNode, currentSourceFile);
      if (externalModuleName) {
        if (includeNonAmdDependencies && importAliasName) {
          setEmitFlags(importAliasName, 8 /* NoSubstitution */);
          aliasedModuleNames.push(externalModuleName);
          importAliasNames.push(factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            importAliasName
          ));
        } else {
          unaliasedModuleNames.push(externalModuleName);
        }
      }
    }
    return { aliasedModuleNames, unaliasedModuleNames, importAliasNames };
  }
  function getAMDImportExpressionForImport(node) {
    if (isImportEqualsDeclaration(node) || isExportDeclaration(node) || !getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions)) {
      return void 0;
    }
    const name = getLocalNameForExternalImport(factory2, node, currentSourceFile);
    const expr = getHelperExpressionForImport(node, name);
    if (expr === name) {
      return void 0;
    }
    return factory2.createExpressionStatement(factory2.createAssignment(name, expr));
  }
  function transformAsynchronousModuleBody(node) {
    startLexicalEnvironment();
    const statements = [];
    const statementOffset = factory2.copyPrologue(
      node.statements,
      statements,
      /*ensureUseStrict*/
      !compilerOptions.noImplicitUseStrict,
      topLevelVisitor
    );
    if (shouldEmitUnderscoreUnderscoreESModule()) {
      append(statements, createUnderscoreUnderscoreESModule());
    }
    if (length(currentModuleInfo.exportedNames)) {
      append(statements, factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero())));
    }
    append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement));
    if (moduleKind === 2 /* AMD */) {
      addRange(statements, mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
    }
    addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset));
    addExportEqualsIfNeeded(
      statements,
      /*emitAsReturn*/
      true
    );
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    const body = factory2.createBlock(
      statements,
      /*multiLine*/
      true
    );
    if (needUMDDynamicImportHelper) {
      addEmitHelper(body, dynamicImportUMDHelper);
    }
    return body;
  }
  function addExportEqualsIfNeeded(statements, emitAsReturn) {
    if (currentModuleInfo.exportEquals) {
      const expressionResult = visitNode(currentModuleInfo.exportEquals.expression, visitor, isExpression);
      if (expressionResult) {
        if (emitAsReturn) {
          const statement = factory2.createReturnStatement(expressionResult);
          setTextRange(statement, currentModuleInfo.exportEquals);
          setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */);
          statements.push(statement);
        } else {
          const statement = factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.createPropertyAccessExpression(
                factory2.createIdentifier("module"),
                "exports"
              ),
              expressionResult
            )
          );
          setTextRange(statement, currentModuleInfo.exportEquals);
          setEmitFlags(statement, 3072 /* NoComments */);
          statements.push(statement);
        }
      }
    }
  }
  function topLevelVisitor(node) {
    switch (node.kind) {
      case 271 /* ImportDeclaration */:
        return visitImportDeclaration(node);
      case 270 /* ImportEqualsDeclaration */:
        return visitImportEqualsDeclaration(node);
      case 277 /* ExportDeclaration */:
        return visitExportDeclaration(node);
      case 276 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      default:
        return topLevelNestedVisitor(node);
    }
  }
  function topLevelNestedVisitor(node) {
    switch (node.kind) {
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 247 /* ForStatement */:
        return visitForStatement(
          node,
          /*isTopLevel*/
          true
        );
      case 248 /* ForInStatement */:
        return visitForInStatement(node);
      case 249 /* ForOfStatement */:
        return visitForOfStatement(node);
      case 245 /* DoStatement */:
        return visitDoStatement(node);
      case 246 /* WhileStatement */:
        return visitWhileStatement(node);
      case 255 /* LabeledStatement */:
        return visitLabeledStatement(node);
      case 253 /* WithStatement */:
        return visitWithStatement(node);
      case 244 /* IfStatement */:
        return visitIfStatement(node);
      case 254 /* SwitchStatement */:
        return visitSwitchStatement(node);
      case 268 /* CaseBlock */:
        return visitCaseBlock(node);
      case 295 /* CaseClause */:
        return visitCaseClause(node);
      case 296 /* DefaultClause */:
        return visitDefaultClause(node);
      case 257 /* TryStatement */:
        return visitTryStatement(node);
      case 298 /* CatchClause */:
        return visitCatchClause(node);
      case 240 /* Block */:
        return visitBlock(node);
      default:
        return visitor(node);
    }
  }
  function visitorWorker(node, valueIsDiscarded) {
    if (!(node.transformFlags & (8388608 /* ContainsDynamicImport */ | 4096 /* ContainsDestructuringAssignment */ | 268435456 /* ContainsUpdateExpressionForIdentifier */))) {
      return node;
    }
    switch (node.kind) {
      case 247 /* ForStatement */:
        return visitForStatement(
          node,
          /*isTopLevel*/
          false
        );
      case 243 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node, valueIsDiscarded);
      case 359 /* PartiallyEmittedExpression */:
        return visitPartiallyEmittedExpression(node, valueIsDiscarded);
      case 212 /* CallExpression */:
        if (isImportCall(node) && currentSourceFile.impliedNodeFormat === void 0) {
          return visitImportCallExpression(node);
        }
        break;
      case 225 /* BinaryExpression */:
        if (isDestructuringAssignment(node)) {
          return visitDestructuringAssignment(node, valueIsDiscarded);
        }
        break;
      case 223 /* PrefixUnaryExpression */:
      case 224 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(node, valueIsDiscarded);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    return visitorWorker(
      node,
      /*valueIsDiscarded*/
      false
    );
  }
  function discardedValueVisitor(node) {
    return visitorWorker(
      node,
      /*valueIsDiscarded*/
      true
    );
  }
  function destructuringNeedsFlattening(node) {
    if (isObjectLiteralExpression(node)) {
      for (const elem of node.properties) {
        switch (elem.kind) {
          case 302 /* PropertyAssignment */:
            if (destructuringNeedsFlattening(elem.initializer)) {
              return true;
            }
            break;
          case 303 /* ShorthandPropertyAssignment */:
            if (destructuringNeedsFlattening(elem.name)) {
              return true;
            }
            break;
          case 304 /* SpreadAssignment */:
            if (destructuringNeedsFlattening(elem.expression)) {
              return true;
            }
            break;
          case 173 /* MethodDeclaration */:
          case 176 /* GetAccessor */:
          case 177 /* SetAccessor */:
            return false;
          default:
            Debug.assertNever(elem, "Unhandled object member kind");
        }
      }
    } else if (isArrayLiteralExpression(node)) {
      for (const elem of node.elements) {
        if (isSpreadElement(elem)) {
          if (destructuringNeedsFlattening(elem.expression)) {
            return true;
          }
        } else if (destructuringNeedsFlattening(elem)) {
          return true;
        }
      }
    } else if (isIdentifier(node)) {
      return length(getExports(node)) > (isExportName(node) ? 1 : 0);
    }
    return false;
  }
  function visitDestructuringAssignment(node, valueIsDiscarded) {
    if (destructuringNeedsFlattening(node.left)) {
      return flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !valueIsDiscarded, createAllExportExpressions);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitForStatement(node, isTopLevel) {
    if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) {
      const exportStatements = appendExportsOfVariableDeclarationList(
        /*statements*/
        void 0,
        node.initializer,
        /*isForInOrOfInitializer*/
        false
      );
      if (exportStatements) {
        const statements = [];
        const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList);
        const varStatement = factory2.createVariableStatement(
          /*modifiers*/
          void 0,
          varDeclList
        );
        statements.push(varStatement);
        addRange(statements, exportStatements);
        const condition = visitNode(node.condition, visitor, isExpression);
        const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression);
        const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context);
        statements.push(factory2.updateForStatement(
          node,
          /*initializer*/
          void 0,
          condition,
          incrementor,
          body
        ));
        return statements;
      }
    }
    return factory2.updateForStatement(
      node,
      visitNode(node.initializer, discardedValueVisitor, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, discardedValueVisitor, isExpression),
      visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context)
    );
  }
  function visitForInStatement(node) {
    if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) {
      const exportStatements = appendExportsOfVariableDeclarationList(
        /*statements*/
        void 0,
        node.initializer,
        /*isForInOrOfInitializer*/
        true
      );
      if (some(exportStatements)) {
        const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer);
        const expression = visitNode(node.expression, visitor, isExpression);
        const body = visitIterationBody(node.statement, topLevelNestedVisitor, context);
        const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock(
          [...exportStatements, body],
          /*multiLine*/
          true
        );
        return factory2.updateForInStatement(node, initializer, expression, mergedBody);
      }
    }
    return factory2.updateForInStatement(
      node,
      visitNode(node.initializer, discardedValueVisitor, isForInitializer),
      visitNode(node.expression, visitor, isExpression),
      visitIterationBody(node.statement, topLevelNestedVisitor, context)
    );
  }
  function visitForOfStatement(node) {
    if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) {
      const exportStatements = appendExportsOfVariableDeclarationList(
        /*statements*/
        void 0,
        node.initializer,
        /*isForInOrOfInitializer*/
        true
      );
      const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer);
      const expression = visitNode(node.expression, visitor, isExpression);
      let body = visitIterationBody(node.statement, topLevelNestedVisitor, context);
      if (some(exportStatements)) {
        body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock(
          [...exportStatements, body],
          /*multiLine*/
          true
        );
      }
      return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body);
    }
    return factory2.updateForOfStatement(
      node,
      node.awaitModifier,
      visitNode(node.initializer, discardedValueVisitor, isForInitializer),
      visitNode(node.expression, visitor, isExpression),
      visitIterationBody(node.statement, topLevelNestedVisitor, context)
    );
  }
  function visitDoStatement(node) {
    return factory2.updateDoStatement(
      node,
      visitIterationBody(node.statement, topLevelNestedVisitor, context),
      visitNode(node.expression, visitor, isExpression)
    );
  }
  function visitWhileStatement(node) {
    return factory2.updateWhileStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      visitIterationBody(node.statement, topLevelNestedVisitor, context)
    );
  }
  function visitLabeledStatement(node) {
    return factory2.updateLabeledStatement(
      node,
      node.label,
      Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))
    );
  }
  function visitWithStatement(node) {
    return factory2.updateWithStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))
    );
  }
  function visitIfStatement(node) {
    return factory2.updateIfStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)),
      visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)
    );
  }
  function visitSwitchStatement(node) {
    return factory2.updateSwitchStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock))
    );
  }
  function visitCaseBlock(node) {
    return factory2.updateCaseBlock(
      node,
      visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause)
    );
  }
  function visitCaseClause(node) {
    return factory2.updateCaseClause(
      node,
      visitNode(node.expression, visitor, isExpression),
      visitNodes2(node.statements, topLevelNestedVisitor, isStatement)
    );
  }
  function visitDefaultClause(node) {
    return visitEachChild(node, topLevelNestedVisitor, context);
  }
  function visitTryStatement(node) {
    return visitEachChild(node, topLevelNestedVisitor, context);
  }
  function visitCatchClause(node) {
    return factory2.updateCatchClause(
      node,
      node.variableDeclaration,
      Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock))
    );
  }
  function visitBlock(node) {
    node = visitEachChild(node, topLevelNestedVisitor, context);
    return node;
  }
  function visitExpressionStatement(node) {
    return factory2.updateExpressionStatement(
      node,
      visitNode(node.expression, discardedValueVisitor, isExpression)
    );
  }
  function visitParenthesizedExpression(node, valueIsDiscarded) {
    return factory2.updateParenthesizedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression));
  }
  function visitPartiallyEmittedExpression(node, valueIsDiscarded) {
    return factory2.updatePartiallyEmittedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression));
  }
  function visitPreOrPostfixUnaryExpression(node, valueIsDiscarded) {
    if ((node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) {
      const exportedNames = getExports(node.operand);
      if (exportedNames) {
        let temp;
        let expression = visitNode(node.operand, visitor, isExpression);
        if (isPrefixUnaryExpression(node)) {
          expression = factory2.updatePrefixUnaryExpression(node, expression);
        } else {
          expression = factory2.updatePostfixUnaryExpression(node, expression);
          if (!valueIsDiscarded) {
            temp = factory2.createTempVariable(hoistVariableDeclaration);
            expression = factory2.createAssignment(temp, expression);
            setTextRange(expression, node);
          }
          expression = factory2.createComma(expression, factory2.cloneNode(node.operand));
          setTextRange(expression, node);
        }
        for (const exportName of exportedNames) {
          noSubstitution[getNodeId(expression)] = true;
          expression = createExportExpression(exportName, expression);
          setTextRange(expression, node);
        }
        if (temp) {
          noSubstitution[getNodeId(expression)] = true;
          expression = factory2.createComma(expression, temp);
          setTextRange(expression, node);
        }
        return expression;
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitImportCallExpression(node) {
    if (moduleKind === 0 /* None */ && languageVersion >= 7 /* ES2020 */) {
      return visitEachChild(node, visitor, context);
    }
    const externalModuleName = getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions);
    const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression);
    const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
    const containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */);
    switch (compilerOptions.module) {
      case 2 /* AMD */:
        return createImportCallExpressionAMD(argument, containsLexicalThis);
      case 3 /* UMD */:
        return createImportCallExpressionUMD(argument ?? factory2.createVoidZero(), containsLexicalThis);
      case 1 /* CommonJS */:
      default:
        return createImportCallExpressionCommonJS(argument);
    }
  }
  function createImportCallExpressionUMD(arg, containsLexicalThis) {
    needUMDDynamicImportHelper = true;
    if (isSimpleCopiableExpression(arg)) {
      const argClone = isGeneratedIdentifier(arg) ? arg : isStringLiteral(arg) ? factory2.createStringLiteralFromNode(arg) : setEmitFlags(setTextRange(factory2.cloneNode(arg), arg), 3072 /* NoComments */);
      return factory2.createConditionalExpression(
        /*condition*/
        factory2.createIdentifier("__syncRequire"),
        /*questionToken*/
        void 0,
        /*whenTrue*/
        createImportCallExpressionCommonJS(arg),
        /*colonToken*/
        void 0,
        /*whenFalse*/
        createImportCallExpressionAMD(argClone, containsLexicalThis)
      );
    } else {
      const temp = factory2.createTempVariable(hoistVariableDeclaration);
      return factory2.createComma(factory2.createAssignment(temp, arg), factory2.createConditionalExpression(
        /*condition*/
        factory2.createIdentifier("__syncRequire"),
        /*questionToken*/
        void 0,
        /*whenTrue*/
        createImportCallExpressionCommonJS(
          temp,
          /*isInlineable*/
          true
        ),
        /*colonToken*/
        void 0,
        /*whenFalse*/
        createImportCallExpressionAMD(temp, containsLexicalThis)
      ));
    }
  }
  function createImportCallExpressionAMD(arg, containsLexicalThis) {
    const resolve = factory2.createUniqueName("resolve");
    const reject = factory2.createUniqueName("reject");
    const parameters = [
      factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        /*name*/
        resolve
      ),
      factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        /*name*/
        reject
      )
    ];
    const body = factory2.createBlock([
      factory2.createExpressionStatement(
        factory2.createCallExpression(
          factory2.createIdentifier("require"),
          /*typeArguments*/
          void 0,
          [factory2.createArrayLiteralExpression([arg || factory2.createOmittedExpression()]), resolve, reject]
        )
      )
    ]);
    let func;
    if (languageVersion >= 2 /* ES2015 */) {
      func = factory2.createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        parameters,
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        body
      );
    } else {
      func = factory2.createFunctionExpression(
        /*modifiers*/
        void 0,
        /*asteriskToken*/
        void 0,
        /*name*/
        void 0,
        /*typeParameters*/
        void 0,
        parameters,
        /*type*/
        void 0,
        body
      );
      if (containsLexicalThis) {
        setEmitFlags(func, 16 /* CapturesThis */);
      }
    }
    const promise = factory2.createNewExpression(
      factory2.createIdentifier("Promise"),
      /*typeArguments*/
      void 0,
      [func]
    );
    if (getESModuleInterop(compilerOptions)) {
      return factory2.createCallExpression(
        factory2.createPropertyAccessExpression(promise, factory2.createIdentifier("then")),
        /*typeArguments*/
        void 0,
        [emitHelpers().createImportStarCallbackHelper()]
      );
    }
    return promise;
  }
  function createImportCallExpressionCommonJS(arg, isInlineable) {
    const needSyncEval = arg && !isSimpleInlineableExpression(arg) && !isInlineable;
    const promiseResolveCall = factory2.createCallExpression(
      factory2.createPropertyAccessExpression(factory2.createIdentifier("Promise"), "resolve"),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      needSyncEval ? languageVersion >= 2 /* ES2015 */ ? [
        factory2.createTemplateExpression(factory2.createTemplateHead(""), [
          factory2.createTemplateSpan(arg, factory2.createTemplateTail(""))
        ])
      ] : [
        factory2.createCallExpression(
          factory2.createPropertyAccessExpression(factory2.createStringLiteral(""), "concat"),
          /*typeArguments*/
          void 0,
          [arg]
        )
      ] : []
    );
    let requireCall = factory2.createCallExpression(
      factory2.createIdentifier("require"),
      /*typeArguments*/
      void 0,
      needSyncEval ? [factory2.createIdentifier("s")] : arg ? [arg] : []
    );
    if (getESModuleInterop(compilerOptions)) {
      requireCall = emitHelpers().createImportStarHelper(requireCall);
    }
    const parameters = needSyncEval ? [
      factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        /*name*/
        "s"
      )
    ] : [];
    let func;
    if (languageVersion >= 2 /* ES2015 */) {
      func = factory2.createArrowFunction(
        /*modifiers*/
        void 0,
        /*typeParameters*/
        void 0,
        /*parameters*/
        parameters,
        /*type*/
        void 0,
        /*equalsGreaterThanToken*/
        void 0,
        requireCall
      );
    } else {
      func = factory2.createFunctionExpression(
        /*modifiers*/
        void 0,
        /*asteriskToken*/
        void 0,
        /*name*/
        void 0,
        /*typeParameters*/
        void 0,
        /*parameters*/
        parameters,
        /*type*/
        void 0,
        factory2.createBlock([factory2.createReturnStatement(requireCall)])
      );
    }
    const downleveledImport = factory2.createCallExpression(
      factory2.createPropertyAccessExpression(promiseResolveCall, "then"),
      /*typeArguments*/
      void 0,
      [func]
    );
    return downleveledImport;
  }
  function getHelperExpressionForExport(node, innerExpr) {
    if (!getESModuleInterop(compilerOptions) || getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) {
      return innerExpr;
    }
    if (getExportNeedsImportStarHelper(node)) {
      return emitHelpers().createImportStarHelper(innerExpr);
    }
    return innerExpr;
  }
  function getHelperExpressionForImport(node, innerExpr) {
    if (!getESModuleInterop(compilerOptions) || getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) {
      return innerExpr;
    }
    if (getImportNeedsImportStarHelper(node)) {
      return emitHelpers().createImportStarHelper(innerExpr);
    }
    if (getImportNeedsImportDefaultHelper(node)) {
      return emitHelpers().createImportDefaultHelper(innerExpr);
    }
    return innerExpr;
  }
  function visitImportDeclaration(node) {
    let statements;
    const namespaceDeclaration = getNamespaceDeclarationNode(node);
    if (moduleKind !== 2 /* AMD */) {
      if (!node.importClause) {
        return setOriginalNode(setTextRange(factory2.createExpressionStatement(createRequireCall2(node)), node), node);
      } else {
        const variables = [];
        if (namespaceDeclaration && !isDefaultImport(node)) {
          variables.push(
            factory2.createVariableDeclaration(
              factory2.cloneNode(namespaceDeclaration.name),
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              getHelperExpressionForImport(node, createRequireCall2(node))
            )
          );
        } else {
          variables.push(
            factory2.createVariableDeclaration(
              factory2.getGeneratedNameForNode(node),
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              getHelperExpressionForImport(node, createRequireCall2(node))
            )
          );
          if (namespaceDeclaration && isDefaultImport(node)) {
            variables.push(
              factory2.createVariableDeclaration(
                factory2.cloneNode(namespaceDeclaration.name),
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                factory2.getGeneratedNameForNode(node)
              )
            );
          }
        }
        statements = append(
          statements,
          setOriginalNode(
            setTextRange(
              factory2.createVariableStatement(
                /*modifiers*/
                void 0,
                factory2.createVariableDeclarationList(
                  variables,
                  languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
                )
              ),
              /*location*/
              node
            ),
            /*original*/
            node
          )
        );
      }
    } else if (namespaceDeclaration && isDefaultImport(node)) {
      statements = append(
        statements,
        factory2.createVariableStatement(
          /*modifiers*/
          void 0,
          factory2.createVariableDeclarationList(
            [
              setOriginalNode(
                setTextRange(
                  factory2.createVariableDeclaration(
                    factory2.cloneNode(namespaceDeclaration.name),
                    /*exclamationToken*/
                    void 0,
                    /*type*/
                    void 0,
                    factory2.getGeneratedNameForNode(node)
                  ),
                  /*location*/
                  node
                ),
                /*original*/
                node
              )
            ],
            languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
          )
        )
      );
    }
    statements = appendExportsOfImportDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function createRequireCall2(importNode) {
    const moduleName = getExternalModuleNameLiteral(factory2, importNode, currentSourceFile, host, resolver, compilerOptions);
    const args = [];
    if (moduleName) {
      args.push(moduleName);
    }
    return factory2.createCallExpression(
      factory2.createIdentifier("require"),
      /*typeArguments*/
      void 0,
      args
    );
  }
  function visitImportEqualsDeclaration(node) {
    Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
    let statements;
    if (moduleKind !== 2 /* AMD */) {
      if (hasSyntacticModifier(node, 1 /* Export */)) {
        statements = append(
          statements,
          setOriginalNode(
            setTextRange(
              factory2.createExpressionStatement(
                createExportExpression(
                  node.name,
                  createRequireCall2(node)
                )
              ),
              node
            ),
            node
          )
        );
      } else {
        statements = append(
          statements,
          setOriginalNode(
            setTextRange(
              factory2.createVariableStatement(
                /*modifiers*/
                void 0,
                factory2.createVariableDeclarationList(
                  [
                    factory2.createVariableDeclaration(
                      factory2.cloneNode(node.name),
                      /*exclamationToken*/
                      void 0,
                      /*type*/
                      void 0,
                      createRequireCall2(node)
                    )
                  ],
                  /*flags*/
                  languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
                )
              ),
              node
            ),
            node
          )
        );
      }
    } else {
      if (hasSyntacticModifier(node, 1 /* Export */)) {
        statements = append(
          statements,
          setOriginalNode(
            setTextRange(
              factory2.createExpressionStatement(
                createExportExpression(factory2.getExportName(node), factory2.getLocalName(node))
              ),
              node
            ),
            node
          )
        );
      }
    }
    statements = appendExportsOfImportEqualsDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function visitExportDeclaration(node) {
    if (!node.moduleSpecifier) {
      return void 0;
    }
    const generatedName = factory2.getGeneratedNameForNode(node);
    if (node.exportClause && isNamedExports(node.exportClause)) {
      const statements = [];
      if (moduleKind !== 2 /* AMD */) {
        statements.push(
          setOriginalNode(
            setTextRange(
              factory2.createVariableStatement(
                /*modifiers*/
                void 0,
                factory2.createVariableDeclarationList([
                  factory2.createVariableDeclaration(
                    generatedName,
                    /*exclamationToken*/
                    void 0,
                    /*type*/
                    void 0,
                    createRequireCall2(node)
                  )
                ])
              ),
              /*location*/
              node
            ),
            /* original */
            node
          )
        );
      }
      for (const specifier of node.exportClause.elements) {
        if (languageVersion === 0 /* ES3 */) {
          statements.push(
            setOriginalNode(
              setTextRange(
                factory2.createExpressionStatement(
                  emitHelpers().createCreateBindingHelper(generatedName, factory2.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory2.createStringLiteralFromNode(specifier.name) : void 0)
                ),
                specifier
              ),
              specifier
            )
          );
        } else {
          const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) && idText(specifier.propertyName || specifier.name) === "default";
          const exportedValue = factory2.createPropertyAccessExpression(
            exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName,
            specifier.propertyName || specifier.name
          );
          statements.push(
            setOriginalNode(
              setTextRange(
                factory2.createExpressionStatement(
                  createExportExpression(
                    factory2.getExportName(specifier),
                    exportedValue,
                    /*location*/
                    void 0,
                    /*liveBinding*/
                    true
                  )
                ),
                specifier
              ),
              specifier
            )
          );
        }
      }
      return singleOrMany(statements);
    } else if (node.exportClause) {
      const statements = [];
      statements.push(
        setOriginalNode(
          setTextRange(
            factory2.createExpressionStatement(
              createExportExpression(
                factory2.cloneNode(node.exportClause.name),
                getHelperExpressionForExport(node, moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : factory2.createIdentifier(idText(node.exportClause.name)))
              )
            ),
            node
          ),
          node
        )
      );
      return singleOrMany(statements);
    } else {
      return setOriginalNode(
        setTextRange(
          factory2.createExpressionStatement(
            emitHelpers().createExportStarHelper(moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : generatedName)
          ),
          node
        ),
        node
      );
    }
  }
  function visitExportAssignment(node) {
    if (node.isExportEquals) {
      return void 0;
    }
    return createExportStatement(
      factory2.createIdentifier("default"),
      visitNode(node.expression, visitor, isExpression),
      /*location*/
      node,
      /*allowComments*/
      true
    );
  }
  function visitFunctionDeclaration(node) {
    let statements;
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      statements = append(
        statements,
        setOriginalNode(
          setTextRange(
            factory2.createFunctionDeclaration(
              visitNodes2(node.modifiers, modifierVisitor, isModifier),
              node.asteriskToken,
              factory2.getDeclarationName(
                node,
                /*allowComments*/
                true,
                /*allowSourceMaps*/
                true
              ),
              /*typeParameters*/
              void 0,
              visitNodes2(node.parameters, visitor, isParameter),
              /*type*/
              void 0,
              visitEachChild(node.body, visitor, context)
            ),
            /*location*/
            node
          ),
          /*original*/
          node
        )
      );
    } else {
      statements = append(statements, visitEachChild(node, visitor, context));
    }
    statements = appendExportsOfHoistedDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function visitClassDeclaration(node) {
    let statements;
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      statements = append(
        statements,
        setOriginalNode(
          setTextRange(
            factory2.createClassDeclaration(
              visitNodes2(node.modifiers, modifierVisitor, isModifierLike),
              factory2.getDeclarationName(
                node,
                /*allowComments*/
                true,
                /*allowSourceMaps*/
                true
              ),
              /*typeParameters*/
              void 0,
              visitNodes2(node.heritageClauses, visitor, isHeritageClause),
              visitNodes2(node.members, visitor, isClassElement)
            ),
            node
          ),
          node
        )
      );
    } else {
      statements = append(statements, visitEachChild(node, visitor, context));
    }
    statements = appendExportsOfHoistedDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function visitVariableStatement(node) {
    let statements;
    let variables;
    let expressions;
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      let modifiers;
      let removeCommentsOnExpressions = false;
      for (const variable of node.declarationList.declarations) {
        if (isIdentifier(variable.name) && isLocalName(variable.name)) {
          if (!modifiers) {
            modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier);
          }
          if (variable.initializer) {
            const updatedVariable = factory2.updateVariableDeclaration(
              variable,
              variable.name,
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              createExportExpression(
                variable.name,
                visitNode(variable.initializer, visitor, isExpression)
              )
            );
            variables = append(variables, updatedVariable);
          } else {
            variables = append(variables, variable);
          }
        } else if (variable.initializer) {
          if (!isBindingPattern(variable.name) && (isArrowFunction(variable.initializer) || isFunctionExpression(variable.initializer) || isClassExpression(variable.initializer))) {
            const expression = factory2.createAssignment(
              setTextRange(
                factory2.createPropertyAccessExpression(
                  factory2.createIdentifier("exports"),
                  variable.name
                ),
                /*location*/
                variable.name
              ),
              factory2.createIdentifier(getTextOfIdentifierOrLiteral(variable.name))
            );
            const updatedVariable = factory2.createVariableDeclaration(
              variable.name,
              variable.exclamationToken,
              variable.type,
              visitNode(variable.initializer, visitor, isExpression)
            );
            variables = append(variables, updatedVariable);
            expressions = append(expressions, expression);
            removeCommentsOnExpressions = true;
          } else {
            expressions = append(expressions, transformInitializedVariable(variable));
          }
        }
      }
      if (variables) {
        statements = append(statements, factory2.updateVariableStatement(node, modifiers, factory2.updateVariableDeclarationList(node.declarationList, variables)));
      }
      if (expressions) {
        const statement = setOriginalNode(setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node), node);
        if (removeCommentsOnExpressions) {
          removeAllComments(statement);
        }
        statements = append(statements, statement);
      }
    } else {
      statements = append(statements, visitEachChild(node, visitor, context));
    }
    statements = appendExportsOfVariableStatement(statements, node);
    return singleOrMany(statements);
  }
  function createAllExportExpressions(name, value, location) {
    const exportedNames = getExports(name);
    if (exportedNames) {
      let expression = isExportName(name) ? value : factory2.createAssignment(name, value);
      for (const exportName of exportedNames) {
        setEmitFlags(expression, 8 /* NoSubstitution */);
        expression = createExportExpression(
          exportName,
          expression,
          /*location*/
          location
        );
      }
      return expression;
    }
    return factory2.createAssignment(name, value);
  }
  function transformInitializedVariable(node) {
    if (isBindingPattern(node.name)) {
      return flattenDestructuringAssignment(
        visitNode(node, visitor, isInitializedVariable),
        visitor,
        context,
        0 /* All */,
        /*needsValue*/
        false,
        createAllExportExpressions
      );
    } else {
      return factory2.createAssignment(
        setTextRange(
          factory2.createPropertyAccessExpression(
            factory2.createIdentifier("exports"),
            node.name
          ),
          /*location*/
          node.name
        ),
        node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory2.createVoidZero()
      );
    }
  }
  function appendExportsOfImportDeclaration(statements, decl) {
    if (currentModuleInfo.exportEquals) {
      return statements;
    }
    const importClause = decl.importClause;
    if (!importClause) {
      return statements;
    }
    if (importClause.name) {
      statements = appendExportsOfDeclaration(statements, importClause);
    }
    const namedBindings = importClause.namedBindings;
    if (namedBindings) {
      switch (namedBindings.kind) {
        case 273 /* NamespaceImport */:
          statements = appendExportsOfDeclaration(statements, namedBindings);
          break;
        case 274 /* NamedImports */:
          for (const importBinding of namedBindings.elements) {
            statements = appendExportsOfDeclaration(
              statements,
              importBinding,
              /*liveBinding*/
              true
            );
          }
          break;
      }
    }
    return statements;
  }
  function appendExportsOfImportEqualsDeclaration(statements, decl) {
    if (currentModuleInfo.exportEquals) {
      return statements;
    }
    return appendExportsOfDeclaration(statements, decl);
  }
  function appendExportsOfVariableStatement(statements, node) {
    return appendExportsOfVariableDeclarationList(
      statements,
      node.declarationList,
      /*isForInOrOfInitializer*/
      false
    );
  }
  function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) {
    if (currentModuleInfo.exportEquals) {
      return statements;
    }
    for (const decl of node.declarations) {
      statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer);
    }
    return statements;
  }
  function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) {
    if (currentModuleInfo.exportEquals) {
      return statements;
    }
    if (isBindingPattern(decl.name)) {
      for (const element of decl.name.elements) {
        if (!isOmittedExpression(element)) {
          statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer);
        }
      }
    } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) {
      statements = appendExportsOfDeclaration(statements, decl);
    }
    return statements;
  }
  function appendExportsOfHoistedDeclaration(statements, decl) {
    if (currentModuleInfo.exportEquals) {
      return statements;
    }
    if (hasSyntacticModifier(decl, 1 /* Export */)) {
      const exportName = hasSyntacticModifier(decl, 1024 /* Default */) ? factory2.createIdentifier("default") : factory2.getDeclarationName(decl);
      statements = appendExportStatement(
        statements,
        exportName,
        factory2.getLocalName(decl),
        /*location*/
        decl
      );
    }
    if (decl.name) {
      statements = appendExportsOfDeclaration(statements, decl);
    }
    return statements;
  }
  function appendExportsOfDeclaration(statements, decl, liveBinding) {
    const name = factory2.getDeclarationName(decl);
    const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(idText(name));
    if (exportSpecifiers) {
      for (const exportSpecifier of exportSpecifiers) {
        statements = appendExportStatement(
          statements,
          exportSpecifier.name,
          name,
          /*location*/
          exportSpecifier.name,
          /*allowComments*/
          void 0,
          liveBinding
        );
      }
    }
    return statements;
  }
  function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
    statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
    return statements;
  }
  function createUnderscoreUnderscoreESModule() {
    let statement;
    if (languageVersion === 0 /* ES3 */) {
      statement = factory2.createExpressionStatement(
        createExportExpression(
          factory2.createIdentifier("__esModule"),
          factory2.createTrue()
        )
      );
    } else {
      statement = factory2.createExpressionStatement(
        factory2.createCallExpression(
          factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"),
          /*typeArguments*/
          void 0,
          [
            factory2.createIdentifier("exports"),
            factory2.createStringLiteral("__esModule"),
            factory2.createObjectLiteralExpression([
              factory2.createPropertyAssignment("value", factory2.createTrue())
            ])
          ]
        )
      );
    }
    setEmitFlags(statement, 2097152 /* CustomPrologue */);
    return statement;
  }
  function createExportStatement(name, value, location, allowComments, liveBinding) {
    const statement = setTextRange(factory2.createExpressionStatement(createExportExpression(
      name,
      value,
      /*location*/
      void 0,
      liveBinding
    )), location);
    startOnNewLine(statement);
    if (!allowComments) {
      setEmitFlags(statement, 3072 /* NoComments */);
    }
    return statement;
  }
  function createExportExpression(name, value, location, liveBinding) {
    return setTextRange(
      liveBinding && languageVersion !== 0 /* ES3 */ ? factory2.createCallExpression(
        factory2.createPropertyAccessExpression(
          factory2.createIdentifier("Object"),
          "defineProperty"
        ),
        /*typeArguments*/
        void 0,
        [
          factory2.createIdentifier("exports"),
          factory2.createStringLiteralFromNode(name),
          factory2.createObjectLiteralExpression([
            factory2.createPropertyAssignment("enumerable", factory2.createTrue()),
            factory2.createPropertyAssignment("get", factory2.createFunctionExpression(
              /*modifiers*/
              void 0,
              /*asteriskToken*/
              void 0,
              /*name*/
              void 0,
              /*typeParameters*/
              void 0,
              /*parameters*/
              [],
              /*type*/
              void 0,
              factory2.createBlock([factory2.createReturnStatement(value)])
            ))
          ])
        ]
      ) : factory2.createAssignment(
        factory2.createPropertyAccessExpression(
          factory2.createIdentifier("exports"),
          factory2.cloneNode(name)
        ),
        value
      ),
      location
    );
  }
  function modifierVisitor(node) {
    switch (node.kind) {
      case 95 /* ExportKeyword */:
      case 90 /* DefaultKeyword */:
        return void 0;
    }
    return node;
  }
  function onEmitNode(hint, node, emitCallback) {
    if (node.kind === 311 /* SourceFile */) {
      currentSourceFile = node;
      currentModuleInfo = moduleInfoMap[getOriginalNodeId(currentSourceFile)];
      previousOnEmitNode(hint, node, emitCallback);
      currentSourceFile = void 0;
      currentModuleInfo = void 0;
    } else {
      previousOnEmitNode(hint, node, emitCallback);
    }
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (node.id && noSubstitution[node.id]) {
      return node;
    }
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    } else if (isShorthandPropertyAssignment(node)) {
      return substituteShorthandPropertyAssignment(node);
    }
    return node;
  }
  function substituteShorthandPropertyAssignment(node) {
    const name = node.name;
    const exportedOrImportedName = substituteExpressionIdentifier(name);
    if (exportedOrImportedName !== name) {
      if (node.objectAssignmentInitializer) {
        const initializer = factory2.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
        return setTextRange(factory2.createPropertyAssignment(name, initializer), node);
      }
      return setTextRange(factory2.createPropertyAssignment(name, exportedOrImportedName), node);
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return substituteExpressionIdentifier(node);
      case 212 /* CallExpression */:
        return substituteCallExpression(node);
      case 214 /* TaggedTemplateExpression */:
        return substituteTaggedTemplateExpression(node);
      case 225 /* BinaryExpression */:
        return substituteBinaryExpression(node);
    }
    return node;
  }
  function substituteCallExpression(node) {
    if (isIdentifier(node.expression)) {
      const expression = substituteExpressionIdentifier(node.expression);
      noSubstitution[getNodeId(expression)] = true;
      if (!isIdentifier(expression) && !(getEmitFlags(node.expression) & 8192 /* HelperName */)) {
        return addInternalEmitFlags(
          factory2.updateCallExpression(
            node,
            expression,
            /*typeArguments*/
            void 0,
            node.arguments
          ),
          16 /* IndirectCall */
        );
      }
    }
    return node;
  }
  function substituteTaggedTemplateExpression(node) {
    if (isIdentifier(node.tag)) {
      const tag = substituteExpressionIdentifier(node.tag);
      noSubstitution[getNodeId(tag)] = true;
      if (!isIdentifier(tag) && !(getEmitFlags(node.tag) & 8192 /* HelperName */)) {
        return addInternalEmitFlags(
          factory2.updateTaggedTemplateExpression(
            node,
            tag,
            /*typeArguments*/
            void 0,
            node.template
          ),
          16 /* IndirectCall */
        );
      }
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    var _a, _b;
    if (getEmitFlags(node) & 8192 /* HelperName */) {
      const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
      if (externalHelpersModuleName) {
        return factory2.createPropertyAccessExpression(externalHelpersModuleName, node);
      }
      return node;
    } else if (!(isGeneratedIdentifier(node) && !(node.emitNode.autoGenerate.flags & 64 /* AllowNameSubstitution */)) && !isLocalName(node)) {
      const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node));
      if (exportContainer && exportContainer.kind === 311 /* SourceFile */) {
        return setTextRange(
          factory2.createPropertyAccessExpression(
            factory2.createIdentifier("exports"),
            factory2.cloneNode(node)
          ),
          /*location*/
          node
        );
      }
      const importDeclaration = resolver.getReferencedImportDeclaration(node);
      if (importDeclaration) {
        if (isImportClause(importDeclaration)) {
          return setTextRange(
            factory2.createPropertyAccessExpression(
              factory2.getGeneratedNameForNode(importDeclaration.parent),
              factory2.createIdentifier("default")
            ),
            /*location*/
            node
          );
        } else if (isImportSpecifier(importDeclaration)) {
          const name = importDeclaration.propertyName || importDeclaration.name;
          return setTextRange(
            factory2.createPropertyAccessExpression(
              factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration),
              factory2.cloneNode(name)
            ),
            /*location*/
            node
          );
        }
      }
    }
    return node;
  }
  function substituteBinaryExpression(node) {
    if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) {
      const exportedNames = getExports(node.left);
      if (exportedNames) {
        let expression = node;
        for (const exportName of exportedNames) {
          noSubstitution[getNodeId(expression)] = true;
          expression = createExportExpression(
            exportName,
            expression,
            /*location*/
            node
          );
        }
        return expression;
      }
    }
    return node;
  }
  function getExports(name) {
    if (!isGeneratedIdentifier(name)) {
      const importDeclaration = resolver.getReferencedImportDeclaration(name);
      if (importDeclaration) {
        return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)];
      }
      const bindingsSet = /* @__PURE__ */ new Set();
      const declarations = resolver.getReferencedValueDeclarations(name);
      if (declarations) {
        for (const declaration of declarations) {
          const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)];
          if (bindings) {
            for (const binding of bindings) {
              bindingsSet.add(binding);
            }
          }
        }
        if (bindingsSet.size) {
          return arrayFrom(bindingsSet);
        }
      }
    }
  }
}
var dynamicImportUMDHelper = {
  name: "typescript:dynamicimport-sync-require",
  scoped: true,
  text: `
            var __syncRequire = typeof module === "object" && typeof module.exports === "object";`
};

// src/compiler/transformers/module/system.ts
function transformSystemModule(context) {
  const {
    factory: factory2,
    startLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const compilerOptions = context.getCompilerOptions();
  const resolver = context.getEmitResolver();
  const host = context.getEmitHost();
  const previousOnSubstituteNode = context.onSubstituteNode;
  const previousOnEmitNode = context.onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.enableSubstitution(80 /* Identifier */);
  context.enableSubstitution(303 /* ShorthandPropertyAssignment */);
  context.enableSubstitution(225 /* BinaryExpression */);
  context.enableSubstitution(235 /* MetaProperty */);
  context.enableEmitNotification(311 /* SourceFile */);
  const moduleInfoMap = [];
  const exportFunctionsMap = [];
  const noSubstitutionMap = [];
  const contextObjectMap = [];
  let currentSourceFile;
  let moduleInfo;
  let exportFunction;
  let contextObject;
  let hoistedStatements;
  let enclosingBlockScopedContainer;
  let noSubstitution;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 8388608 /* ContainsDynamicImport */)) {
      return node;
    }
    const id = getOriginalNodeId(node);
    currentSourceFile = node;
    enclosingBlockScopedContainer = node;
    moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node, resolver, compilerOptions);
    exportFunction = factory2.createUniqueName("exports");
    exportFunctionsMap[id] = exportFunction;
    contextObject = contextObjectMap[id] = factory2.createUniqueName("context");
    const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
    const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
    const moduleBodyFunction = factory2.createFunctionExpression(
      /*modifiers*/
      void 0,
      /*asteriskToken*/
      void 0,
      /*name*/
      void 0,
      /*typeParameters*/
      void 0,
      [
        factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          exportFunction
        ),
        factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          contextObject
        )
      ],
      /*type*/
      void 0,
      moduleBodyBlock
    );
    const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions);
    const dependencies = factory2.createArrayLiteralExpression(map(dependencyGroups, (dependencyGroup) => dependencyGroup.name));
    const updated = setEmitFlags(
      factory2.updateSourceFile(
        node,
        setTextRange(
          factory2.createNodeArray([
            factory2.createExpressionStatement(
              factory2.createCallExpression(
                factory2.createPropertyAccessExpression(factory2.createIdentifier("System"), "register"),
                /*typeArguments*/
                void 0,
                moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction]
              )
            )
          ]),
          node.statements
        )
      ),
      2048 /* NoTrailingComments */
    );
    if (!outFile(compilerOptions)) {
      moveEmitHelpers(updated, moduleBodyBlock, (helper) => !helper.scoped);
    }
    if (noSubstitution) {
      noSubstitutionMap[id] = noSubstitution;
      noSubstitution = void 0;
    }
    currentSourceFile = void 0;
    moduleInfo = void 0;
    exportFunction = void 0;
    contextObject = void 0;
    hoistedStatements = void 0;
    enclosingBlockScopedContainer = void 0;
    return updated;
  }
  function collectDependencyGroups(externalImports) {
    const groupIndices = /* @__PURE__ */ new Map();
    const dependencyGroups = [];
    for (const externalImport of externalImports) {
      const externalModuleName = getExternalModuleNameLiteral(factory2, externalImport, currentSourceFile, host, resolver, compilerOptions);
      if (externalModuleName) {
        const text = externalModuleName.text;
        const groupIndex = groupIndices.get(text);
        if (groupIndex !== void 0) {
          dependencyGroups[groupIndex].externalImports.push(externalImport);
        } else {
          groupIndices.set(text, dependencyGroups.length);
          dependencyGroups.push({
            name: externalModuleName,
            externalImports: [externalImport]
          });
        }
      }
    }
    return dependencyGroups;
  }
  function createSystemModuleBody(node, dependencyGroups) {
    const statements = [];
    startLexicalEnvironment();
    const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || !compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile);
    const statementOffset = factory2.copyPrologue(node.statements, statements, ensureUseStrict, topLevelVisitor);
    statements.push(
      factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList([
          factory2.createVariableDeclaration(
            "__moduleName",
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            factory2.createLogicalAnd(
              contextObject,
              factory2.createPropertyAccessExpression(contextObject, "id")
            )
          )
        ])
      )
    );
    visitNode(moduleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement);
    const executeStatements = visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset);
    addRange(statements, hoistedStatements);
    insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
    const exportStarFunction = addExportStarIfNeeded(statements);
    const modifiers = node.transformFlags & 2097152 /* ContainsAwait */ ? factory2.createModifiersFromModifierFlags(512 /* Async */) : void 0;
    const moduleObject = factory2.createObjectLiteralExpression(
      [
        factory2.createPropertyAssignment(
          "setters",
          createSettersArray(exportStarFunction, dependencyGroups)
        ),
        factory2.createPropertyAssignment(
          "execute",
          factory2.createFunctionExpression(
            modifiers,
            /*asteriskToken*/
            void 0,
            /*name*/
            void 0,
            /*typeParameters*/
            void 0,
            /*parameters*/
            [],
            /*type*/
            void 0,
            factory2.createBlock(
              executeStatements,
              /*multiLine*/
              true
            )
          )
        )
      ],
      /*multiLine*/
      true
    );
    statements.push(factory2.createReturnStatement(moduleObject));
    return factory2.createBlock(
      statements,
      /*multiLine*/
      true
    );
  }
  function addExportStarIfNeeded(statements) {
    if (!moduleInfo.hasExportStarsToExportValues) {
      return;
    }
    if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
      let hasExportDeclarationWithExportClause = false;
      for (const externalImport of moduleInfo.externalImports) {
        if (externalImport.kind === 277 /* ExportDeclaration */ && externalImport.exportClause) {
          hasExportDeclarationWithExportClause = true;
          break;
        }
      }
      if (!hasExportDeclarationWithExportClause) {
        const exportStarFunction2 = createExportStarFunction(
          /*localNames*/
          void 0
        );
        statements.push(exportStarFunction2);
        return exportStarFunction2.name;
      }
    }
    const exportedNames = [];
    if (moduleInfo.exportedNames) {
      for (const exportedLocalName of moduleInfo.exportedNames) {
        if (exportedLocalName.escapedText === "default") {
          continue;
        }
        exportedNames.push(
          factory2.createPropertyAssignment(
            factory2.createStringLiteralFromNode(exportedLocalName),
            factory2.createTrue()
          )
        );
      }
    }
    const exportedNamesStorageRef = factory2.createUniqueName("exportedNames");
    statements.push(
      factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList([
          factory2.createVariableDeclaration(
            exportedNamesStorageRef,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            factory2.createObjectLiteralExpression(
              exportedNames,
              /*multiLine*/
              true
            )
          )
        ])
      )
    );
    const exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
    statements.push(exportStarFunction);
    return exportStarFunction.name;
  }
  function createExportStarFunction(localNames) {
    const exportStarFunction = factory2.createUniqueName("exportStar");
    const m = factory2.createIdentifier("m");
    const n = factory2.createIdentifier("n");
    const exports = factory2.createIdentifier("exports");
    let condition = factory2.createStrictInequality(n, factory2.createStringLiteral("default"));
    if (localNames) {
      condition = factory2.createLogicalAnd(
        condition,
        factory2.createLogicalNot(
          factory2.createCallExpression(
            factory2.createPropertyAccessExpression(localNames, "hasOwnProperty"),
            /*typeArguments*/
            void 0,
            [n]
          )
        )
      );
    }
    return factory2.createFunctionDeclaration(
      /*modifiers*/
      void 0,
      /*asteriskToken*/
      void 0,
      exportStarFunction,
      /*typeParameters*/
      void 0,
      [factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        m
      )],
      /*type*/
      void 0,
      factory2.createBlock(
        [
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList([
              factory2.createVariableDeclaration(
                exports,
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                factory2.createObjectLiteralExpression([])
              )
            ])
          ),
          factory2.createForInStatement(
            factory2.createVariableDeclarationList([
              factory2.createVariableDeclaration(n)
            ]),
            m,
            factory2.createBlock([
              setEmitFlags(
                factory2.createIfStatement(
                  condition,
                  factory2.createExpressionStatement(
                    factory2.createAssignment(
                      factory2.createElementAccessExpression(exports, n),
                      factory2.createElementAccessExpression(m, n)
                    )
                  )
                ),
                1 /* SingleLine */
              )
            ])
          ),
          factory2.createExpressionStatement(
            factory2.createCallExpression(
              exportFunction,
              /*typeArguments*/
              void 0,
              [exports]
            )
          )
        ],
        /*multiLine*/
        true
      )
    );
  }
  function createSettersArray(exportStarFunction, dependencyGroups) {
    const setters = [];
    for (const group2 of dependencyGroups) {
      const localName = forEach(group2.externalImports, (i) => getLocalNameForExternalImport(factory2, i, currentSourceFile));
      const parameterName = localName ? factory2.getGeneratedNameForNode(localName) : factory2.createUniqueName("");
      const statements = [];
      for (const entry of group2.externalImports) {
        const importVariableName = getLocalNameForExternalImport(factory2, entry, currentSourceFile);
        switch (entry.kind) {
          case 271 /* ImportDeclaration */:
            if (!entry.importClause) {
              break;
            }
          case 270 /* ImportEqualsDeclaration */:
            Debug.assert(importVariableName !== void 0);
            statements.push(
              factory2.createExpressionStatement(
                factory2.createAssignment(importVariableName, parameterName)
              )
            );
            if (hasSyntacticModifier(entry, 1 /* Export */)) {
              statements.push(
                factory2.createExpressionStatement(
                  factory2.createCallExpression(
                    exportFunction,
                    /*typeArguments*/
                    void 0,
                    [
                      factory2.createStringLiteral(idText(importVariableName)),
                      parameterName
                    ]
                  )
                )
              );
            }
            break;
          case 277 /* ExportDeclaration */:
            Debug.assert(importVariableName !== void 0);
            if (entry.exportClause) {
              if (isNamedExports(entry.exportClause)) {
                const properties = [];
                for (const e of entry.exportClause.elements) {
                  properties.push(
                    factory2.createPropertyAssignment(
                      factory2.createStringLiteral(idText(e.name)),
                      factory2.createElementAccessExpression(
                        parameterName,
                        factory2.createStringLiteral(idText(e.propertyName || e.name))
                      )
                    )
                  );
                }
                statements.push(
                  factory2.createExpressionStatement(
                    factory2.createCallExpression(
                      exportFunction,
                      /*typeArguments*/
                      void 0,
                      [factory2.createObjectLiteralExpression(
                        properties,
                        /*multiLine*/
                        true
                      )]
                    )
                  )
                );
              } else {
                statements.push(
                  factory2.createExpressionStatement(
                    factory2.createCallExpression(
                      exportFunction,
                      /*typeArguments*/
                      void 0,
                      [
                        factory2.createStringLiteral(idText(entry.exportClause.name)),
                        parameterName
                      ]
                    )
                  )
                );
              }
            } else {
              statements.push(
                factory2.createExpressionStatement(
                  factory2.createCallExpression(
                    exportStarFunction,
                    /*typeArguments*/
                    void 0,
                    [parameterName]
                  )
                )
              );
            }
            break;
        }
      }
      setters.push(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          /*asteriskToken*/
          void 0,
          /*name*/
          void 0,
          /*typeParameters*/
          void 0,
          [factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            parameterName
          )],
          /*type*/
          void 0,
          factory2.createBlock(
            statements,
            /*multiLine*/
            true
          )
        )
      );
    }
    return factory2.createArrayLiteralExpression(
      setters,
      /*multiLine*/
      true
    );
  }
  function topLevelVisitor(node) {
    switch (node.kind) {
      case 271 /* ImportDeclaration */:
        return visitImportDeclaration(node);
      case 270 /* ImportEqualsDeclaration */:
        return visitImportEqualsDeclaration(node);
      case 277 /* ExportDeclaration */:
        return visitExportDeclaration(node);
      case 276 /* ExportAssignment */:
        return visitExportAssignment(node);
      default:
        return topLevelNestedVisitor(node);
    }
  }
  function visitImportDeclaration(node) {
    let statements;
    if (node.importClause) {
      hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile));
    }
    return singleOrMany(appendExportsOfImportDeclaration(statements, node));
  }
  function visitExportDeclaration(node) {
    Debug.assertIsDefined(node);
    return void 0;
  }
  function visitImportEqualsDeclaration(node) {
    Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
    let statements;
    hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile));
    return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node));
  }
  function visitExportAssignment(node) {
    if (node.isExportEquals) {
      return void 0;
    }
    const expression = visitNode(node.expression, visitor, isExpression);
    return createExportStatement(
      factory2.createIdentifier("default"),
      expression,
      /*allowComments*/
      true
    );
  }
  function visitFunctionDeclaration(node) {
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      hoistedStatements = append(
        hoistedStatements,
        factory2.updateFunctionDeclaration(
          node,
          visitNodes2(node.modifiers, modifierVisitor, isModifierLike),
          node.asteriskToken,
          factory2.getDeclarationName(
            node,
            /*allowComments*/
            true,
            /*allowSourceMaps*/
            true
          ),
          /*typeParameters*/
          void 0,
          visitNodes2(node.parameters, visitor, isParameter),
          /*type*/
          void 0,
          visitNode(node.body, visitor, isBlock)
        )
      );
    } else {
      hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context));
    }
    hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
    return void 0;
  }
  function visitClassDeclaration(node) {
    let statements;
    const name = factory2.getLocalName(node);
    hoistVariableDeclaration(name);
    statements = append(
      statements,
      setTextRange(
        factory2.createExpressionStatement(
          factory2.createAssignment(
            name,
            setTextRange(
              factory2.createClassExpression(
                visitNodes2(node.modifiers, modifierVisitor, isModifierLike),
                node.name,
                /*typeParameters*/
                void 0,
                visitNodes2(node.heritageClauses, visitor, isHeritageClause),
                visitNodes2(node.members, visitor, isClassElement)
              ),
              node
            )
          )
        ),
        node
      )
    );
    statements = appendExportsOfHoistedDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function visitVariableStatement(node) {
    if (!shouldHoistVariableDeclarationList(node.declarationList)) {
      return visitNode(node, visitor, isStatement);
    }
    let expressions;
    const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */);
    for (const variable of node.declarationList.declarations) {
      if (variable.initializer) {
        expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration));
      } else {
        hoistBindingElement(variable);
      }
    }
    let statements;
    if (expressions) {
      statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node));
    }
    statements = appendExportsOfVariableStatement(
      statements,
      node,
      /*exportSelf*/
      false
    );
    return singleOrMany(statements);
  }
  function hoistBindingElement(node) {
    if (isBindingPattern(node.name)) {
      for (const element of node.name.elements) {
        if (!isOmittedExpression(element)) {
          hoistBindingElement(element);
        }
      }
    } else {
      hoistVariableDeclaration(factory2.cloneNode(node.name));
    }
  }
  function shouldHoistVariableDeclarationList(node) {
    return (getEmitFlags(node) & 4194304 /* NoHoisting */) === 0 && (enclosingBlockScopedContainer.kind === 311 /* SourceFile */ || (getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
  }
  function transformInitializedVariable(node, isExportedDeclaration) {
    const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
    return isBindingPattern(node.name) ? flattenDestructuringAssignment(
      node,
      visitor,
      context,
      0 /* All */,
      /*needsValue*/
      false,
      createAssignment
    ) : node.initializer ? createAssignment(node.name, visitNode(node.initializer, visitor, isExpression)) : node.name;
  }
  function createExportedVariableAssignment(name, value, location) {
    return createVariableAssignment(
      name,
      value,
      location,
      /*isExportedDeclaration*/
      true
    );
  }
  function createNonExportedVariableAssignment(name, value, location) {
    return createVariableAssignment(
      name,
      value,
      location,
      /*isExportedDeclaration*/
      false
    );
  }
  function createVariableAssignment(name, value, location, isExportedDeclaration) {
    hoistVariableDeclaration(factory2.cloneNode(name));
    return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value), location));
  }
  function appendExportsOfImportDeclaration(statements, decl) {
    if (moduleInfo.exportEquals) {
      return statements;
    }
    const importClause = decl.importClause;
    if (!importClause) {
      return statements;
    }
    if (importClause.name) {
      statements = appendExportsOfDeclaration(statements, importClause);
    }
    const namedBindings = importClause.namedBindings;
    if (namedBindings) {
      switch (namedBindings.kind) {
        case 273 /* NamespaceImport */:
          statements = appendExportsOfDeclaration(statements, namedBindings);
          break;
        case 274 /* NamedImports */:
          for (const importBinding of namedBindings.elements) {
            statements = appendExportsOfDeclaration(statements, importBinding);
          }
          break;
      }
    }
    return statements;
  }
  function appendExportsOfImportEqualsDeclaration(statements, decl) {
    if (moduleInfo.exportEquals) {
      return statements;
    }
    return appendExportsOfDeclaration(statements, decl);
  }
  function appendExportsOfVariableStatement(statements, node, exportSelf) {
    if (moduleInfo.exportEquals) {
      return statements;
    }
    for (const decl of node.declarationList.declarations) {
      if (decl.initializer || exportSelf) {
        statements = appendExportsOfBindingElement(statements, decl, exportSelf);
      }
    }
    return statements;
  }
  function appendExportsOfBindingElement(statements, decl, exportSelf) {
    if (moduleInfo.exportEquals) {
      return statements;
    }
    if (isBindingPattern(decl.name)) {
      for (const element of decl.name.elements) {
        if (!isOmittedExpression(element)) {
          statements = appendExportsOfBindingElement(statements, element, exportSelf);
        }
      }
    } else if (!isGeneratedIdentifier(decl.name)) {
      let excludeName;
      if (exportSelf) {
        statements = appendExportStatement(statements, decl.name, factory2.getLocalName(decl));
        excludeName = idText(decl.name);
      }
      statements = appendExportsOfDeclaration(statements, decl, excludeName);
    }
    return statements;
  }
  function appendExportsOfHoistedDeclaration(statements, decl) {
    if (moduleInfo.exportEquals) {
      return statements;
    }
    let excludeName;
    if (hasSyntacticModifier(decl, 1 /* Export */)) {
      const exportName = hasSyntacticModifier(decl, 1024 /* Default */) ? factory2.createStringLiteral("default") : decl.name;
      statements = appendExportStatement(statements, exportName, factory2.getLocalName(decl));
      excludeName = getTextOfIdentifierOrLiteral(exportName);
    }
    if (decl.name) {
      statements = appendExportsOfDeclaration(statements, decl, excludeName);
    }
    return statements;
  }
  function appendExportsOfDeclaration(statements, decl, excludeName) {
    if (moduleInfo.exportEquals) {
      return statements;
    }
    const name = factory2.getDeclarationName(decl);
    const exportSpecifiers = moduleInfo.exportSpecifiers.get(idText(name));
    if (exportSpecifiers) {
      for (const exportSpecifier of exportSpecifiers) {
        if (exportSpecifier.name.escapedText !== excludeName) {
          statements = appendExportStatement(statements, exportSpecifier.name, name);
        }
      }
    }
    return statements;
  }
  function appendExportStatement(statements, exportName, expression, allowComments) {
    statements = append(statements, createExportStatement(exportName, expression, allowComments));
    return statements;
  }
  function createExportStatement(name, value, allowComments) {
    const statement = factory2.createExpressionStatement(createExportExpression(name, value));
    startOnNewLine(statement);
    if (!allowComments) {
      setEmitFlags(statement, 3072 /* NoComments */);
    }
    return statement;
  }
  function createExportExpression(name, value) {
    const exportName = isIdentifier(name) ? factory2.createStringLiteralFromNode(name) : name;
    setEmitFlags(value, getEmitFlags(value) | 3072 /* NoComments */);
    return setCommentRange(factory2.createCallExpression(
      exportFunction,
      /*typeArguments*/
      void 0,
      [exportName, value]
    ), value);
  }
  function topLevelNestedVisitor(node) {
    switch (node.kind) {
      case 242 /* VariableStatement */:
        return visitVariableStatement(node);
      case 261 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 262 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 247 /* ForStatement */:
        return visitForStatement(
          node,
          /*isTopLevel*/
          true
        );
      case 248 /* ForInStatement */:
        return visitForInStatement(node);
      case 249 /* ForOfStatement */:
        return visitForOfStatement(node);
      case 245 /* DoStatement */:
        return visitDoStatement(node);
      case 246 /* WhileStatement */:
        return visitWhileStatement(node);
      case 255 /* LabeledStatement */:
        return visitLabeledStatement(node);
      case 253 /* WithStatement */:
        return visitWithStatement(node);
      case 244 /* IfStatement */:
        return visitIfStatement(node);
      case 254 /* SwitchStatement */:
        return visitSwitchStatement(node);
      case 268 /* CaseBlock */:
        return visitCaseBlock(node);
      case 295 /* CaseClause */:
        return visitCaseClause(node);
      case 296 /* DefaultClause */:
        return visitDefaultClause(node);
      case 257 /* TryStatement */:
        return visitTryStatement(node);
      case 298 /* CatchClause */:
        return visitCatchClause(node);
      case 240 /* Block */:
        return visitBlock(node);
      default:
        return visitor(node);
    }
  }
  function visitForStatement(node, isTopLevel) {
    const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
    enclosingBlockScopedContainer = node;
    node = factory2.updateForStatement(
      node,
      visitNode(node.initializer, isTopLevel ? visitForInitializer : discardedValueVisitor, isForInitializer),
      visitNode(node.condition, visitor, isExpression),
      visitNode(node.incrementor, discardedValueVisitor, isExpression),
      visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context)
    );
    enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
    return node;
  }
  function visitForInStatement(node) {
    const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
    enclosingBlockScopedContainer = node;
    node = factory2.updateForInStatement(
      node,
      visitForInitializer(node.initializer),
      visitNode(node.expression, visitor, isExpression),
      visitIterationBody(node.statement, topLevelNestedVisitor, context)
    );
    enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
    return node;
  }
  function visitForOfStatement(node) {
    const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
    enclosingBlockScopedContainer = node;
    node = factory2.updateForOfStatement(
      node,
      node.awaitModifier,
      visitForInitializer(node.initializer),
      visitNode(node.expression, visitor, isExpression),
      visitIterationBody(node.statement, topLevelNestedVisitor, context)
    );
    enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
    return node;
  }
  function shouldHoistForInitializer(node) {
    return isVariableDeclarationList(node) && shouldHoistVariableDeclarationList(node);
  }
  function visitForInitializer(node) {
    if (shouldHoistForInitializer(node)) {
      let expressions;
      for (const variable of node.declarations) {
        expressions = append(expressions, transformInitializedVariable(
          variable,
          /*isExportedDeclaration*/
          false
        ));
        if (!variable.initializer) {
          hoistBindingElement(variable);
        }
      }
      return expressions ? factory2.inlineExpressions(expressions) : factory2.createOmittedExpression();
    } else {
      return visitNode(node, discardedValueVisitor, isForInitializer);
    }
  }
  function visitDoStatement(node) {
    return factory2.updateDoStatement(
      node,
      visitIterationBody(node.statement, topLevelNestedVisitor, context),
      visitNode(node.expression, visitor, isExpression)
    );
  }
  function visitWhileStatement(node) {
    return factory2.updateWhileStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      visitIterationBody(node.statement, topLevelNestedVisitor, context)
    );
  }
  function visitLabeledStatement(node) {
    return factory2.updateLabeledStatement(
      node,
      node.label,
      Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))
    );
  }
  function visitWithStatement(node) {
    return factory2.updateWithStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))
    );
  }
  function visitIfStatement(node) {
    return factory2.updateIfStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)),
      visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)
    );
  }
  function visitSwitchStatement(node) {
    return factory2.updateSwitchStatement(
      node,
      visitNode(node.expression, visitor, isExpression),
      Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock))
    );
  }
  function visitCaseBlock(node) {
    const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
    enclosingBlockScopedContainer = node;
    node = factory2.updateCaseBlock(
      node,
      visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause)
    );
    enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
    return node;
  }
  function visitCaseClause(node) {
    return factory2.updateCaseClause(
      node,
      visitNode(node.expression, visitor, isExpression),
      visitNodes2(node.statements, topLevelNestedVisitor, isStatement)
    );
  }
  function visitDefaultClause(node) {
    return visitEachChild(node, topLevelNestedVisitor, context);
  }
  function visitTryStatement(node) {
    return visitEachChild(node, topLevelNestedVisitor, context);
  }
  function visitCatchClause(node) {
    const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
    enclosingBlockScopedContainer = node;
    node = factory2.updateCatchClause(
      node,
      node.variableDeclaration,
      Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock))
    );
    enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
    return node;
  }
  function visitBlock(node) {
    const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
    enclosingBlockScopedContainer = node;
    node = visitEachChild(node, topLevelNestedVisitor, context);
    enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
    return node;
  }
  function visitorWorker(node, valueIsDiscarded) {
    if (!(node.transformFlags & (4096 /* ContainsDestructuringAssignment */ | 8388608 /* ContainsDynamicImport */ | 268435456 /* ContainsUpdateExpressionForIdentifier */))) {
      return node;
    }
    switch (node.kind) {
      case 247 /* ForStatement */:
        return visitForStatement(
          node,
          /*isTopLevel*/
          false
        );
      case 243 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 216 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node, valueIsDiscarded);
      case 359 /* PartiallyEmittedExpression */:
        return visitPartiallyEmittedExpression(node, valueIsDiscarded);
      case 225 /* BinaryExpression */:
        if (isDestructuringAssignment(node)) {
          return visitDestructuringAssignment(node, valueIsDiscarded);
        }
        break;
      case 212 /* CallExpression */:
        if (isImportCall(node)) {
          return visitImportCallExpression(node);
        }
        break;
      case 223 /* PrefixUnaryExpression */:
      case 224 /* PostfixUnaryExpression */:
        return visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitor(node) {
    return visitorWorker(
      node,
      /*valueIsDiscarded*/
      false
    );
  }
  function discardedValueVisitor(node) {
    return visitorWorker(
      node,
      /*valueIsDiscarded*/
      true
    );
  }
  function visitExpressionStatement(node) {
    return factory2.updateExpressionStatement(node, visitNode(node.expression, discardedValueVisitor, isExpression));
  }
  function visitParenthesizedExpression(node, valueIsDiscarded) {
    return factory2.updateParenthesizedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression));
  }
  function visitPartiallyEmittedExpression(node, valueIsDiscarded) {
    return factory2.updatePartiallyEmittedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression));
  }
  function visitImportCallExpression(node) {
    const externalModuleName = getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions);
    const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression);
    const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
    return factory2.createCallExpression(
      factory2.createPropertyAccessExpression(
        contextObject,
        factory2.createIdentifier("import")
      ),
      /*typeArguments*/
      void 0,
      argument ? [argument] : []
    );
  }
  function visitDestructuringAssignment(node, valueIsDiscarded) {
    if (hasExportedReferenceInDestructuringTarget(node.left)) {
      return flattenDestructuringAssignment(
        node,
        visitor,
        context,
        0 /* All */,
        !valueIsDiscarded
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function hasExportedReferenceInDestructuringTarget(node) {
    if (isAssignmentExpression(
      node,
      /*excludeCompoundAssignment*/
      true
    )) {
      return hasExportedReferenceInDestructuringTarget(node.left);
    } else if (isSpreadElement(node)) {
      return hasExportedReferenceInDestructuringTarget(node.expression);
    } else if (isObjectLiteralExpression(node)) {
      return some(node.properties, hasExportedReferenceInDestructuringTarget);
    } else if (isArrayLiteralExpression(node)) {
      return some(node.elements, hasExportedReferenceInDestructuringTarget);
    } else if (isShorthandPropertyAssignment(node)) {
      return hasExportedReferenceInDestructuringTarget(node.name);
    } else if (isPropertyAssignment(node)) {
      return hasExportedReferenceInDestructuringTarget(node.initializer);
    } else if (isIdentifier(node)) {
      const container = resolver.getReferencedExportContainer(node);
      return container !== void 0 && container.kind === 311 /* SourceFile */;
    } else {
      return false;
    }
  }
  function visitPrefixOrPostfixUnaryExpression(node, valueIsDiscarded) {
    if ((node.operator === 46 /* PlusPlusToken */ || node.operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) && !isDeclarationNameOfEnumOrNamespace(node.operand)) {
      const exportedNames = getExports(node.operand);
      if (exportedNames) {
        let temp;
        let expression = visitNode(node.operand, visitor, isExpression);
        if (isPrefixUnaryExpression(node)) {
          expression = factory2.updatePrefixUnaryExpression(node, expression);
        } else {
          expression = factory2.updatePostfixUnaryExpression(node, expression);
          if (!valueIsDiscarded) {
            temp = factory2.createTempVariable(hoistVariableDeclaration);
            expression = factory2.createAssignment(temp, expression);
            setTextRange(expression, node);
          }
          expression = factory2.createComma(expression, factory2.cloneNode(node.operand));
          setTextRange(expression, node);
        }
        for (const exportName of exportedNames) {
          expression = createExportExpression(exportName, preventSubstitution(expression));
        }
        if (temp) {
          expression = factory2.createComma(expression, temp);
          setTextRange(expression, node);
        }
        return expression;
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function modifierVisitor(node) {
    switch (node.kind) {
      case 95 /* ExportKeyword */:
      case 90 /* DefaultKeyword */:
        return void 0;
    }
    return node;
  }
  function onEmitNode(hint, node, emitCallback) {
    if (node.kind === 311 /* SourceFile */) {
      const id = getOriginalNodeId(node);
      currentSourceFile = node;
      moduleInfo = moduleInfoMap[id];
      exportFunction = exportFunctionsMap[id];
      noSubstitution = noSubstitutionMap[id];
      contextObject = contextObjectMap[id];
      if (noSubstitution) {
        delete noSubstitutionMap[id];
      }
      previousOnEmitNode(hint, node, emitCallback);
      currentSourceFile = void 0;
      moduleInfo = void 0;
      exportFunction = void 0;
      contextObject = void 0;
      noSubstitution = void 0;
    } else {
      previousOnEmitNode(hint, node, emitCallback);
    }
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (isSubstitutionPrevented(node)) {
      return node;
    }
    if (hint === 1 /* Expression */) {
      return substituteExpression(node);
    } else if (hint === 4 /* Unspecified */) {
      return substituteUnspecified(node);
    }
    return node;
  }
  function substituteUnspecified(node) {
    switch (node.kind) {
      case 303 /* ShorthandPropertyAssignment */:
        return substituteShorthandPropertyAssignment(node);
    }
    return node;
  }
  function substituteShorthandPropertyAssignment(node) {
    var _a, _b;
    const name = node.name;
    if (!isGeneratedIdentifier(name) && !isLocalName(name)) {
      const importDeclaration = resolver.getReferencedImportDeclaration(name);
      if (importDeclaration) {
        if (isImportClause(importDeclaration)) {
          return setTextRange(
            factory2.createPropertyAssignment(
              factory2.cloneNode(name),
              factory2.createPropertyAccessExpression(
                factory2.getGeneratedNameForNode(importDeclaration.parent),
                factory2.createIdentifier("default")
              )
            ),
            /*location*/
            node
          );
        } else if (isImportSpecifier(importDeclaration)) {
          return setTextRange(
            factory2.createPropertyAssignment(
              factory2.cloneNode(name),
              factory2.createPropertyAccessExpression(
                factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration),
                factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name)
              )
            ),
            /*location*/
            node
          );
        }
      }
    }
    return node;
  }
  function substituteExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return substituteExpressionIdentifier(node);
      case 225 /* BinaryExpression */:
        return substituteBinaryExpression(node);
      case 235 /* MetaProperty */:
        return substituteMetaProperty(node);
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    var _a, _b;
    if (getEmitFlags(node) & 8192 /* HelperName */) {
      const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
      if (externalHelpersModuleName) {
        return factory2.createPropertyAccessExpression(externalHelpersModuleName, node);
      }
      return node;
    }
    if (!isGeneratedIdentifier(node) && !isLocalName(node)) {
      const importDeclaration = resolver.getReferencedImportDeclaration(node);
      if (importDeclaration) {
        if (isImportClause(importDeclaration)) {
          return setTextRange(
            factory2.createPropertyAccessExpression(
              factory2.getGeneratedNameForNode(importDeclaration.parent),
              factory2.createIdentifier("default")
            ),
            /*location*/
            node
          );
        } else if (isImportSpecifier(importDeclaration)) {
          return setTextRange(
            factory2.createPropertyAccessExpression(
              factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration),
              factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name)
            ),
            /*location*/
            node
          );
        }
      }
    }
    return node;
  }
  function substituteBinaryExpression(node) {
    if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) {
      const exportedNames = getExports(node.left);
      if (exportedNames) {
        let expression = node;
        for (const exportName of exportedNames) {
          expression = createExportExpression(exportName, preventSubstitution(expression));
        }
        return expression;
      }
    }
    return node;
  }
  function substituteMetaProperty(node) {
    if (isImportMeta(node)) {
      return factory2.createPropertyAccessExpression(contextObject, factory2.createIdentifier("meta"));
    }
    return node;
  }
  function getExports(name) {
    let exportedNames;
    const valueDeclaration = getReferencedDeclaration(name);
    if (valueDeclaration) {
      const exportContainer = resolver.getReferencedExportContainer(
        name,
        /*prefixLocals*/
        false
      );
      if (exportContainer && exportContainer.kind === 311 /* SourceFile */) {
        exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration));
      }
      exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]);
    }
    return exportedNames;
  }
  function getReferencedDeclaration(name) {
    if (!isGeneratedIdentifier(name)) {
      const importDeclaration = resolver.getReferencedImportDeclaration(name);
      if (importDeclaration)
        return importDeclaration;
      const valueDeclaration = resolver.getReferencedValueDeclaration(name);
      if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]))
        return valueDeclaration;
      const declarations = resolver.getReferencedValueDeclarations(name);
      if (declarations) {
        for (const declaration of declarations) {
          if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)]))
            return declaration;
        }
      }
      return valueDeclaration;
    }
  }
  function preventSubstitution(node) {
    if (noSubstitution === void 0)
      noSubstitution = [];
    noSubstitution[getNodeId(node)] = true;
    return node;
  }
  function isSubstitutionPrevented(node) {
    return noSubstitution && node.id && noSubstitution[node.id];
  }
}

// src/compiler/transformers/module/esnextAnd2015.ts
function transformECMAScriptModule(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers
  } = context;
  const host = context.getEmitHost();
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const previousOnEmitNode = context.onEmitNode;
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  context.enableEmitNotification(311 /* SourceFile */);
  context.enableSubstitution(80 /* Identifier */);
  let helperNameSubstitutions;
  let currentSourceFile;
  let importRequireStatements;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    if (isExternalModule(node) || getIsolatedModules(compilerOptions)) {
      currentSourceFile = node;
      importRequireStatements = void 0;
      let result = updateExternalModule(node);
      currentSourceFile = void 0;
      if (importRequireStatements) {
        result = factory2.updateSourceFile(
          result,
          setTextRange(factory2.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements)
        );
      }
      if (!isExternalModule(node) || some(result.statements, isExternalModuleIndicator)) {
        return result;
      }
      return factory2.updateSourceFile(
        result,
        setTextRange(factory2.createNodeArray([...result.statements, createEmptyExports(factory2)]), result.statements)
      );
    }
    return node;
  }
  function updateExternalModule(node) {
    const externalHelpersImportDeclaration = createExternalHelpersImportDeclarationIfNeeded(factory2, emitHelpers(), node, compilerOptions);
    if (externalHelpersImportDeclaration) {
      const statements = [];
      const statementOffset = factory2.copyPrologue(node.statements, statements);
      append(statements, externalHelpersImportDeclaration);
      addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset));
      return factory2.updateSourceFile(
        node,
        setTextRange(factory2.createNodeArray(statements), node.statements)
      );
    } else {
      return visitEachChild(node, visitor, context);
    }
  }
  function visitor(node) {
    switch (node.kind) {
      case 270 /* ImportEqualsDeclaration */:
        return getEmitModuleKind(compilerOptions) >= 100 /* Node16 */ ? visitImportEqualsDeclaration(node) : void 0;
      case 276 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 277 /* ExportDeclaration */:
        const exportDecl = node;
        return visitExportDeclaration(exportDecl);
    }
    return node;
  }
  function createRequireCall2(importNode) {
    const moduleName = getExternalModuleNameLiteral(factory2, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions);
    const args = [];
    if (moduleName) {
      args.push(moduleName);
    }
    if (!importRequireStatements) {
      const createRequireName = factory2.createUniqueName("_createRequire", 16 /* Optimistic */ | 32 /* FileLevel */);
      const importStatement = factory2.createImportDeclaration(
        /*modifiers*/
        void 0,
        factory2.createImportClause(
          /*isTypeOnly*/
          false,
          /*name*/
          void 0,
          factory2.createNamedImports([
            factory2.createImportSpecifier(
              /*isTypeOnly*/
              false,
              factory2.createIdentifier("createRequire"),
              createRequireName
            )
          ])
        ),
        factory2.createStringLiteral("module")
      );
      const requireHelperName = factory2.createUniqueName("__require", 16 /* Optimistic */ | 32 /* FileLevel */);
      const requireStatement = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList(
          [
            factory2.createVariableDeclaration(
              requireHelperName,
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              factory2.createCallExpression(
                factory2.cloneNode(createRequireName),
                /*typeArguments*/
                void 0,
                [
                  factory2.createPropertyAccessExpression(factory2.createMetaProperty(102 /* ImportKeyword */, factory2.createIdentifier("meta")), factory2.createIdentifier("url"))
                ]
              )
            )
          ],
          /*flags*/
          languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
        )
      );
      importRequireStatements = [importStatement, requireStatement];
    }
    const name = importRequireStatements[1].declarationList.declarations[0].name;
    Debug.assertNode(name, isIdentifier);
    return factory2.createCallExpression(
      factory2.cloneNode(name),
      /*typeArguments*/
      void 0,
      args
    );
  }
  function visitImportEqualsDeclaration(node) {
    Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
    let statements;
    statements = append(
      statements,
      setOriginalNode(
        setTextRange(
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList(
              [
                factory2.createVariableDeclaration(
                  factory2.cloneNode(node.name),
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  createRequireCall2(node)
                )
              ],
              /*flags*/
              languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
            )
          ),
          node
        ),
        node
      )
    );
    statements = appendExportsOfImportEqualsDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function appendExportsOfImportEqualsDeclaration(statements, node) {
    if (hasSyntacticModifier(node, 1 /* Export */)) {
      statements = append(statements, factory2.createExportDeclaration(
        /*modifiers*/
        void 0,
        node.isTypeOnly,
        factory2.createNamedExports([factory2.createExportSpecifier(
          /*isTypeOnly*/
          false,
          /*propertyName*/
          void 0,
          idText(node.name)
        )])
      ));
    }
    return statements;
  }
  function visitExportAssignment(node) {
    return node.isExportEquals ? void 0 : node;
  }
  function visitExportDeclaration(node) {
    if (compilerOptions.module !== void 0 && compilerOptions.module > 5 /* ES2015 */) {
      return node;
    }
    if (!node.exportClause || !isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
      return node;
    }
    const oldIdentifier = node.exportClause.name;
    const synthName = factory2.getGeneratedNameForNode(oldIdentifier);
    const importDecl = factory2.createImportDeclaration(
      /*modifiers*/
      void 0,
      factory2.createImportClause(
        /*isTypeOnly*/
        false,
        /*name*/
        void 0,
        factory2.createNamespaceImport(
          synthName
        )
      ),
      node.moduleSpecifier,
      node.assertClause
    );
    setOriginalNode(importDecl, node.exportClause);
    const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory2.createExportDefault(synthName) : factory2.createExportDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      false,
      factory2.createNamedExports([factory2.createExportSpecifier(
        /*isTypeOnly*/
        false,
        synthName,
        oldIdentifier
      )])
    );
    setOriginalNode(exportDecl, node);
    return [importDecl, exportDecl];
  }
  function onEmitNode(hint, node, emitCallback) {
    if (isSourceFile(node)) {
      if ((isExternalModule(node) || getIsolatedModules(compilerOptions)) && compilerOptions.importHelpers) {
        helperNameSubstitutions = /* @__PURE__ */ new Map();
      }
      previousOnEmitNode(hint, node, emitCallback);
      helperNameSubstitutions = void 0;
    } else {
      previousOnEmitNode(hint, node, emitCallback);
    }
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (helperNameSubstitutions && isIdentifier(node) && getEmitFlags(node) & 8192 /* HelperName */) {
      return substituteHelperName(node);
    }
    return node;
  }
  function substituteHelperName(node) {
    const name = idText(node);
    let substitution = helperNameSubstitutions.get(name);
    if (!substitution) {
      helperNameSubstitutions.set(name, substitution = factory2.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
    }
    return substitution;
  }
}

// src/compiler/transformers/module/node.ts
function transformNodeModule(context) {
  const previousOnSubstituteNode = context.onSubstituteNode;
  const previousOnEmitNode = context.onEmitNode;
  const esmTransform = transformECMAScriptModule(context);
  const esmOnSubstituteNode = context.onSubstituteNode;
  const esmOnEmitNode = context.onEmitNode;
  context.onSubstituteNode = previousOnSubstituteNode;
  context.onEmitNode = previousOnEmitNode;
  const cjsTransform = transformModule(context);
  const cjsOnSubstituteNode = context.onSubstituteNode;
  const cjsOnEmitNode = context.onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.enableSubstitution(311 /* SourceFile */);
  context.enableEmitNotification(311 /* SourceFile */);
  let currentSourceFile;
  return transformSourceFileOrBundle;
  function onSubstituteNode(hint, node) {
    if (isSourceFile(node)) {
      currentSourceFile = node;
      return previousOnSubstituteNode(hint, node);
    } else {
      if (!currentSourceFile) {
        return previousOnSubstituteNode(hint, node);
      }
      if (currentSourceFile.impliedNodeFormat === 99 /* ESNext */) {
        return esmOnSubstituteNode(hint, node);
      }
      return cjsOnSubstituteNode(hint, node);
    }
  }
  function onEmitNode(hint, node, emitCallback) {
    if (isSourceFile(node)) {
      currentSourceFile = node;
    }
    if (!currentSourceFile) {
      return previousOnEmitNode(hint, node, emitCallback);
    }
    if (currentSourceFile.impliedNodeFormat === 99 /* ESNext */) {
      return esmOnEmitNode(hint, node, emitCallback);
    }
    return cjsOnEmitNode(hint, node, emitCallback);
  }
  function getModuleTransformForFile(file) {
    return file.impliedNodeFormat === 99 /* ESNext */ ? esmTransform : cjsTransform;
  }
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    currentSourceFile = node;
    const result = getModuleTransformForFile(node)(node);
    currentSourceFile = void 0;
    Debug.assert(isSourceFile(result));
    return result;
  }
  function transformSourceFileOrBundle(node) {
    return node.kind === 311 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
  }
  function transformBundle(node) {
    return context.factory.createBundle(map(node.sourceFiles, transformSourceFile), node.prepends);
  }
}

// src/compiler/transformers/declarations/diagnostics.ts
function canProduceDiagnostics(node) {
  return isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isSetAccessor(node) || isGetAccessor(node) || isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isParameter(node) || isTypeParameterDeclaration(node) || isExpressionWithTypeArguments(node) || isImportEqualsDeclaration(node) || isTypeAliasDeclaration(node) || isConstructorDeclaration(node) || isIndexSignatureDeclaration(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isJSDocTypeAlias(node);
}
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
  if (isSetAccessor(node) || isGetAccessor(node)) {
    return getAccessorNameVisibilityError;
  } else if (isMethodSignature(node) || isMethodDeclaration(node)) {
    return getMethodNameVisibilityError;
  } else {
    return createGetSymbolAccessibilityDiagnosticForNode(node);
  }
  function getAccessorNameVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    if (isStatic(node)) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
    } else if (node.parent.kind === 262 /* ClassDeclaration */) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
    } else {
      return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
    }
  }
  function getMethodNameVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    if (isStatic(node)) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
    } else if (node.parent.kind === 262 /* ClassDeclaration */) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
    } else {
      return symbolAccessibilityResult.errorModuleName ? Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
    }
  }
}
function createGetSymbolAccessibilityDiagnosticForNode(node) {
  if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) {
    return getVariableDeclarationTypeVisibilityError;
  } else if (isSetAccessor(node) || isGetAccessor(node)) {
    return getAccessorDeclarationTypeVisibilityError;
  } else if (isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isIndexSignatureDeclaration(node)) {
    return getReturnTypeVisibilityError;
  } else if (isParameter(node)) {
    if (isParameterPropertyDeclaration(node, node.parent) && hasSyntacticModifier(node.parent, 8 /* Private */)) {
      return getVariableDeclarationTypeVisibilityError;
    }
    return getParameterDeclarationTypeVisibilityError;
  } else if (isTypeParameterDeclaration(node)) {
    return getTypeParameterConstraintVisibilityError;
  } else if (isExpressionWithTypeArguments(node)) {
    return getHeritageClauseVisibilityError;
  } else if (isImportEqualsDeclaration(node)) {
    return getImportEntityNameVisibilityError;
  } else if (isTypeAliasDeclaration(node) || isJSDocTypeAlias(node)) {
    return getTypeAliasDeclarationVisibilityError;
  } else {
    return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${Debug.formatSyntaxKind(node.kind)}`);
  }
  function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    if (node.kind === 259 /* VariableDeclaration */ || node.kind === 207 /* BindingElement */) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
    } else if (node.kind === 171 /* PropertyDeclaration */ || node.kind === 210 /* PropertyAccessExpression */ || node.kind === 211 /* ElementAccessExpression */ || node.kind === 225 /* BinaryExpression */ || node.kind === 170 /* PropertySignature */ || node.kind === 168 /* Parameter */ && hasSyntacticModifier(node.parent, 8 /* Private */)) {
      if (isStatic(node)) {
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
      } else if (node.parent.kind === 262 /* ClassDeclaration */ || node.kind === 168 /* Parameter */) {
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
      } else {
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
      }
    }
  }
  function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
    let diagnosticMessage;
    if (node.kind === 177 /* SetAccessor */) {
      if (isStatic(node)) {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
      } else {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
      }
    } else {
      if (isStatic(node)) {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
      } else {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
      }
    }
    return {
      diagnosticMessage,
      errorNode: node.name,
      typeName: node.name
    };
  }
  function getReturnTypeVisibilityError(symbolAccessibilityResult) {
    let diagnosticMessage;
    switch (node.kind) {
      case 179 /* ConstructSignature */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
        break;
      case 178 /* CallSignature */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
        break;
      case 180 /* IndexSignature */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
        break;
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
        if (isStatic(node)) {
          diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
        } else if (node.parent.kind === 262 /* ClassDeclaration */) {
          diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
        } else {
          diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
        }
        break;
      case 261 /* FunctionDeclaration */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
        break;
      default:
        return Debug.fail("This is unknown kind for signature: " + node.kind);
    }
    return {
      diagnosticMessage,
      errorNode: node.name || node
    };
  }
  function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    switch (node.parent.kind) {
      case 175 /* Constructor */:
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
      case 179 /* ConstructSignature */:
      case 184 /* ConstructorType */:
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
      case 178 /* CallSignature */:
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
      case 180 /* IndexSignature */:
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
        if (isStatic(node.parent)) {
          return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
        } else if (node.parent.parent.kind === 262 /* ClassDeclaration */) {
          return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
        } else {
          return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
        }
      case 261 /* FunctionDeclaration */:
      case 183 /* FunctionType */:
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
      case 177 /* SetAccessor */:
      case 176 /* GetAccessor */:
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
      default:
        return Debug.fail(`Unknown parent for parameter: ${Debug.formatSyntaxKind(node.parent.kind)}`);
    }
  }
  function getTypeParameterConstraintVisibilityError() {
    let diagnosticMessage;
    switch (node.parent.kind) {
      case 262 /* ClassDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
        break;
      case 263 /* InterfaceDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
        break;
      case 199 /* MappedType */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
        break;
      case 184 /* ConstructorType */:
      case 179 /* ConstructSignature */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
        break;
      case 178 /* CallSignature */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
        break;
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
        if (isStatic(node.parent)) {
          diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
        } else if (node.parent.parent.kind === 262 /* ClassDeclaration */) {
          diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
        } else {
          diagnosticMessage = Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
        }
        break;
      case 183 /* FunctionType */:
      case 261 /* FunctionDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
        break;
      case 194 /* InferType */:
        diagnosticMessage = Diagnostics.Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1;
        break;
      case 264 /* TypeAliasDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
        break;
      default:
        return Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
    }
    return {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    };
  }
  function getHeritageClauseVisibilityError() {
    let diagnosticMessage;
    if (isClassDeclaration(node.parent.parent)) {
      diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === 119 /* ImplementsKeyword */ ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
    } else {
      diagnosticMessage = Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
    }
    return {
      diagnosticMessage,
      errorNode: node,
      typeName: getNameOfDeclaration(node.parent.parent)
    };
  }
  function getImportEntityNameVisibilityError() {
    return {
      diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1,
      errorNode: node,
      typeName: node.name
    };
  }
  function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) {
    return {
      diagnosticMessage: symbolAccessibilityResult.errorModuleName ? Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 : Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
      errorNode: isJSDocTypeAlias(node) ? Debug.checkDefined(node.typeExpression) : node.type,
      typeName: isJSDocTypeAlias(node) ? getNameOfDeclaration(node) : node.name
    };
  }
}

// src/compiler/transformers/declarations.ts
function getDeclarationDiagnostics(host, resolver, file) {
  const compilerOptions = host.getCompilerOptions();
  const result = transformNodes(
    resolver,
    host,
    factory,
    compilerOptions,
    file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJson),
    [transformDeclarations],
    /*allowDtsFiles*/
    false
  );
  return result.diagnostics;
}
function hasInternalAnnotation(range, currentSourceFile) {
  const comment = currentSourceFile.text.substring(range.pos, range.end);
  return stringContains(comment, "@internal");
}
function isInternalDeclaration(node, currentSourceFile) {
  const parseTreeNode = getParseTreeNode(node);
  if (parseTreeNode && parseTreeNode.kind === 168 /* Parameter */) {
    const paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
    const previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : void 0;
    const text = currentSourceFile.text;
    const commentRanges = previousSibling ? concatenate(
      // to handle
      // ... parameters, /** @internal */
      // public param: string
      getTrailingCommentRanges(text, skipTrivia(
        text,
        previousSibling.end + 1,
        /*stopAfterLineBreak*/
        false,
        /*stopAtComments*/
        true
      )),
      getLeadingCommentRanges(text, node.pos)
    ) : getTrailingCommentRanges(text, skipTrivia(
      text,
      node.pos,
      /*stopAfterLineBreak*/
      false,
      /*stopAtComments*/
      true
    ));
    return commentRanges && commentRanges.length && hasInternalAnnotation(last(commentRanges), currentSourceFile);
  }
  const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
  return !!forEach(leadingCommentRanges, (range) => {
    return hasInternalAnnotation(range, currentSourceFile);
  });
}
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */;
function transformDeclarations(context) {
  const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context");
  let getSymbolAccessibilityDiagnostic = throwDiagnostic;
  let needsDeclare = true;
  let isBundledEmit = false;
  let resultHasExternalModuleIndicator = false;
  let needsScopeFixMarker = false;
  let resultHasScopeMarker = false;
  let enclosingDeclaration;
  let necessaryTypeReferences;
  let lateMarkedStatements;
  let lateStatementReplacementMap;
  let suppressNewDiagnosticContexts;
  let exportedModulesFromDeclarationEmit;
  const { factory: factory2 } = context;
  const host = context.getEmitHost();
  const symbolTracker = {
    trackSymbol,
    reportInaccessibleThisError,
    reportInaccessibleUniqueSymbolError,
    reportCyclicStructureError,
    reportPrivateInBaseOfClassExpression,
    reportLikelyUnsafeImportRequiredError,
    reportTruncationError,
    moduleResolverHost: host,
    trackReferencedAmbientModule,
    trackExternalModuleSymbolOfImportTypeNode,
    reportNonlocalAugmentation,
    reportNonSerializableProperty,
    reportImportTypeNodeResolutionModeOverride
  };
  let errorNameNode;
  let errorFallbackNode;
  let currentSourceFile;
  let refs;
  let libs2;
  let emittedImports;
  const resolver = context.getEmitResolver();
  const options = context.getCompilerOptions();
  const { noResolve, stripInternal } = options;
  return transformRoot;
  function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
    if (!typeReferenceDirectives) {
      return;
    }
    necessaryTypeReferences = necessaryTypeReferences || /* @__PURE__ */ new Set();
    for (const ref of typeReferenceDirectives) {
      necessaryTypeReferences.add(ref);
    }
  }
  function trackReferencedAmbientModule(node, symbol) {
    const directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
    if (length(directives)) {
      return recordTypeReferenceDirectivesIfNecessary(directives);
    }
    const container = getSourceFileOfNode(node);
    refs.set(getOriginalNodeId(container), container);
  }
  function handleSymbolAccessibilityError(symbolAccessibilityResult) {
    if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
      if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
        if (!lateMarkedStatements) {
          lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
        } else {
          for (const ref of symbolAccessibilityResult.aliasesToMakeVisible) {
            pushIfUnique(lateMarkedStatements, ref);
          }
        }
      }
    } else {
      const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
      if (errorInfo) {
        if (errorInfo.typeName) {
          context.addDiagnostic(createDiagnosticForNode(
            symbolAccessibilityResult.errorNode || errorInfo.errorNode,
            errorInfo.diagnosticMessage,
            getTextOfNode(errorInfo.typeName),
            symbolAccessibilityResult.errorSymbolName,
            symbolAccessibilityResult.errorModuleName
          ));
        } else {
          context.addDiagnostic(createDiagnosticForNode(
            symbolAccessibilityResult.errorNode || errorInfo.errorNode,
            errorInfo.diagnosticMessage,
            symbolAccessibilityResult.errorSymbolName,
            symbolAccessibilityResult.errorModuleName
          ));
        }
        return true;
      }
    }
    return false;
  }
  function trackExternalModuleSymbolOfImportTypeNode(symbol) {
    if (!isBundledEmit) {
      (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
    }
  }
  function trackSymbol(symbol, enclosingDeclaration2, meaning) {
    if (symbol.flags & 262144 /* TypeParameter */)
      return false;
    const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible(
      symbol,
      enclosingDeclaration2,
      meaning,
      /*shouldComputeAliasToMarkVisible*/
      true
    ));
    recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
    return issuedDiagnostic;
  }
  function reportPrivateInBaseOfClassExpression(propertyName) {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(
        createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)
      );
    }
  }
  function errorDeclarationNameWithFallback() {
    return errorNameNode ? declarationNameToString(errorNameNode) : errorFallbackNode && getNameOfDeclaration(errorFallbackNode) ? declarationNameToString(getNameOfDeclaration(errorFallbackNode)) : errorFallbackNode && isExportAssignment(errorFallbackNode) ? errorFallbackNode.isExportEquals ? "export=" : "default" : "(Missing)";
  }
  function reportInaccessibleUniqueSymbolError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(
        errorNameNode || errorFallbackNode,
        Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary,
        errorDeclarationNameWithFallback(),
        "unique symbol"
      ));
    }
  }
  function reportCyclicStructureError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(
        errorNameNode || errorFallbackNode,
        Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary,
        errorDeclarationNameWithFallback()
      ));
    }
  }
  function reportInaccessibleThisError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(
        errorNameNode || errorFallbackNode,
        Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary,
        errorDeclarationNameWithFallback(),
        "this"
      ));
    }
  }
  function reportLikelyUnsafeImportRequiredError(specifier) {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(
        errorNameNode || errorFallbackNode,
        Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary,
        errorDeclarationNameWithFallback(),
        specifier
      ));
    }
  }
  function reportTruncationError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
    }
  }
  function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
    var _a;
    const primaryDeclaration = (_a = parentSymbol.declarations) == null ? void 0 : _a.find((d) => getSourceFileOfNode(d) === containingFile);
    const augmentingDeclarations = filter(symbol.declarations, (d) => getSourceFileOfNode(d) !== containingFile);
    if (primaryDeclaration && augmentingDeclarations) {
      for (const augmentations of augmentingDeclarations) {
        context.addDiagnostic(addRelatedInfo(
          createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized),
          createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file)
        ));
      }
    }
  }
  function reportNonSerializableProperty(propertyName) {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName));
    }
  }
  function reportImportTypeNodeResolutionModeOverride() {
    if (!isNightly() && (errorNameNode || errorFallbackNode)) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_type_of_this_expression_cannot_be_named_without_a_resolution_mode_assertion_which_is_an_unstable_feature_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next));
    }
  }
  function transformDeclarationsForJS(sourceFile, bundled) {
    const oldDiag = getSymbolAccessibilityDiagnostic;
    getSymbolAccessibilityDiagnostic = (s) => s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : {
      diagnosticMessage: s.errorModuleName ? Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
      errorNode: s.errorNode || sourceFile
    };
    const result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
    getSymbolAccessibilityDiagnostic = oldDiag;
    return result;
  }
  function transformRoot(node) {
    if (node.kind === 311 /* SourceFile */ && node.isDeclarationFile) {
      return node;
    }
    if (node.kind === 312 /* Bundle */) {
      isBundledEmit = true;
      refs = /* @__PURE__ */ new Map();
      libs2 = /* @__PURE__ */ new Map();
      let hasNoDefaultLib = false;
      const bundle = factory2.createBundle(map(
        node.sourceFiles,
        (sourceFile) => {
          if (sourceFile.isDeclarationFile)
            return void 0;
          hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib;
          currentSourceFile = sourceFile;
          enclosingDeclaration = sourceFile;
          lateMarkedStatements = void 0;
          suppressNewDiagnosticContexts = false;
          lateStatementReplacementMap = /* @__PURE__ */ new Map();
          getSymbolAccessibilityDiagnostic = throwDiagnostic;
          needsScopeFixMarker = false;
          resultHasScopeMarker = false;
          collectReferences(sourceFile, refs);
          collectLibs(sourceFile, libs2);
          if (isExternalOrCommonJsModule(sourceFile) || isJsonSourceFile(sourceFile)) {
            resultHasExternalModuleIndicator = false;
            needsDeclare = false;
            const statements = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(
              sourceFile,
              /*bundled*/
              true
            )) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement);
            const newFile = factory2.updateSourceFile(
              sourceFile,
              [factory2.createModuleDeclaration(
                [factory2.createModifier(138 /* DeclareKeyword */)],
                factory2.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)),
                factory2.createModuleBlock(setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements))
              )],
              /*isDeclarationFile*/
              true,
              /*referencedFiles*/
              [],
              /*typeReferences*/
              [],
              /*hasNoDefaultLib*/
              false,
              /*libReferences*/
              []
            );
            return newFile;
          }
          needsDeclare = true;
          const updated2 = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement);
          return factory2.updateSourceFile(
            sourceFile,
            transformAndReplaceLatePaintedStatements(updated2),
            /*isDeclarationFile*/
            true,
            /*referencedFiles*/
            [],
            /*typeReferences*/
            [],
            /*hasNoDefaultLib*/
            false,
            /*libReferences*/
            []
          );
        }
      ), mapDefined(node.prepends, (prepend) => {
        if (prepend.kind === 314 /* InputFiles */) {
          const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal);
          hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib;
          collectReferences(sourceFile, refs);
          recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, (ref) => [ref.fileName, ref.resolutionMode]));
          collectLibs(sourceFile, libs2);
          return sourceFile;
        }
        return prepend;
      }));
      bundle.syntheticFileReferences = [];
      bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
      bundle.syntheticLibReferences = getLibReferences();
      bundle.hasNoDefaultLib = hasNoDefaultLib;
      const outputFilePath2 = getDirectoryPath(normalizeSlashes(getOutputPathsFor(
        node,
        host,
        /*forceDtsPaths*/
        true
      ).declarationFilePath));
      const referenceVisitor2 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath2);
      refs.forEach(referenceVisitor2);
      return bundle;
    }
    needsDeclare = true;
    needsScopeFixMarker = false;
    resultHasScopeMarker = false;
    enclosingDeclaration = node;
    currentSourceFile = node;
    getSymbolAccessibilityDiagnostic = throwDiagnostic;
    isBundledEmit = false;
    resultHasExternalModuleIndicator = false;
    suppressNewDiagnosticContexts = false;
    lateMarkedStatements = void 0;
    lateStatementReplacementMap = /* @__PURE__ */ new Map();
    necessaryTypeReferences = void 0;
    refs = collectReferences(currentSourceFile, /* @__PURE__ */ new Map());
    libs2 = collectLibs(currentSourceFile, /* @__PURE__ */ new Map());
    const references = [];
    const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(
      node,
      host,
      /*forceDtsPaths*/
      true
    ).declarationFilePath));
    const referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
    let combinedStatements;
    if (isSourceFileJS(currentSourceFile)) {
      combinedStatements = factory2.createNodeArray(transformDeclarationsForJS(node));
      refs.forEach(referenceVisitor);
      emittedImports = filter(combinedStatements, isAnyImportSyntax);
    } else {
      const statements = visitNodes2(node.statements, visitDeclarationStatements, isStatement);
      combinedStatements = setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
      refs.forEach(referenceVisitor);
      emittedImports = filter(combinedStatements, isAnyImportSyntax);
      if (isExternalModule(node) && (!resultHasExternalModuleIndicator || needsScopeFixMarker && !resultHasScopeMarker)) {
        combinedStatements = setTextRange(factory2.createNodeArray([...combinedStatements, createEmptyExports(factory2)]), combinedStatements);
      }
    }
    const updated = factory2.updateSourceFile(
      node,
      combinedStatements,
      /*isDeclarationFile*/
      true,
      references,
      getFileReferencesForUsedTypeReferences(),
      node.hasNoDefaultLib,
      getLibReferences()
    );
    updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
    return updated;
    function getLibReferences() {
      return arrayFrom(libs2.keys(), (lib) => ({ fileName: lib, pos: -1, end: -1 }));
    }
    function getFileReferencesForUsedTypeReferences() {
      return necessaryTypeReferences ? mapDefined(arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForSpecifierModeTuple) : [];
    }
    function getFileReferenceForSpecifierModeTuple([typeName, mode]) {
      if (emittedImports) {
        for (const importStatement of emittedImports) {
          if (isImportEqualsDeclaration(importStatement) && isExternalModuleReference(importStatement.moduleReference)) {
            const expr = importStatement.moduleReference.expression;
            if (isStringLiteralLike(expr) && expr.text === typeName) {
              return void 0;
            }
          } else if (isImportDeclaration(importStatement) && isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
            return void 0;
          }
        }
      }
      return { fileName: typeName, pos: -1, end: -1, ...mode ? { resolutionMode: mode } : void 0 };
    }
    function mapReferencesIntoArray(references2, outputFilePath2) {
      return (file) => {
        let declFileName;
        if (file.isDeclarationFile) {
          declFileName = file.fileName;
        } else {
          if (isBundledEmit && contains(node.sourceFiles, file))
            return;
          const paths = getOutputPathsFor(
            file,
            host,
            /*forceDtsPaths*/
            true
          );
          declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
        }
        if (declFileName) {
          const specifier = getModuleSpecifier(
            options,
            currentSourceFile,
            toPath(outputFilePath2, host.getCurrentDirectory(), host.getCanonicalFileName),
            toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName),
            host
          );
          if (!pathIsRelative(specifier)) {
            recordTypeReferenceDirectivesIfNecessary([[
              specifier,
              /*mode*/
              void 0
            ]]);
            return;
          }
          let fileName = getRelativePathToDirectoryOrUrl(
            outputFilePath2,
            declFileName,
            host.getCurrentDirectory(),
            host.getCanonicalFileName,
            /*isAbsolutePathAnUrl*/
            false
          );
          if (startsWith(fileName, "./") && hasExtension(fileName)) {
            fileName = fileName.substring(2);
          }
          if (startsWith(fileName, "node_modules/") || pathContainsNodeModules(fileName)) {
            return;
          }
          references2.push({ pos: -1, end: -1, fileName });
        }
      };
    }
  }
  function collectReferences(sourceFile, ret) {
    if (noResolve || !isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile))
      return ret;
    forEach(sourceFile.referencedFiles, (f) => {
      const elem = host.getSourceFileFromReference(sourceFile, f);
      if (elem) {
        ret.set(getOriginalNodeId(elem), elem);
      }
    });
    return ret;
  }
  function collectLibs(sourceFile, ret) {
    forEach(sourceFile.libReferenceDirectives, (ref) => {
      const lib = host.getLibFileFromReference(ref);
      if (lib) {
        ret.set(toFileNameLowerCase(ref.fileName), true);
      }
    });
    return ret;
  }
  function filterBindingPatternInitializersAndRenamings(name) {
    if (name.kind === 80 /* Identifier */) {
      return name;
    } else {
      if (name.kind === 206 /* ArrayBindingPattern */) {
        return factory2.updateArrayBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isArrayBindingElement));
      } else {
        return factory2.updateObjectBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isBindingElement));
      }
    }
    function visitBindingElement(elem) {
      if (elem.kind === 231 /* OmittedExpression */) {
        return elem;
      }
      if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) {
        return factory2.updateBindingElement(
          elem,
          elem.dotDotDotToken,
          /*propertyName*/
          void 0,
          elem.propertyName,
          shouldPrintWithInitializer(elem) ? elem.initializer : void 0
        );
      }
      return factory2.updateBindingElement(
        elem,
        elem.dotDotDotToken,
        elem.propertyName,
        filterBindingPatternInitializersAndRenamings(elem.name),
        shouldPrintWithInitializer(elem) ? elem.initializer : void 0
      );
    }
  }
  function ensureParameter(p, modifierMask, type) {
    let oldDiag;
    if (!suppressNewDiagnosticContexts) {
      oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p);
    }
    const newParam = factory2.updateParameterDeclaration(
      p,
      maskModifiers(factory2, p, modifierMask),
      p.dotDotDotToken,
      filterBindingPatternInitializersAndRenamings(p.name),
      resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0,
      ensureType(
        p,
        type || p.type,
        /*ignorePrivate*/
        true
      ),
      // Ignore private param props, since this type is going straight back into a param
      ensureNoInitializer(p)
    );
    if (!suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = oldDiag;
    }
    return newParam;
  }
  function shouldPrintWithInitializer(node) {
    return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(getParseTreeNode(node));
  }
  function ensureNoInitializer(node) {
    if (shouldPrintWithInitializer(node)) {
      return resolver.createLiteralConstValue(getParseTreeNode(node), symbolTracker);
    }
    return void 0;
  }
  function ensureType(node, type, ignorePrivate) {
    if (!ignorePrivate && hasEffectiveModifier(node, 8 /* Private */)) {
      return;
    }
    if (shouldPrintWithInitializer(node)) {
      return;
    }
    const shouldUseResolverType = node.kind === 168 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node));
    if (type && !shouldUseResolverType) {
      return visitNode(type, visitDeclarationSubtree, isTypeNode);
    }
    if (!getParseTreeNode(node)) {
      return type ? visitNode(type, visitDeclarationSubtree, isTypeNode) : factory2.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    if (node.kind === 177 /* SetAccessor */) {
      return factory2.createKeywordTypeNode(133 /* AnyKeyword */);
    }
    errorNameNode = node.name;
    let oldDiag;
    if (!suppressNewDiagnosticContexts) {
      oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node);
    }
    if (node.kind === 259 /* VariableDeclaration */ || node.kind === 207 /* BindingElement */) {
      return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
    }
    if (node.kind === 168 /* Parameter */ || node.kind === 171 /* PropertyDeclaration */ || node.kind === 170 /* PropertySignature */) {
      if (isPropertySignature(node) || !node.initializer)
        return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
      return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
    }
    return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
    function cleanup(returnValue) {
      errorNameNode = void 0;
      if (!suppressNewDiagnosticContexts) {
        getSymbolAccessibilityDiagnostic = oldDiag;
      }
      return returnValue || factory2.createKeywordTypeNode(133 /* AnyKeyword */);
    }
  }
  function isDeclarationAndNotVisible(node) {
    node = getParseTreeNode(node);
    switch (node.kind) {
      case 261 /* FunctionDeclaration */:
      case 266 /* ModuleDeclaration */:
      case 263 /* InterfaceDeclaration */:
      case 262 /* ClassDeclaration */:
      case 264 /* TypeAliasDeclaration */:
      case 265 /* EnumDeclaration */:
        return !resolver.isDeclarationVisible(node);
      case 259 /* VariableDeclaration */:
        return !getBindingNameVisible(node);
      case 270 /* ImportEqualsDeclaration */:
      case 271 /* ImportDeclaration */:
      case 277 /* ExportDeclaration */:
      case 276 /* ExportAssignment */:
        return false;
      case 174 /* ClassStaticBlockDeclaration */:
        return true;
    }
    return false;
  }
  function shouldEmitFunctionProperties(input) {
    var _a;
    if (input.body) {
      return true;
    }
    const overloadSignatures = (_a = input.symbol.declarations) == null ? void 0 : _a.filter((decl) => isFunctionDeclaration(decl) && !decl.body);
    return !overloadSignatures || overloadSignatures.indexOf(input) === overloadSignatures.length - 1;
  }
  function getBindingNameVisible(elem) {
    if (isOmittedExpression(elem)) {
      return false;
    }
    if (isBindingPattern(elem.name)) {
      return some(elem.name.elements, getBindingNameVisible);
    } else {
      return resolver.isDeclarationVisible(elem);
    }
  }
  function updateParamsList(node, params, modifierMask) {
    if (hasEffectiveModifier(node, 8 /* Private */)) {
      return factory2.createNodeArray();
    }
    const newParams = map(params, (p) => ensureParameter(p, modifierMask));
    if (!newParams) {
      return factory2.createNodeArray();
    }
    return factory2.createNodeArray(newParams, params.hasTrailingComma);
  }
  function updateAccessorParamsList(input, isPrivate) {
    let newParams;
    if (!isPrivate) {
      const thisParameter = getThisParameter(input);
      if (thisParameter) {
        newParams = [ensureParameter(thisParameter)];
      }
    }
    if (isSetAccessorDeclaration(input)) {
      let newValueParameter;
      if (!isPrivate) {
        const valueParameter = getSetAccessorValueParameter(input);
        if (valueParameter) {
          const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
          newValueParameter = ensureParameter(
            valueParameter,
            /*modifierMask*/
            void 0,
            accessorType
          );
        }
      }
      if (!newValueParameter) {
        newValueParameter = factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          "value"
        );
      }
      newParams = append(newParams, newValueParameter);
    }
    return factory2.createNodeArray(newParams || emptyArray);
  }
  function ensureTypeParams(node, params) {
    return hasEffectiveModifier(node, 8 /* Private */) ? void 0 : visitNodes2(params, visitDeclarationSubtree, isTypeParameterDeclaration);
  }
  function isEnclosingDeclaration(node) {
    return isSourceFile(node) || isTypeAliasDeclaration(node) || isModuleDeclaration(node) || isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionLike(node) || isIndexSignatureDeclaration(node) || isMappedTypeNode(node);
  }
  function checkEntityNameVisibility(entityName, enclosingDeclaration2) {
    const visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration2);
    handleSymbolAccessibilityError(visibilityResult);
    recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
  }
  function preserveJsDoc(updated, original) {
    if (hasJSDocNodes(updated) && hasJSDocNodes(original)) {
      updated.jsDoc = original.jsDoc;
    }
    return setCommentRange(updated, getCommentRange(original));
  }
  function rewriteModuleSpecifier(parent2, input) {
    if (!input)
      return void 0;
    resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent2.kind !== 266 /* ModuleDeclaration */ && parent2.kind !== 204 /* ImportType */;
    if (isStringLiteralLike(input)) {
      if (isBundledEmit) {
        const newName = getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent2);
        if (newName) {
          return factory2.createStringLiteral(newName);
        }
      } else {
        const symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
        if (symbol) {
          (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
        }
      }
    }
    return input;
  }
  function transformImportEqualsDeclaration(decl) {
    if (!resolver.isDeclarationVisible(decl))
      return;
    if (decl.moduleReference.kind === 282 /* ExternalModuleReference */) {
      const specifier = getExternalModuleImportEqualsDeclarationExpression(decl);
      return factory2.updateImportEqualsDeclaration(
        decl,
        decl.modifiers,
        decl.isTypeOnly,
        decl.name,
        factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))
      );
    } else {
      const oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(decl);
      checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
      getSymbolAccessibilityDiagnostic = oldDiag;
      return decl;
    }
  }
  function transformImportDeclaration(decl) {
    if (!decl.importClause) {
      return factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        decl.importClause,
        rewriteModuleSpecifier(decl, decl.moduleSpecifier),
        getResolutionModeOverrideForClauseInNightly(decl.assertClause)
      );
    }
    const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : void 0;
    if (!decl.importClause.namedBindings) {
      return visibleDefaultBinding && factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(
        decl.importClause,
        decl.importClause.isTypeOnly,
        visibleDefaultBinding,
        /*namedBindings*/
        void 0
      ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause));
    }
    if (decl.importClause.namedBindings.kind === 273 /* NamespaceImport */) {
      const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : (
        /*namedBindings*/
        void 0
      );
      return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(
        decl.importClause,
        decl.importClause.isTypeOnly,
        visibleDefaultBinding,
        namedBindings
      ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : void 0;
    }
    const bindingList = mapDefined(decl.importClause.namedBindings.elements, (b) => resolver.isDeclarationVisible(b) ? b : void 0);
    if (bindingList && bindingList.length || visibleDefaultBinding) {
      return factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        factory2.updateImportClause(
          decl.importClause,
          decl.importClause.isTypeOnly,
          visibleDefaultBinding,
          bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0
        ),
        rewriteModuleSpecifier(decl, decl.moduleSpecifier),
        getResolutionModeOverrideForClauseInNightly(decl.assertClause)
      );
    }
    if (resolver.isImportRequiredByAugmentation(decl)) {
      return factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        /*importClause*/
        void 0,
        rewriteModuleSpecifier(decl, decl.moduleSpecifier),
        getResolutionModeOverrideForClauseInNightly(decl.assertClause)
      );
    }
  }
  function getResolutionModeOverrideForClauseInNightly(assertClause) {
    const mode = getResolutionModeOverrideForClause(assertClause);
    if (mode !== void 0) {
      if (!isNightly()) {
        context.addDiagnostic(createDiagnosticForNode(assertClause, Diagnostics.resolution_mode_assertions_are_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next));
      }
      return assertClause;
    }
    return void 0;
  }
  function transformAndReplaceLatePaintedStatements(statements) {
    while (length(lateMarkedStatements)) {
      const i = lateMarkedStatements.shift();
      if (!isLateVisibilityPaintedStatement(i)) {
        return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${Debug.formatSyntaxKind(i.kind)}`);
      }
      const priorNeedsDeclare = needsDeclare;
      needsDeclare = i.parent && isSourceFile(i.parent) && !(isExternalModule(i.parent) && isBundledEmit);
      const result = transformTopLevelDeclaration(i);
      needsDeclare = priorNeedsDeclare;
      lateStatementReplacementMap.set(getOriginalNodeId(i), result);
    }
    return visitNodes2(statements, visitLateVisibilityMarkedStatements, isStatement);
    function visitLateVisibilityMarkedStatements(statement) {
      if (isLateVisibilityPaintedStatement(statement)) {
        const key = getOriginalNodeId(statement);
        if (lateStatementReplacementMap.has(key)) {
          const result = lateStatementReplacementMap.get(key);
          lateStatementReplacementMap.delete(key);
          if (result) {
            if (isArray(result) ? some(result, needsScopeMarker) : needsScopeMarker(result)) {
              needsScopeFixMarker = true;
            }
            if (isSourceFile(statement.parent) && (isArray(result) ? some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result))) {
              resultHasExternalModuleIndicator = true;
            }
          }
          return result;
        }
      }
      return statement;
    }
  }
  function visitDeclarationSubtree(input) {
    if (shouldStripInternal(input))
      return;
    if (isDeclaration(input)) {
      if (isDeclarationAndNotVisible(input))
        return;
      if (hasDynamicName(input) && !resolver.isLateBound(getParseTreeNode(input))) {
        return;
      }
    }
    if (isFunctionLike(input) && resolver.isImplementationOfOverload(input))
      return;
    if (isSemicolonClassElement(input))
      return;
    let previousEnclosingDeclaration;
    if (isEnclosingDeclaration(input)) {
      previousEnclosingDeclaration = enclosingDeclaration;
      enclosingDeclaration = input;
    }
    const oldDiag = getSymbolAccessibilityDiagnostic;
    const canProduceDiagnostic = canProduceDiagnostics(input);
    const oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
    let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 186 /* TypeLiteral */ || input.kind === 199 /* MappedType */) && input.parent.kind !== 264 /* TypeAliasDeclaration */;
    if (isMethodDeclaration(input) || isMethodSignature(input)) {
      if (hasEffectiveModifier(input, 8 /* Private */)) {
        if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
          return;
        return cleanup(factory2.createPropertyDeclaration(
          ensureModifiers(input),
          input.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        ));
      }
    }
    if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input);
    }
    if (isTypeQueryNode(input)) {
      checkEntityNameVisibility(input.exprName, enclosingDeclaration);
    }
    if (shouldEnterSuppressNewDiagnosticsContextContext) {
      suppressNewDiagnosticContexts = true;
    }
    if (isProcessedComponent(input)) {
      switch (input.kind) {
        case 232 /* ExpressionWithTypeArguments */: {
          if (isEntityName(input.expression) || isEntityNameExpression(input.expression)) {
            checkEntityNameVisibility(input.expression, enclosingDeclaration);
          }
          const node = visitEachChild(input, visitDeclarationSubtree, context);
          return cleanup(factory2.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
        }
        case 182 /* TypeReference */: {
          checkEntityNameVisibility(input.typeName, enclosingDeclaration);
          const node = visitEachChild(input, visitDeclarationSubtree, context);
          return cleanup(factory2.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
        }
        case 179 /* ConstructSignature */:
          return cleanup(factory2.updateConstructSignature(
            input,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input, input.type)
          ));
        case 175 /* Constructor */: {
          const ctor = factory2.createConstructorDeclaration(
            /*modifiers*/
            ensureModifiers(input),
            updateParamsList(input, input.parameters, 0 /* None */),
            /*body*/
            void 0
          );
          return cleanup(ctor);
        }
        case 173 /* MethodDeclaration */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          const sig = factory2.createMethodDeclaration(
            ensureModifiers(input),
            /*asteriskToken*/
            void 0,
            input.name,
            input.questionToken,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input, input.type),
            /*body*/
            void 0
          );
          return cleanup(sig);
        }
        case 176 /* GetAccessor */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
          return cleanup(factory2.updateGetAccessorDeclaration(
            input,
            ensureModifiers(input),
            input.name,
            updateAccessorParamsList(input, hasEffectiveModifier(input, 8 /* Private */)),
            ensureType(input, accessorType),
            /*body*/
            void 0
          ));
        }
        case 177 /* SetAccessor */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updateSetAccessorDeclaration(
            input,
            ensureModifiers(input),
            input.name,
            updateAccessorParamsList(input, hasEffectiveModifier(input, 8 /* Private */)),
            /*body*/
            void 0
          ));
        }
        case 171 /* PropertyDeclaration */:
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updatePropertyDeclaration(
            input,
            ensureModifiers(input),
            input.name,
            input.questionToken,
            ensureType(input, input.type),
            ensureNoInitializer(input)
          ));
        case 170 /* PropertySignature */:
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updatePropertySignature(
            input,
            ensureModifiers(input),
            input.name,
            input.questionToken,
            ensureType(input, input.type)
          ));
        case 172 /* MethodSignature */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updateMethodSignature(
            input,
            ensureModifiers(input),
            input.name,
            input.questionToken,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input, input.type)
          ));
        }
        case 178 /* CallSignature */: {
          return cleanup(factory2.updateCallSignature(
            input,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input, input.type)
          ));
        }
        case 180 /* IndexSignature */: {
          return cleanup(factory2.updateIndexSignature(
            input,
            ensureModifiers(input),
            updateParamsList(input, input.parameters),
            visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(133 /* AnyKeyword */)
          ));
        }
        case 259 /* VariableDeclaration */: {
          if (isBindingPattern(input.name)) {
            return recreateBindingPattern(input.name);
          }
          shouldEnterSuppressNewDiagnosticsContextContext = true;
          suppressNewDiagnosticContexts = true;
          return cleanup(factory2.updateVariableDeclaration(
            input,
            input.name,
            /*exclamationToken*/
            void 0,
            ensureType(input, input.type),
            ensureNoInitializer(input)
          ));
        }
        case 167 /* TypeParameter */: {
          if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
            return cleanup(factory2.updateTypeParameterDeclaration(
              input,
              input.modifiers,
              input.name,
              /*constraint*/
              void 0,
              /*defaultType*/
              void 0
            ));
          }
          return cleanup(visitEachChild(input, visitDeclarationSubtree, context));
        }
        case 193 /* ConditionalType */: {
          const checkType = visitNode(input.checkType, visitDeclarationSubtree, isTypeNode);
          const extendsType = visitNode(input.extendsType, visitDeclarationSubtree, isTypeNode);
          const oldEnclosingDecl = enclosingDeclaration;
          enclosingDeclaration = input.trueType;
          const trueType = visitNode(input.trueType, visitDeclarationSubtree, isTypeNode);
          enclosingDeclaration = oldEnclosingDecl;
          const falseType = visitNode(input.falseType, visitDeclarationSubtree, isTypeNode);
          Debug.assert(checkType);
          Debug.assert(extendsType);
          Debug.assert(trueType);
          Debug.assert(falseType);
          return cleanup(factory2.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
        }
        case 183 /* FunctionType */: {
          return cleanup(factory2.updateFunctionTypeNode(input, visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode))));
        }
        case 184 /* ConstructorType */: {
          return cleanup(factory2.updateConstructorTypeNode(input, ensureModifiers(input), visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode))));
        }
        case 204 /* ImportType */: {
          if (!isLiteralImportTypeNode(input))
            return cleanup(input);
          return cleanup(factory2.updateImportTypeNode(
            input,
            factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)),
            input.assertions,
            input.qualifier,
            visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode),
            input.isTypeOf
          ));
        }
        default:
          Debug.assertNever(input, `Attempted to process unhandled node kind: ${Debug.formatSyntaxKind(input.kind)}`);
      }
    }
    if (isTupleTypeNode(input) && getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === getLineAndCharacterOfPosition(currentSourceFile, input.end).line) {
      setEmitFlags(input, 1 /* SingleLine */);
    }
    return cleanup(visitEachChild(input, visitDeclarationSubtree, context));
    function cleanup(returnValue) {
      if (returnValue && canProduceDiagnostic && hasDynamicName(input)) {
        checkName(input);
      }
      if (isEnclosingDeclaration(input)) {
        enclosingDeclaration = previousEnclosingDeclaration;
      }
      if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
        getSymbolAccessibilityDiagnostic = oldDiag;
      }
      if (shouldEnterSuppressNewDiagnosticsContextContext) {
        suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
      }
      if (returnValue === input) {
        return returnValue;
      }
      return returnValue && setOriginalNode(preserveJsDoc(returnValue, input), input);
    }
  }
  function isPrivateMethodTypeParameter(node) {
    return node.parent.kind === 173 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 8 /* Private */);
  }
  function visitDeclarationStatements(input) {
    if (!isPreservedDeclarationStatement(input)) {
      return;
    }
    if (shouldStripInternal(input))
      return;
    switch (input.kind) {
      case 277 /* ExportDeclaration */: {
        if (isSourceFile(input.parent)) {
          resultHasExternalModuleIndicator = true;
        }
        resultHasScopeMarker = true;
        return factory2.updateExportDeclaration(
          input,
          input.modifiers,
          input.isTypeOnly,
          input.exportClause,
          rewriteModuleSpecifier(input, input.moduleSpecifier),
          getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : void 0
        );
      }
      case 276 /* ExportAssignment */: {
        if (isSourceFile(input.parent)) {
          resultHasExternalModuleIndicator = true;
        }
        resultHasScopeMarker = true;
        if (input.expression.kind === 80 /* Identifier */) {
          return input;
        } else {
          const newId = factory2.createUniqueName("_default", 16 /* Optimistic */);
          getSymbolAccessibilityDiagnostic = () => ({
            diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
            errorNode: input
          });
          errorFallbackNode = input;
          const varDecl = factory2.createVariableDeclaration(
            newId,
            /*exclamationToken*/
            void 0,
            resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker),
            /*initializer*/
            void 0
          );
          errorFallbackNode = void 0;
          const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */));
          preserveJsDoc(statement, input);
          removeAllComments(input);
          return [statement, factory2.updateExportAssignment(input, input.modifiers, newId)];
        }
      }
    }
    const result = transformTopLevelDeclaration(input);
    lateStatementReplacementMap.set(getOriginalNodeId(input), result);
    return input;
  }
  function stripExportModifiers(statement) {
    if (isImportEqualsDeclaration(statement) || hasEffectiveModifier(statement, 1024 /* Default */) || !canHaveModifiers(statement)) {
      return statement;
    }
    const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(statement) & (258047 /* All */ ^ 1 /* Export */));
    return factory2.updateModifiers(statement, modifiers);
  }
  function transformTopLevelDeclaration(input) {
    if (lateMarkedStatements) {
      while (orderedRemoveItem(lateMarkedStatements, input))
        ;
    }
    if (shouldStripInternal(input))
      return;
    switch (input.kind) {
      case 270 /* ImportEqualsDeclaration */: {
        return transformImportEqualsDeclaration(input);
      }
      case 271 /* ImportDeclaration */: {
        return transformImportDeclaration(input);
      }
    }
    if (isDeclaration(input) && isDeclarationAndNotVisible(input))
      return;
    if (isFunctionLike(input) && resolver.isImplementationOfOverload(input))
      return;
    let previousEnclosingDeclaration;
    if (isEnclosingDeclaration(input)) {
      previousEnclosingDeclaration = enclosingDeclaration;
      enclosingDeclaration = input;
    }
    const canProdiceDiagnostic = canProduceDiagnostics(input);
    const oldDiag = getSymbolAccessibilityDiagnostic;
    if (canProdiceDiagnostic) {
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input);
    }
    const previousNeedsDeclare = needsDeclare;
    switch (input.kind) {
      case 264 /* TypeAliasDeclaration */: {
        needsDeclare = false;
        const clean2 = cleanup(factory2.updateTypeAliasDeclaration(
          input,
          ensureModifiers(input),
          input.name,
          visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration),
          Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode))
        ));
        needsDeclare = previousNeedsDeclare;
        return clean2;
      }
      case 263 /* InterfaceDeclaration */: {
        return cleanup(factory2.updateInterfaceDeclaration(
          input,
          ensureModifiers(input),
          input.name,
          ensureTypeParams(input, input.typeParameters),
          transformHeritageClauses(input.heritageClauses),
          visitNodes2(input.members, visitDeclarationSubtree, isTypeElement)
        ));
      }
      case 261 /* FunctionDeclaration */: {
        const clean2 = cleanup(factory2.updateFunctionDeclaration(
          input,
          ensureModifiers(input),
          /*asteriskToken*/
          void 0,
          input.name,
          ensureTypeParams(input, input.typeParameters),
          updateParamsList(input, input.parameters),
          ensureType(input, input.type),
          /*body*/
          void 0
        ));
        if (clean2 && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) {
          const props = resolver.getPropertiesOfContainerFunction(input);
          const fakespace = parseNodeFactory.createModuleDeclaration(
            /*modifiers*/
            void 0,
            clean2.name || factory2.createIdentifier("_default"),
            factory2.createModuleBlock([]),
            16 /* Namespace */
          );
          setParent(fakespace, enclosingDeclaration);
          fakespace.locals = createSymbolTable(props);
          fakespace.symbol = props[0].parent;
          const exportMappings = [];
          let declarations = mapDefined(props, (p) => {
            if (!p.valueDeclaration || !(isPropertyAccessExpression(p.valueDeclaration) || isElementAccessExpression(p.valueDeclaration) || isBinaryExpression(p.valueDeclaration))) {
              return void 0;
            }
            const nameStr = unescapeLeadingUnderscores(p.escapedName);
            if (!isIdentifierText(nameStr, 99 /* ESNext */)) {
              return void 0;
            }
            getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
            const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, symbolTracker);
            getSymbolAccessibilityDiagnostic = oldDiag;
            const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr);
            const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr);
            if (isNonContextualKeywordName) {
              exportMappings.push([name, nameStr]);
            }
            const varDecl = factory2.createVariableDeclaration(
              name,
              /*exclamationToken*/
              void 0,
              type,
              /*initializer*/
              void 0
            );
            return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [factory2.createToken(95 /* ExportKeyword */)], factory2.createVariableDeclarationList([varDecl]));
          });
          if (!exportMappings.length) {
            declarations = mapDefined(declarations, (declaration) => factory2.updateModifiers(declaration, 0 /* None */));
          } else {
            declarations.push(factory2.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory2.createNamedExports(map(exportMappings, ([gen, exp]) => {
                return factory2.createExportSpecifier(
                  /*isTypeOnly*/
                  false,
                  gen,
                  exp
                );
              }))
            ));
          }
          const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 16 /* Namespace */);
          if (!hasEffectiveModifier(clean2, 1024 /* Default */)) {
            return [clean2, namespaceDecl];
          }
          const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~1025 /* ExportDefault */ | 2 /* Ambient */);
          const cleanDeclaration = factory2.updateFunctionDeclaration(
            clean2,
            modifiers,
            /*asteriskToken*/
            void 0,
            clean2.name,
            clean2.typeParameters,
            clean2.parameters,
            clean2.type,
            /*body*/
            void 0
          );
          const namespaceDeclaration = factory2.updateModuleDeclaration(
            namespaceDecl,
            modifiers,
            namespaceDecl.name,
            namespaceDecl.body
          );
          const exportDefaultDeclaration = factory2.createExportAssignment(
            /*modifiers*/
            void 0,
            /*isExportEquals*/
            false,
            namespaceDecl.name
          );
          if (isSourceFile(input.parent)) {
            resultHasExternalModuleIndicator = true;
          }
          resultHasScopeMarker = true;
          return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
        } else {
          return clean2;
        }
      }
      case 266 /* ModuleDeclaration */: {
        needsDeclare = false;
        const inner = input.body;
        if (inner && inner.kind === 267 /* ModuleBlock */) {
          const oldNeedsScopeFix = needsScopeFixMarker;
          const oldHasScopeFix = resultHasScopeMarker;
          resultHasScopeMarker = false;
          needsScopeFixMarker = false;
          const statements = visitNodes2(inner.statements, visitDeclarationStatements, isStatement);
          let lateStatements = transformAndReplaceLatePaintedStatements(statements);
          if (input.flags & 16777216 /* Ambient */) {
            needsScopeFixMarker = false;
          }
          if (!isGlobalScopeAugmentation(input) && !hasScopeMarker2(lateStatements) && !resultHasScopeMarker) {
            if (needsScopeFixMarker) {
              lateStatements = factory2.createNodeArray([...lateStatements, createEmptyExports(factory2)]);
            } else {
              lateStatements = visitNodes2(lateStatements, stripExportModifiers, isStatement);
            }
          }
          const body = factory2.updateModuleBlock(inner, lateStatements);
          needsDeclare = previousNeedsDeclare;
          needsScopeFixMarker = oldNeedsScopeFix;
          resultHasScopeMarker = oldHasScopeFix;
          const mods = ensureModifiers(input);
          return cleanup(factory2.updateModuleDeclaration(
            input,
            mods,
            isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name,
            body
          ));
        } else {
          needsDeclare = previousNeedsDeclare;
          const mods = ensureModifiers(input);
          needsDeclare = false;
          visitNode(inner, visitDeclarationStatements);
          const id = getOriginalNodeId(inner);
          const body = lateStatementReplacementMap.get(id);
          lateStatementReplacementMap.delete(id);
          return cleanup(factory2.updateModuleDeclaration(
            input,
            mods,
            input.name,
            body
          ));
        }
      }
      case 262 /* ClassDeclaration */: {
        errorNameNode = input.name;
        errorFallbackNode = input;
        const modifiers = factory2.createNodeArray(ensureModifiers(input));
        const typeParameters = ensureTypeParams(input, input.typeParameters);
        const ctor = getFirstConstructorWithBody(input);
        let parameterProperties;
        if (ctor) {
          const oldDiag2 = getSymbolAccessibilityDiagnostic;
          parameterProperties = compact(flatMap(ctor.parameters, (param) => {
            if (!hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param))
              return;
            getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param);
            if (param.name.kind === 80 /* Identifier */) {
              return preserveJsDoc(factory2.createPropertyDeclaration(
                ensureModifiers(param),
                param.name,
                param.questionToken,
                ensureType(param, param.type),
                ensureNoInitializer(param)
              ), param);
            } else {
              return walkBindingPattern(param.name);
            }
            function walkBindingPattern(pattern) {
              let elems;
              for (const elem of pattern.elements) {
                if (isOmittedExpression(elem))
                  continue;
                if (isBindingPattern(elem.name)) {
                  elems = concatenate(elems, walkBindingPattern(elem.name));
                }
                elems = elems || [];
                elems.push(factory2.createPropertyDeclaration(
                  ensureModifiers(param),
                  elem.name,
                  /*questionOrExclamationToken*/
                  void 0,
                  ensureType(
                    elem,
                    /*type*/
                    void 0
                  ),
                  /*initializer*/
                  void 0
                ));
              }
              return elems;
            }
          }));
          getSymbolAccessibilityDiagnostic = oldDiag2;
        }
        const hasPrivateIdentifier = some(input.members, (member) => !!member.name && isPrivateIdentifier(member.name));
        const privateIdentifier = hasPrivateIdentifier ? [
          factory2.createPropertyDeclaration(
            /*modifiers*/
            void 0,
            factory2.createPrivateIdentifier("#private"),
            /*questionOrExclamationToken*/
            void 0,
            /*type*/
            void 0,
            /*initializer*/
            void 0
          )
        ] : void 0;
        const memberNodes = concatenate(concatenate(privateIdentifier, parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement));
        const members = factory2.createNodeArray(memberNodes);
        const extendsClause = getEffectiveBaseTypeNode(input);
        if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */) {
          const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default";
          const newId = factory2.createUniqueName(`${oldId}_base`, 16 /* Optimistic */);
          getSymbolAccessibilityDiagnostic = () => ({
            diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
            errorNode: extendsClause,
            typeName: input.name
          });
          const varDecl = factory2.createVariableDeclaration(
            newId,
            /*exclamationToken*/
            void 0,
            resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker),
            /*initializer*/
            void 0
          );
          const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */));
          const heritageClauses = factory2.createNodeArray(map(input.heritageClauses, (clause) => {
            if (clause.token === 96 /* ExtendsKeyword */) {
              const oldDiag2 = getSymbolAccessibilityDiagnostic;
              getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
              const newClause = factory2.updateHeritageClause(clause, map(clause.types, (t) => factory2.updateExpressionWithTypeArguments(t, newId, visitNodes2(t.typeArguments, visitDeclarationSubtree, isTypeNode))));
              getSymbolAccessibilityDiagnostic = oldDiag2;
              return newClause;
            }
            return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */)), visitDeclarationSubtree, isExpressionWithTypeArguments));
          }));
          return [statement, cleanup(factory2.updateClassDeclaration(
            input,
            modifiers,
            input.name,
            typeParameters,
            heritageClauses,
            members
          ))];
        } else {
          const heritageClauses = transformHeritageClauses(input.heritageClauses);
          return cleanup(factory2.updateClassDeclaration(
            input,
            modifiers,
            input.name,
            typeParameters,
            heritageClauses,
            members
          ));
        }
      }
      case 242 /* VariableStatement */: {
        return cleanup(transformVariableStatement(input));
      }
      case 265 /* EnumDeclaration */: {
        return cleanup(factory2.updateEnumDeclaration(input, factory2.createNodeArray(ensureModifiers(input)), input.name, factory2.createNodeArray(mapDefined(input.members, (m) => {
          if (shouldStripInternal(m))
            return;
          const constValue = resolver.getConstantValue(m);
          return preserveJsDoc(factory2.updateEnumMember(m, m.name, constValue !== void 0 ? typeof constValue === "string" ? factory2.createStringLiteral(constValue) : factory2.createNumericLiteral(constValue) : void 0), m);
        }))));
      }
    }
    return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${Debug.formatSyntaxKind(input.kind)}`);
    function cleanup(node) {
      if (isEnclosingDeclaration(input)) {
        enclosingDeclaration = previousEnclosingDeclaration;
      }
      if (canProdiceDiagnostic) {
        getSymbolAccessibilityDiagnostic = oldDiag;
      }
      if (input.kind === 266 /* ModuleDeclaration */) {
        needsDeclare = previousNeedsDeclare;
      }
      if (node === input) {
        return node;
      }
      errorFallbackNode = void 0;
      errorNameNode = void 0;
      return node && setOriginalNode(preserveJsDoc(node, input), input);
    }
  }
  function transformVariableStatement(input) {
    if (!forEach(input.declarationList.declarations, getBindingNameVisible))
      return;
    const nodes = visitNodes2(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration);
    if (!length(nodes))
      return;
    return factory2.updateVariableStatement(input, factory2.createNodeArray(ensureModifiers(input)), factory2.updateVariableDeclarationList(input.declarationList, nodes));
  }
  function recreateBindingPattern(d) {
    return flatten(mapDefined(d.elements, (e) => recreateBindingElement(e)));
  }
  function recreateBindingElement(e) {
    if (e.kind === 231 /* OmittedExpression */) {
      return;
    }
    if (e.name) {
      if (!getBindingNameVisible(e))
        return;
      if (isBindingPattern(e.name)) {
        return recreateBindingPattern(e.name);
      } else {
        return factory2.createVariableDeclaration(
          e.name,
          /*exclamationToken*/
          void 0,
          ensureType(
            e,
            /*type*/
            void 0
          ),
          /*initializer*/
          void 0
        );
      }
    }
  }
  function checkName(node) {
    let oldDiag;
    if (!suppressNewDiagnosticContexts) {
      oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node);
    }
    errorNameNode = node.name;
    Debug.assert(resolver.isLateBound(getParseTreeNode(node)));
    const decl = node;
    const entityName = decl.name.expression;
    checkEntityNameVisibility(entityName, enclosingDeclaration);
    if (!suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = oldDiag;
    }
    errorNameNode = void 0;
  }
  function shouldStripInternal(node) {
    return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
  }
  function isScopeMarker2(node) {
    return isExportAssignment(node) || isExportDeclaration(node);
  }
  function hasScopeMarker2(statements) {
    return some(statements, isScopeMarker2);
  }
  function ensureModifiers(node) {
    const currentFlags = getEffectiveModifierFlags(node);
    const newFlags = ensureModifierFlags(node);
    if (currentFlags === newFlags) {
      return visitArray(node.modifiers, (n) => tryCast(n, isModifier), isModifier);
    }
    return factory2.createModifiersFromModifierFlags(newFlags);
  }
  function ensureModifierFlags(node) {
    let mask2 = 258047 /* All */ ^ (4 /* Public */ | 512 /* Async */ | 16384 /* Override */);
    let additions = needsDeclare && !isAlwaysType(node) ? 2 /* Ambient */ : 0 /* None */;
    const parentIsFile = node.parent.kind === 311 /* SourceFile */;
    if (!parentIsFile || isBundledEmit && parentIsFile && isExternalModule(node.parent)) {
      mask2 ^= 2 /* Ambient */;
      additions = 0 /* None */;
    }
    return maskModifierFlags(node, mask2, additions);
  }
  function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
    let accessorType = getTypeAnnotationFromAccessor(node);
    if (!accessorType && node !== accessors.firstAccessor) {
      accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
    }
    if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
      accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
    }
    return accessorType;
  }
  function transformHeritageClauses(nodes) {
    return factory2.createNodeArray(filter(map(nodes, (clause) => factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => {
      return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */;
    })), visitDeclarationSubtree, isExpressionWithTypeArguments))), (clause) => clause.types && !!clause.types.length));
  }
}
function isAlwaysType(node) {
  if (node.kind === 263 /* InterfaceDeclaration */) {
    return true;
  }
  return false;
}
function maskModifiers(factory2, node, modifierMask, modifierAdditions) {
  return factory2.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
}
function maskModifierFlags(node, modifierMask = 258047 /* All */ ^ 4 /* Public */, modifierAdditions = 0 /* None */) {
  let flags = getEffectiveModifierFlags(node) & modifierMask | modifierAdditions;
  if (flags & 1024 /* Default */ && !(flags & 1 /* Export */)) {
    flags ^= 1 /* Export */;
  }
  if (flags & 1024 /* Default */ && flags & 2 /* Ambient */) {
    flags ^= 2 /* Ambient */;
  }
  return flags;
}
function getTypeAnnotationFromAccessor(accessor) {
  if (accessor) {
    return accessor.kind === 176 /* GetAccessor */ ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : void 0;
  }
}
function canHaveLiteralInitializer(node) {
  switch (node.kind) {
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
      return !hasEffectiveModifier(node, 8 /* Private */);
    case 168 /* Parameter */:
    case 259 /* VariableDeclaration */:
      return true;
  }
  return false;
}
function isPreservedDeclarationStatement(node) {
  switch (node.kind) {
    case 261 /* FunctionDeclaration */:
    case 266 /* ModuleDeclaration */:
    case 270 /* ImportEqualsDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 262 /* ClassDeclaration */:
    case 264 /* TypeAliasDeclaration */:
    case 265 /* EnumDeclaration */:
    case 242 /* VariableStatement */:
    case 271 /* ImportDeclaration */:
    case 277 /* ExportDeclaration */:
    case 276 /* ExportAssignment */:
      return true;
  }
  return false;
}
function isProcessedComponent(node) {
  switch (node.kind) {
    case 179 /* ConstructSignature */:
    case 175 /* Constructor */:
    case 173 /* MethodDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
    case 172 /* MethodSignature */:
    case 178 /* CallSignature */:
    case 180 /* IndexSignature */:
    case 259 /* VariableDeclaration */:
    case 167 /* TypeParameter */:
    case 232 /* ExpressionWithTypeArguments */:
    case 182 /* TypeReference */:
    case 193 /* ConditionalType */:
    case 183 /* FunctionType */:
    case 184 /* ConstructorType */:
    case 204 /* ImportType */:
      return true;
  }
  return false;
}

// src/compiler/transformer.ts
function getModuleTransformer(moduleKind) {
  switch (moduleKind) {
    case 99 /* ESNext */:
    case 7 /* ES2022 */:
    case 6 /* ES2020 */:
    case 5 /* ES2015 */:
      return transformECMAScriptModule;
    case 4 /* System */:
      return transformSystemModule;
    case 100 /* Node16 */:
    case 199 /* NodeNext */:
      return transformNodeModule;
    default:
      return transformModule;
  }
}
var noTransformers = { scriptTransformers: emptyArray, declarationTransformers: emptyArray };
function getTransformers(compilerOptions, customTransformers, emitOnly) {
  return {
    scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnly),
    declarationTransformers: getDeclarationTransformers(customTransformers)
  };
}
function getScriptTransformers(compilerOptions, customTransformers, emitOnly) {
  if (emitOnly)
    return emptyArray;
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const moduleKind = getEmitModuleKind(compilerOptions);
  const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
  const transformers = [];
  addRange(transformers, customTransformers && map(customTransformers.before, wrapScriptTransformerFactory));
  transformers.push(transformTypeScript);
  if (compilerOptions.experimentalDecorators) {
    transformers.push(transformLegacyDecorators);
  } else if (languageVersion < 99 /* ESNext */ || !useDefineForClassFields) {
    transformers.push(transformESDecorators);
  }
  transformers.push(transformClassFields);
  if (getJSXTransformEnabled(compilerOptions)) {
    transformers.push(transformJsx);
  }
  if (languageVersion < 99 /* ESNext */) {
    transformers.push(transformESNext);
  }
  if (languageVersion < 8 /* ES2021 */) {
    transformers.push(transformES2021);
  }
  if (languageVersion < 7 /* ES2020 */) {
    transformers.push(transformES2020);
  }
  if (languageVersion < 6 /* ES2019 */) {
    transformers.push(transformES2019);
  }
  if (languageVersion < 5 /* ES2018 */) {
    transformers.push(transformES2018);
  }
  if (languageVersion < 4 /* ES2017 */) {
    transformers.push(transformES2017);
  }
  if (languageVersion < 3 /* ES2016 */) {
    transformers.push(transformES2016);
  }
  if (languageVersion < 2 /* ES2015 */) {
    transformers.push(transformES2015);
    transformers.push(transformGenerators);
  }
  transformers.push(getModuleTransformer(moduleKind));
  if (languageVersion < 1 /* ES5 */) {
    transformers.push(transformES5);
  }
  addRange(transformers, customTransformers && map(customTransformers.after, wrapScriptTransformerFactory));
  return transformers;
}
function getDeclarationTransformers(customTransformers) {
  const transformers = [];
  transformers.push(transformDeclarations);
  addRange(transformers, customTransformers && map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
  return transformers;
}
function wrapCustomTransformer(transformer) {
  return (node) => isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node);
}
function wrapCustomTransformerFactory(transformer, handleDefault) {
  return (context) => {
    const customTransformer = transformer(context);
    return typeof customTransformer === "function" ? handleDefault(context, customTransformer) : wrapCustomTransformer(customTransformer);
  };
}
function wrapScriptTransformerFactory(transformer) {
  return wrapCustomTransformerFactory(transformer, chainBundle);
}
function wrapDeclarationTransformerFactory(transformer) {
  return wrapCustomTransformerFactory(transformer, (_, node) => node);
}
function noEmitSubstitution(_hint, node) {
  return node;
}
function noEmitNotification(hint, node, callback) {
  callback(hint, node);
}
function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) {
  var _a, _b;
  const enabledSyntaxKindFeatures = new Array(362 /* Count */);
  let lexicalEnvironmentVariableDeclarations;
  let lexicalEnvironmentFunctionDeclarations;
  let lexicalEnvironmentStatements;
  let lexicalEnvironmentFlags = 0 /* None */;
  let lexicalEnvironmentVariableDeclarationsStack = [];
  let lexicalEnvironmentFunctionDeclarationsStack = [];
  let lexicalEnvironmentStatementsStack = [];
  let lexicalEnvironmentFlagsStack = [];
  let lexicalEnvironmentStackOffset = 0;
  let lexicalEnvironmentSuspended = false;
  let blockScopedVariableDeclarationsStack = [];
  let blockScopeStackOffset = 0;
  let blockScopedVariableDeclarations;
  let emitHelpers;
  let onSubstituteNode = noEmitSubstitution;
  let onEmitNode = noEmitNotification;
  let state = 0 /* Uninitialized */;
  const diagnostics = [];
  const context = {
    factory: factory2,
    getCompilerOptions: () => options,
    getEmitResolver: () => resolver,
    // TODO: GH#18217
    getEmitHost: () => host,
    // TODO: GH#18217
    getEmitHelperFactory: memoize(() => createEmitHelperFactory(context)),
    startLexicalEnvironment,
    suspendLexicalEnvironment,
    resumeLexicalEnvironment,
    endLexicalEnvironment,
    setLexicalEnvironmentFlags,
    getLexicalEnvironmentFlags,
    hoistVariableDeclaration,
    hoistFunctionDeclaration,
    addInitializationStatement,
    startBlockScope,
    endBlockScope,
    addBlockScopedVariable,
    requestEmitHelper,
    readEmitHelpers,
    enableSubstitution,
    enableEmitNotification,
    isSubstitutionEnabled,
    isEmitNotificationEnabled,
    get onSubstituteNode() {
      return onSubstituteNode;
    },
    set onSubstituteNode(value) {
      Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
      Debug.assert(value !== void 0, "Value must not be 'undefined'");
      onSubstituteNode = value;
    },
    get onEmitNode() {
      return onEmitNode;
    },
    set onEmitNode(value) {
      Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
      Debug.assert(value !== void 0, "Value must not be 'undefined'");
      onEmitNode = value;
    },
    addDiagnostic(diag2) {
      diagnostics.push(diag2);
    }
  };
  for (const node of nodes) {
    disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node)));
  }
  mark("beforeTransform");
  const transformersWithContext = transformers.map((t) => t(context));
  const transformation = (node) => {
    for (const transform2 of transformersWithContext) {
      node = transform2(node);
    }
    return node;
  };
  state = 1 /* Initialized */;
  const transformed = [];
  for (const node of nodes) {
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "transformNodes", node.kind === 311 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
    transformed.push((allowDtsFiles ? transformation : transformRoot)(node));
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  state = 2 /* Completed */;
  mark("afterTransform");
  measure("transformTime", "beforeTransform", "afterTransform");
  return {
    transformed,
    substituteNode,
    emitNodeWithNotification,
    isEmitNotificationEnabled,
    dispose,
    diagnostics
  };
  function transformRoot(node) {
    return node && (!isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
  }
  function enableSubstitution(kind) {
    Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
    enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
  }
  function isSubstitutionEnabled(node) {
    return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 && (getEmitFlags(node) & 8 /* NoSubstitution */) === 0;
  }
  function substituteNode(hint, node) {
    Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
    return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
  }
  function enableEmitNotification(kind) {
    Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
    enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
  }
  function isEmitNotificationEnabled(node) {
    return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 || (getEmitFlags(node) & 4 /* AdviseOnEmitNode */) !== 0;
  }
  function emitNodeWithNotification(hint, node, emitCallback) {
    Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
    if (node) {
      if (isEmitNotificationEnabled(node)) {
        onEmitNode(hint, node, emitCallback);
      } else {
        emitCallback(hint, node);
      }
    }
  }
  function hoistVariableDeclaration(name) {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    const decl = setEmitFlags(factory2.createVariableDeclaration(name), 128 /* NoNestedSourceMaps */);
    if (!lexicalEnvironmentVariableDeclarations) {
      lexicalEnvironmentVariableDeclarations = [decl];
    } else {
      lexicalEnvironmentVariableDeclarations.push(decl);
    }
    if (lexicalEnvironmentFlags & 1 /* InParameters */) {
      lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
    }
  }
  function hoistFunctionDeclaration(func) {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    setEmitFlags(func, 2097152 /* CustomPrologue */);
    if (!lexicalEnvironmentFunctionDeclarations) {
      lexicalEnvironmentFunctionDeclarations = [func];
    } else {
      lexicalEnvironmentFunctionDeclarations.push(func);
    }
  }
  function addInitializationStatement(node) {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    setEmitFlags(node, 2097152 /* CustomPrologue */);
    if (!lexicalEnvironmentStatements) {
      lexicalEnvironmentStatements = [node];
    } else {
      lexicalEnvironmentStatements.push(node);
    }
  }
  function startLexicalEnvironment() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
    lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
    lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
    lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
    lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
    lexicalEnvironmentStackOffset++;
    lexicalEnvironmentVariableDeclarations = void 0;
    lexicalEnvironmentFunctionDeclarations = void 0;
    lexicalEnvironmentStatements = void 0;
    lexicalEnvironmentFlags = 0 /* None */;
  }
  function suspendLexicalEnvironment() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
    lexicalEnvironmentSuspended = true;
  }
  function resumeLexicalEnvironment() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
    lexicalEnvironmentSuspended = false;
  }
  function endLexicalEnvironment() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
    Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
    let statements;
    if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations || lexicalEnvironmentStatements) {
      if (lexicalEnvironmentFunctionDeclarations) {
        statements = [...lexicalEnvironmentFunctionDeclarations];
      }
      if (lexicalEnvironmentVariableDeclarations) {
        const statement = factory2.createVariableStatement(
          /*modifiers*/
          void 0,
          factory2.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)
        );
        setEmitFlags(statement, 2097152 /* CustomPrologue */);
        if (!statements) {
          statements = [statement];
        } else {
          statements.push(statement);
        }
      }
      if (lexicalEnvironmentStatements) {
        if (!statements) {
          statements = [...lexicalEnvironmentStatements];
        } else {
          statements = [...statements, ...lexicalEnvironmentStatements];
        }
      }
    }
    lexicalEnvironmentStackOffset--;
    lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
    lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
    lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
    lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
    if (lexicalEnvironmentStackOffset === 0) {
      lexicalEnvironmentVariableDeclarationsStack = [];
      lexicalEnvironmentFunctionDeclarationsStack = [];
      lexicalEnvironmentStatementsStack = [];
      lexicalEnvironmentFlagsStack = [];
    }
    return statements;
  }
  function setLexicalEnvironmentFlags(flags, value) {
    lexicalEnvironmentFlags = value ? lexicalEnvironmentFlags | flags : lexicalEnvironmentFlags & ~flags;
  }
  function getLexicalEnvironmentFlags() {
    return lexicalEnvironmentFlags;
  }
  function startBlockScope() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed.");
    blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations;
    blockScopeStackOffset++;
    blockScopedVariableDeclarations = void 0;
  }
  function endBlockScope() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed.");
    const statements = some(blockScopedVariableDeclarations) ? [
      factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList(
          blockScopedVariableDeclarations.map((identifier) => factory2.createVariableDeclaration(identifier)),
          1 /* Let */
        )
      )
    ] : void 0;
    blockScopeStackOffset--;
    blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset];
    if (blockScopeStackOffset === 0) {
      blockScopedVariableDeclarationsStack = [];
    }
    return statements;
  }
  function addBlockScopedVariable(name) {
    Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body.");
    (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name);
  }
  function requestEmitHelper(helper) {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
    Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
    if (helper.dependencies) {
      for (const h of helper.dependencies) {
        requestEmitHelper(h);
      }
    }
    emitHelpers = append(emitHelpers, helper);
  }
  function readEmitHelpers() {
    Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
    Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
    const helpers = emitHelpers;
    emitHelpers = void 0;
    return helpers;
  }
  function dispose() {
    if (state < 3 /* Disposed */) {
      for (const node of nodes) {
        disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node)));
      }
      lexicalEnvironmentVariableDeclarations = void 0;
      lexicalEnvironmentVariableDeclarationsStack = void 0;
      lexicalEnvironmentFunctionDeclarations = void 0;
      lexicalEnvironmentFunctionDeclarationsStack = void 0;
      onSubstituteNode = void 0;
      onEmitNode = void 0;
      emitHelpers = void 0;
      state = 3 /* Disposed */;
    }
  }
}
var nullTransformationContext = {
  factory,
  // eslint-disable-line object-shorthand
  getCompilerOptions: () => ({}),
  getEmitResolver: notImplemented,
  getEmitHost: notImplemented,
  getEmitHelperFactory: notImplemented,
  startLexicalEnvironment: noop,
  resumeLexicalEnvironment: noop,
  suspendLexicalEnvironment: noop,
  endLexicalEnvironment: returnUndefined,
  setLexicalEnvironmentFlags: noop,
  getLexicalEnvironmentFlags: () => 0,
  hoistVariableDeclaration: noop,
  hoistFunctionDeclaration: noop,
  addInitializationStatement: noop,
  startBlockScope: noop,
  endBlockScope: returnUndefined,
  addBlockScopedVariable: noop,
  requestEmitHelper: noop,
  readEmitHelpers: notImplemented,
  enableSubstitution: noop,
  enableEmitNotification: noop,
  isSubstitutionEnabled: notImplemented,
  isEmitNotificationEnabled: notImplemented,
  onSubstituteNode: noEmitSubstitution,
  onEmitNode: noEmitNotification,
  addDiagnostic: noop
};

// src/compiler/emitter.ts
var brackets = createBracketsMap();
function isBuildInfoFile(file) {
  return fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
}
function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit = false, onlyBuildInfo, includeBuildInfo) {
  const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
  const options = host.getCompilerOptions();
  if (outFile(options)) {
    const prepends = host.getPrependNodes();
    if (sourceFiles.length || prepends.length) {
      const bundle = factory.createBundle(sourceFiles, prepends);
      const result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
      if (result) {
        return result;
      }
    }
  } else {
    if (!onlyBuildInfo) {
      for (const sourceFile of sourceFiles) {
        const result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
        if (result) {
          return result;
        }
      }
    }
    if (includeBuildInfo) {
      const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
      if (buildInfoPath)
        return action(
          { buildInfoPath },
          /*sourceFileOrBundle*/
          void 0
        );
    }
  }
}
function getTsBuildInfoEmitOutputFilePath(options) {
  const configFile = options.configFilePath;
  if (!isIncrementalCompilation(options))
    return void 0;
  if (options.tsBuildInfoFile)
    return options.tsBuildInfoFile;
  const outPath = outFile(options);
  let buildInfoExtensionLess;
  if (outPath) {
    buildInfoExtensionLess = removeFileExtension(outPath);
  } else {
    if (!configFile)
      return void 0;
    const configFileExtensionLess = removeFileExtension(configFile);
    buildInfoExtensionLess = options.outDir ? options.rootDir ? resolvePath(options.outDir, getRelativePathFromDirectory(
      options.rootDir,
      configFileExtensionLess,
      /*ignoreCase*/
      true
    )) : combinePaths(options.outDir, getBaseFileName(configFileExtensionLess)) : configFileExtensionLess;
  }
  return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
}
function getOutputPathsForBundle(options, forceDtsPaths) {
  const outPath = outFile(options);
  const jsFilePath = options.emitDeclarationOnly ? void 0 : outPath;
  const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
  const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : void 0;
  const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0;
  const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
  return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath };
}
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
  const options = host.getCompilerOptions();
  if (sourceFile.kind === 312 /* Bundle */) {
    return getOutputPathsForBundle(options, forceDtsPaths);
  } else {
    const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile.fileName, options));
    const isJsonFile = isJsonSourceFile(sourceFile);
    const isJsonEmittedToSameLocation = isJsonFile && comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
    const jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? void 0 : ownOutputFilePath;
    const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? void 0 : getSourceMapFilePath(jsFilePath, options);
    const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) && !isJsonFile ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : void 0;
    const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0;
    return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath: void 0 };
  }
}
function getSourceMapFilePath(jsFilePath, options) {
  return options.sourceMap && !options.inlineSourceMap ? jsFilePath + ".map" : void 0;
}
function getOutputExtension(fileName, options) {
  return fileExtensionIs(fileName, ".json" /* Json */) ? ".json" /* Json */ : options.jsx === 1 /* Preserve */ && fileExtensionIsOneOf(fileName, [".jsx" /* Jsx */, ".tsx" /* Tsx */]) ? ".jsx" /* Jsx */ : fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".mjs" /* Mjs */]) ? ".mjs" /* Mjs */ : fileExtensionIsOneOf(fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]) ? ".cjs" /* Cjs */ : ".js" /* Js */;
}
function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir, getCommonSourceDirectory2) {
  return outputDir ? resolvePath(
    outputDir,
    getRelativePathFromDirectory(getCommonSourceDirectory2 ? getCommonSourceDirectory2() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase)
  ) : inputFileName;
}
function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2) {
  return changeExtension(
    getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory2),
    getDeclarationEmitExtensionForPath(inputFileName)
  );
}
function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2) {
  if (configFile.options.emitDeclarationOnly)
    return void 0;
  const isJsonFile = fileExtensionIs(inputFileName, ".json" /* Json */);
  const outputFileName = changeExtension(
    getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory2),
    getOutputExtension(inputFileName, configFile.options)
  );
  return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? outputFileName : void 0;
}
function createAddOutput() {
  let outputs;
  return { addOutput, getOutputs };
  function addOutput(path) {
    if (path) {
      (outputs || (outputs = [])).push(path);
    }
  }
  function getOutputs() {
    return outputs || emptyArray;
  }
}
function getSingleOutputFileNames(configFile, addOutput) {
  const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(
    configFile.options,
    /*forceDtsPaths*/
    false
  );
  addOutput(jsFilePath);
  addOutput(sourceMapFilePath);
  addOutput(declarationFilePath);
  addOutput(declarationMapPath);
  addOutput(buildInfoPath);
}
function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2) {
  if (isDeclarationFileName(inputFileName))
    return;
  const js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2);
  addOutput(js);
  if (fileExtensionIs(inputFileName, ".json" /* Json */))
    return;
  if (js && configFile.options.sourceMap) {
    addOutput(`${js}.map`);
  }
  if (getEmitDeclarations(configFile.options)) {
    const dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2);
    addOutput(dts);
    if (configFile.options.declarationMap) {
      addOutput(`${dts}.map`);
    }
  }
}
function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCanonicalFileName, checkSourceFilesBelongToPath) {
  let commonSourceDirectory;
  if (options.rootDir) {
    commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
    checkSourceFilesBelongToPath == null ? void 0 : checkSourceFilesBelongToPath(options.rootDir);
  } else if (options.composite && options.configFilePath) {
    commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath));
    checkSourceFilesBelongToPath == null ? void 0 : checkSourceFilesBelongToPath(commonSourceDirectory);
  } else {
    commonSourceDirectory = computeCommonSourceDirectoryOfFilenames(emittedFiles(), currentDirectory, getCanonicalFileName);
  }
  if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
    commonSourceDirectory += directorySeparator;
  }
  return commonSourceDirectory;
}
function getCommonSourceDirectoryOfConfig({ options, fileNames }, ignoreCase) {
  return getCommonSourceDirectory(
    options,
    () => filter(fileNames, (file) => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !isDeclarationFileName(file)),
    getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))),
    createGetCanonicalFileName(!ignoreCase)
  );
}
function getAllProjectOutputs(configFile, ignoreCase) {
  const { addOutput, getOutputs } = createAddOutput();
  if (outFile(configFile.options)) {
    getSingleOutputFileNames(configFile, addOutput);
  } else {
    const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase));
    for (const inputFileName of configFile.fileNames) {
      getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2);
    }
    addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
  }
  return getOutputs();
}
function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
  inputFileName = normalizePath(inputFileName);
  Debug.assert(contains(commandLine.fileNames, inputFileName), `Expected fileName to be present in command line`);
  const { addOutput, getOutputs } = createAddOutput();
  if (outFile(commandLine.options)) {
    getSingleOutputFileNames(commandLine, addOutput);
  } else {
    getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
  }
  return getOutputs();
}
function getFirstProjectOutput(configFile, ignoreCase) {
  if (outFile(configFile.options)) {
    const { jsFilePath, declarationFilePath } = getOutputPathsForBundle(
      configFile.options,
      /*forceDtsPaths*/
      false
    );
    return Debug.checkDefined(jsFilePath || declarationFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`);
  }
  const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase));
  for (const inputFileName of configFile.fileNames) {
    if (isDeclarationFileName(inputFileName))
      continue;
    const jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2);
    if (jsFilePath)
      return jsFilePath;
    if (fileExtensionIs(inputFileName, ".json" /* Json */))
      continue;
    if (getEmitDeclarations(configFile.options)) {
      return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2);
    }
  }
  const buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
  if (buildInfoPath)
    return buildInfoPath;
  return Debug.fail(`project ${configFile.options.configFilePath} expected to have at least one output`);
}
function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) {
  var compilerOptions = host.getCompilerOptions();
  var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0;
  var emittedFilesList = compilerOptions.listEmittedFiles ? [] : void 0;
  var emitterDiagnostics = createDiagnosticCollection();
  var newLine = getNewLineCharacter(compilerOptions);
  var writer = createTextWriter(newLine);
  var { enter, exit } = createTimer("printTime", "beforePrint", "afterPrint");
  var bundleBuildInfo;
  var emitSkipped = false;
  enter();
  forEachEmittedFile(
    host,
    emitSourceFileOrBundle,
    getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit),
    forceDtsEmit,
    onlyBuildInfo,
    !targetSourceFile
  );
  exit();
  return {
    emitSkipped,
    diagnostics: emitterDiagnostics.getDiagnostics(),
    emittedFiles: emittedFilesList,
    sourceMaps: sourceMapDataList
  };
  function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }, sourceFileOrBundle) {
    var _a, _b, _c, _d, _e, _f;
    let buildInfoDirectory;
    if (buildInfoPath && sourceFileOrBundle && isBundle(sourceFileOrBundle)) {
      buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
      bundleBuildInfo = {
        commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
        sourceFiles: sourceFileOrBundle.sourceFiles.map((file) => relativeToBuildInfo(getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())))
      };
    }
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "emitJsFileOrBundle", { jsFilePath });
    emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
    (_b = tracing) == null ? void 0 : _b.pop();
    (_c = tracing) == null ? void 0 : _c.push(tracing.Phase.Emit, "emitDeclarationFileOrBundle", { declarationFilePath });
    emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
    (_d = tracing) == null ? void 0 : _d.pop();
    (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Emit, "emitBuildInfo", { buildInfoPath });
    emitBuildInfo(bundleBuildInfo, buildInfoPath);
    (_f = tracing) == null ? void 0 : _f.pop();
    if (!emitSkipped && emittedFilesList) {
      if (!emitOnly) {
        if (jsFilePath) {
          emittedFilesList.push(jsFilePath);
        }
        if (sourceMapFilePath) {
          emittedFilesList.push(sourceMapFilePath);
        }
        if (buildInfoPath) {
          emittedFilesList.push(buildInfoPath);
        }
      }
      if (emitOnly !== 0 /* Js */) {
        if (declarationFilePath) {
          emittedFilesList.push(declarationFilePath);
        }
        if (declarationMapPath) {
          emittedFilesList.push(declarationMapPath);
        }
      }
    }
    function relativeToBuildInfo(path) {
      return ensurePathIsNonModuleName(getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
    }
  }
  function emitBuildInfo(bundle, buildInfoPath) {
    if (!buildInfoPath || targetSourceFile || emitSkipped)
      return;
    if (host.isEmitBlocked(buildInfoPath)) {
      emitSkipped = true;
      return;
    }
    const buildInfo = host.getBuildInfo(bundle) || createBuildInfo(
      /*program*/
      void 0,
      bundle
    );
    writeFile(
      host,
      emitterDiagnostics,
      buildInfoPath,
      getBuildInfoText(buildInfo),
      /*writeByteOrderMark*/
      false,
      /*sourceFiles*/
      void 0,
      { buildInfo }
    );
  }
  function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
    if (!sourceFileOrBundle || emitOnly || !jsFilePath) {
      return;
    }
    if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) {
      emitSkipped = true;
      return;
    }
    const transform2 = transformNodes(
      resolver,
      host,
      factory,
      compilerOptions,
      [sourceFileOrBundle],
      scriptTransformers,
      /*allowDtsFiles*/
      false
    );
    const printerOptions = {
      removeComments: compilerOptions.removeComments,
      newLine: compilerOptions.newLine,
      noEmitHelpers: compilerOptions.noEmitHelpers,
      module: compilerOptions.module,
      target: compilerOptions.target,
      sourceMap: compilerOptions.sourceMap,
      inlineSourceMap: compilerOptions.inlineSourceMap,
      inlineSources: compilerOptions.inlineSources,
      extendedDiagnostics: compilerOptions.extendedDiagnostics,
      writeBundleFileInfo: !!bundleBuildInfo,
      relativeToBuildInfo
    };
    const printer = createPrinter(printerOptions, {
      // resolver hooks
      hasGlobalName: resolver.hasGlobalName,
      // transform hooks
      onEmitNode: transform2.emitNodeWithNotification,
      isEmitNotificationEnabled: transform2.isEmitNotificationEnabled,
      substituteNode: transform2.substituteNode
    });
    Debug.assert(transform2.transformed.length === 1, "Should only see one output from the transform");
    printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform2, printer, compilerOptions);
    transform2.dispose();
    if (bundleBuildInfo)
      bundleBuildInfo.js = printer.bundleFileInfo;
  }
  function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
    if (!sourceFileOrBundle || emitOnly === 0 /* Js */)
      return;
    if (!declarationFilePath) {
      if (emitOnly || compilerOptions.emitDeclarationOnly)
        emitSkipped = true;
      return;
    }
    const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
    const filesForEmit = forceDtsEmit ? sourceFiles : filter(sourceFiles, isSourceFileNotJson);
    const inputListOrBundle = outFile(compilerOptions) ? [factory.createBundle(filesForEmit, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : void 0)] : filesForEmit;
    if (emitOnly && !getEmitDeclarations(compilerOptions)) {
      filesForEmit.forEach(collectLinkedAliases);
    }
    const declarationTransform = transformNodes(
      resolver,
      host,
      factory,
      compilerOptions,
      inputListOrBundle,
      declarationTransformers,
      /*allowDtsFiles*/
      false
    );
    if (length(declarationTransform.diagnostics)) {
      for (const diagnostic of declarationTransform.diagnostics) {
        emitterDiagnostics.add(diagnostic);
      }
    }
    const printerOptions = {
      removeComments: compilerOptions.removeComments,
      newLine: compilerOptions.newLine,
      noEmitHelpers: true,
      module: compilerOptions.module,
      target: compilerOptions.target,
      sourceMap: !forceDtsEmit && compilerOptions.declarationMap,
      inlineSourceMap: compilerOptions.inlineSourceMap,
      extendedDiagnostics: compilerOptions.extendedDiagnostics,
      onlyPrintJsDocStyle: true,
      writeBundleFileInfo: !!bundleBuildInfo,
      recordInternalSection: !!bundleBuildInfo,
      relativeToBuildInfo
    };
    const declarationPrinter = createPrinter(printerOptions, {
      // resolver hooks
      hasGlobalName: resolver.hasGlobalName,
      // transform hooks
      onEmitNode: declarationTransform.emitNodeWithNotification,
      isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
      substituteNode: declarationTransform.substituteNode
    });
    const declBlocked = !!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
    emitSkipped = emitSkipped || declBlocked;
    if (!declBlocked || forceDtsEmit) {
      Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
      printSourceFileOrBundle(
        declarationFilePath,
        declarationMapPath,
        declarationTransform,
        declarationPrinter,
        {
          sourceMap: printerOptions.sourceMap,
          sourceRoot: compilerOptions.sourceRoot,
          mapRoot: compilerOptions.mapRoot,
          extendedDiagnostics: compilerOptions.extendedDiagnostics
          // Explicitly do not passthru either `inline` option
        }
      );
    }
    declarationTransform.dispose();
    if (bundleBuildInfo)
      bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
  }
  function collectLinkedAliases(node) {
    if (isExportAssignment(node)) {
      if (node.expression.kind === 80 /* Identifier */) {
        resolver.collectLinkedAliases(
          node.expression,
          /*setVisibility*/
          true
        );
      }
      return;
    } else if (isExportSpecifier(node)) {
      resolver.collectLinkedAliases(
        node.propertyName || node.name,
        /*setVisibility*/
        true
      );
      return;
    }
    forEachChild(node, collectLinkedAliases);
  }
  function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform2, printer, mapOptions) {
    const sourceFileOrBundle = transform2.transformed[0];
    const bundle = sourceFileOrBundle.kind === 312 /* Bundle */ ? sourceFileOrBundle : void 0;
    const sourceFile = sourceFileOrBundle.kind === 311 /* SourceFile */ ? sourceFileOrBundle : void 0;
    const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
    let sourceMapGenerator;
    if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
      sourceMapGenerator = createSourceMapGenerator(
        host,
        getBaseFileName(normalizeSlashes(jsFilePath)),
        getSourceRoot(mapOptions),
        getSourceMapDirectory(mapOptions, jsFilePath, sourceFile),
        mapOptions
      );
    }
    if (bundle) {
      printer.writeBundle(bundle, writer, sourceMapGenerator);
    } else {
      printer.writeFile(sourceFile, writer, sourceMapGenerator);
    }
    let sourceMapUrlPos;
    if (sourceMapGenerator) {
      if (sourceMapDataList) {
        sourceMapDataList.push({
          inputSourceFileNames: sourceMapGenerator.getSources(),
          sourceMap: sourceMapGenerator.toJSON()
        });
      }
      const sourceMappingURL = getSourceMappingURL(
        mapOptions,
        sourceMapGenerator,
        jsFilePath,
        sourceMapFilePath,
        sourceFile
      );
      if (sourceMappingURL) {
        if (!writer.isAtStartOfLine())
          writer.rawWrite(newLine);
        sourceMapUrlPos = writer.getTextPos();
        writer.writeComment(`//# ${"sourceMappingURL"}=${sourceMappingURL}`);
      }
      if (sourceMapFilePath) {
        const sourceMap = sourceMapGenerator.toString();
        writeFile(
          host,
          emitterDiagnostics,
          sourceMapFilePath,
          sourceMap,
          /*writeByteOrderMark*/
          false,
          sourceFiles
        );
        if (printer.bundleFileInfo)
          printer.bundleFileInfo.mapHash = computeSignature(sourceMap, host);
      }
    } else {
      writer.writeLine();
    }
    const text = writer.getText();
    writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos, diagnostics: transform2.diagnostics });
    if (printer.bundleFileInfo)
      printer.bundleFileInfo.hash = computeSignature(text, host);
    writer.clear();
  }
  function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
    return (mapOptions.sourceMap || mapOptions.inlineSourceMap) && (sourceFileOrBundle.kind !== 311 /* SourceFile */ || !fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
  }
  function getSourceRoot(mapOptions) {
    const sourceRoot = normalizeSlashes(mapOptions.sourceRoot || "");
    return sourceRoot ? ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
  }
  function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
    if (mapOptions.sourceRoot)
      return host.getCommonSourceDirectory();
    if (mapOptions.mapRoot) {
      let sourceMapDir = normalizeSlashes(mapOptions.mapRoot);
      if (sourceFile) {
        sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
      }
      if (getRootLength(sourceMapDir) === 0) {
        sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
      }
      return sourceMapDir;
    }
    return getDirectoryPath(normalizePath(filePath));
  }
  function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
    if (mapOptions.inlineSourceMap) {
      const sourceMapText = sourceMapGenerator.toString();
      const base64SourceMapText = base64encode(sys, sourceMapText);
      return `data:application/json;base64,${base64SourceMapText}`;
    }
    const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.checkDefined(sourceMapFilePath)));
    if (mapOptions.mapRoot) {
      let sourceMapDir = normalizeSlashes(mapOptions.mapRoot);
      if (sourceFile) {
        sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
      }
      if (getRootLength(sourceMapDir) === 0) {
        sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
        return encodeURI(
          getRelativePathToDirectoryOrUrl(
            getDirectoryPath(normalizePath(filePath)),
            // get the relative sourceMapDir path based on jsFilePath
            combinePaths(sourceMapDir, sourceMapFile),
            // this is where user expects to see sourceMap
            host.getCurrentDirectory(),
            host.getCanonicalFileName,
            /*isAbsolutePathAnUrl*/
            true
          )
        );
      } else {
        return encodeURI(combinePaths(sourceMapDir, sourceMapFile));
      }
    }
    return encodeURI(sourceMapFile);
  }
}
function createBuildInfo(program, bundle) {
  return { bundle, program, version };
}
function getBuildInfoText(buildInfo) {
  return JSON.stringify(buildInfo);
}
function getBuildInfo(buildInfoFile, buildInfoText) {
  return readJsonOrUndefined(buildInfoFile, buildInfoText);
}
var notImplementedResolver = {
  hasGlobalName: notImplemented,
  getReferencedExportContainer: notImplemented,
  getReferencedImportDeclaration: notImplemented,
  getReferencedDeclarationWithCollidingName: notImplemented,
  isDeclarationWithCollidingName: notImplemented,
  isValueAliasDeclaration: notImplemented,
  isReferencedAliasDeclaration: notImplemented,
  isTopLevelValueImportEqualsWithEntityName: notImplemented,
  getNodeCheckFlags: notImplemented,
  isDeclarationVisible: notImplemented,
  isLateBound: (_node) => false,
  collectLinkedAliases: notImplemented,
  isImplementationOfOverload: notImplemented,
  isRequiredInitializedParameter: notImplemented,
  isOptionalUninitializedParameterProperty: notImplemented,
  isExpandoFunctionDeclaration: notImplemented,
  getPropertiesOfContainerFunction: notImplemented,
  createTypeOfDeclaration: notImplemented,
  createReturnTypeOfSignatureDeclaration: notImplemented,
  createTypeOfExpression: notImplemented,
  createLiteralConstValue: notImplemented,
  isSymbolAccessible: notImplemented,
  isEntityNameVisible: notImplemented,
  // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
  getConstantValue: notImplemented,
  getReferencedValueDeclaration: notImplemented,
  getReferencedValueDeclarations: notImplemented,
  getTypeReferenceSerializationKind: notImplemented,
  isOptionalParameter: notImplemented,
  moduleExportsSomeValue: notImplemented,
  isArgumentsLocalBinding: notImplemented,
  getExternalModuleFileFromDeclaration: notImplemented,
  getTypeReferenceDirectivesForEntityName: notImplemented,
  getTypeReferenceDirectivesForSymbol: notImplemented,
  isLiteralConstDeclaration: notImplemented,
  getJsxFactoryEntity: notImplemented,
  getJsxFragmentFactoryEntity: notImplemented,
  getAllAccessorDeclarations: notImplemented,
  getSymbolOfExternalModuleSpecifier: notImplemented,
  isBindingCapturedByNode: notImplemented,
  getDeclarationStatementsForSourceFile: notImplemented,
  isImportRequiredByAugmentation: notImplemented
};
function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
  var _a;
  const jsBundle = Debug.checkDefined(bundle.js);
  const prologueMap = ((_a = jsBundle.sources) == null ? void 0 : _a.prologues) && arrayToMap(jsBundle.sources.prologues, (prologueInfo) => prologueInfo.file);
  return bundle.sourceFiles.map((fileName, index) => {
    const prologueInfo = prologueMap == null ? void 0 : prologueMap.get(index);
    const statements = prologueInfo == null ? void 0 : prologueInfo.directives.map((directive) => {
      const literal = setTextRange(factory.createStringLiteral(directive.expression.text), directive.expression);
      const statement = setTextRange(factory.createExpressionStatement(literal), directive);
      setParent(literal, statement);
      return statement;
    });
    const eofToken = factory.createToken(1 /* EndOfFileToken */);
    const sourceFile = factory.createSourceFile(statements ?? [], eofToken, 0 /* None */);
    sourceFile.fileName = getRelativePathFromDirectory(
      host.getCurrentDirectory(),
      getNormalizedAbsolutePath(fileName, buildInfoDirectory),
      !host.useCaseSensitiveFileNames()
    );
    sourceFile.text = (prologueInfo == null ? void 0 : prologueInfo.text) ?? "";
    setTextRangePosWidth(sourceFile, 0, (prologueInfo == null ? void 0 : prologueInfo.text.length) ?? 0);
    setEachParent(sourceFile.statements, sourceFile);
    setTextRangePosWidth(eofToken, sourceFile.end, 0);
    setParent(eofToken, sourceFile);
    return sourceFile;
  });
}
function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
  var _a, _b;
  (_a = tracing) == null ? void 0 : _a.push(
    tracing.Phase.Emit,
    "emitUsingBuildInfo",
    {},
    /*separateBeginAndEnd*/
    true
  );
  mark("beforeEmit");
  const result = emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers);
  mark("afterEmit");
  measure("Emit", "beforeEmit", "afterEmit");
  (_b = tracing) == null ? void 0 : _b.pop();
  return result;
}
function emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers) {
  const { buildInfoPath, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(
    config.options,
    /*forceDtsPaths*/
    false
  );
  const buildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath);
  if (!buildInfo)
    return buildInfoPath;
  if (!buildInfo.bundle || !buildInfo.bundle.js || declarationFilePath && !buildInfo.bundle.dts)
    return buildInfoPath;
  const jsFileText = host.readFile(Debug.checkDefined(jsFilePath));
  if (!jsFileText)
    return jsFilePath;
  if (computeSignature(jsFileText, host) !== buildInfo.bundle.js.hash)
    return jsFilePath;
  const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
  if (sourceMapFilePath && !sourceMapText || config.options.inlineSourceMap)
    return sourceMapFilePath || "inline sourcemap decoding";
  if (sourceMapFilePath && computeSignature(sourceMapText, host) !== buildInfo.bundle.js.mapHash)
    return sourceMapFilePath;
  const declarationText = declarationFilePath && host.readFile(declarationFilePath);
  if (declarationFilePath && !declarationText)
    return declarationFilePath;
  if (declarationFilePath && computeSignature(declarationText, host) !== buildInfo.bundle.dts.hash)
    return declarationFilePath;
  const declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
  if (declarationMapPath && !declarationMapText || config.options.inlineSourceMap)
    return declarationMapPath || "inline sourcemap decoding";
  if (declarationMapPath && computeSignature(declarationMapText, host) !== buildInfo.bundle.dts.mapHash)
    return declarationMapPath;
  const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
  const ownPrependInput = createInputFilesWithFileTexts(
    jsFilePath,
    jsFileText,
    sourceMapFilePath,
    sourceMapText,
    declarationFilePath,
    declarationText,
    declarationMapPath,
    declarationMapText,
    buildInfoPath,
    buildInfo,
    /*oldFileOfCurrentEmit*/
    true
  );
  const outputFiles = [];
  const prependNodes = createPrependNodes(config.projectReferences, getCommandLine, (f) => host.readFile(f), host);
  const sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
  let changedDtsText;
  let changedDtsData;
  const emitHost = {
    getPrependNodes: memoize(() => [...prependNodes, ownPrependInput]),
    getCanonicalFileName: host.getCanonicalFileName,
    getCommonSourceDirectory: () => getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory),
    getCompilerOptions: () => config.options,
    getCurrentDirectory: () => host.getCurrentDirectory(),
    getSourceFile: returnUndefined,
    getSourceFileByPath: returnUndefined,
    getSourceFiles: () => sourceFilesForJsEmit,
    getLibFileFromReference: notImplemented,
    isSourceFileFromExternalLibrary: returnFalse,
    getResolvedProjectReferenceToRedirect: returnUndefined,
    getProjectReferenceRedirect: returnUndefined,
    isSourceOfProjectReferenceRedirect: returnFalse,
    writeFile: (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => {
      switch (name) {
        case jsFilePath:
          if (jsFileText === text)
            return;
          break;
        case sourceMapFilePath:
          if (sourceMapText === text)
            return;
          break;
        case buildInfoPath:
          break;
        case declarationFilePath:
          if (declarationText === text)
            return;
          changedDtsText = text;
          changedDtsData = data;
          break;
        case declarationMapPath:
          if (declarationMapText === text)
            return;
          break;
        default:
          Debug.fail(`Unexpected path: ${name}`);
      }
      outputFiles.push({ name, text, writeByteOrderMark, data });
    },
    isEmitBlocked: returnFalse,
    readFile: (f) => host.readFile(f),
    fileExists: (f) => host.fileExists(f),
    useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
    getBuildInfo: (bundle) => {
      const program = buildInfo.program;
      if (program && changedDtsText !== void 0 && config.options.composite) {
        program.outSignature = computeSignature(changedDtsText, host, changedDtsData);
      }
      const { js, dts, sourceFiles } = buildInfo.bundle;
      bundle.js.sources = js.sources;
      if (dts) {
        bundle.dts.sources = dts.sources;
      }
      bundle.sourceFiles = sourceFiles;
      return createBuildInfo(program, bundle);
    },
    getSourceFileFromReference: returnUndefined,
    redirectTargetsMap: createMultiMap(),
    getFileIncludeReasons: notImplemented,
    createHash: maybeBind(host, host.createHash)
  };
  emitFiles(
    notImplementedResolver,
    emitHost,
    /*targetSourceFile*/
    void 0,
    getTransformers(config.options, customTransformers)
  );
  return outputFiles;
}
var createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({}));
var createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true }));
var createPrinterWithRemoveCommentsNeverAsciiEscape = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true }));
var createPrinterWithRemoveCommentsOmitTrailingSemicolon = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true }));
function createPrinter(printerOptions = {}, handlers = {}) {
  var {
    hasGlobalName,
    onEmitNode = noEmitNotification,
    isEmitNotificationEnabled,
    substituteNode = noEmitSubstitution,
    onBeforeEmitNode,
    onAfterEmitNode,
    onBeforeEmitNodeArray,
    onAfterEmitNodeArray,
    onBeforeEmitToken,
    onAfterEmitToken
  } = handlers;
  var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
  var newLine = getNewLineCharacter(printerOptions);
  var moduleKind = getEmitModuleKind(printerOptions);
  var bundledHelpers = /* @__PURE__ */ new Map();
  var currentSourceFile;
  var nodeIdToGeneratedName;
  var nodeIdToGeneratedPrivateName;
  var autoGeneratedIdToGeneratedName;
  var generatedNames;
  var formattedNameTempFlagsStack;
  var formattedNameTempFlags;
  var privateNameTempFlagsStack;
  var privateNameTempFlags;
  var tempFlagsStack;
  var tempFlags;
  var reservedNamesStack;
  var reservedNames;
  var reservedPrivateNamesStack;
  var reservedPrivateNames;
  var preserveSourceNewlines = printerOptions.preserveSourceNewlines;
  var nextListElementPos;
  var writer;
  var ownWriter;
  var write = writeBase;
  var isOwnFileEmit;
  var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : void 0;
  var relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : void 0;
  var recordInternalSection = printerOptions.recordInternalSection;
  var sourceFileTextPos = 0;
  var sourceFileTextKind = "text" /* Text */;
  var sourceMapsDisabled = true;
  var sourceMapGenerator;
  var sourceMapSource;
  var sourceMapSourceIndex = -1;
  var mostRecentlyAddedSourceMapSource;
  var mostRecentlyAddedSourceMapSourceIndex = -1;
  var containerPos = -1;
  var containerEnd = -1;
  var declarationListContainerEnd = -1;
  var currentLineMap;
  var detachedCommentsInfo;
  var hasWrittenComment = false;
  var commentsDisabled = !!printerOptions.removeComments;
  var lastSubstitution;
  var currentParenthesizerRule;
  var { enter: enterComment, exit: exitComment } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment");
  var parenthesizer = factory.parenthesizer;
  var typeArgumentParenthesizerRuleSelector = {
    select: (index) => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : void 0
  };
  var emitBinaryExpression = createEmitBinaryExpression();
  reset2();
  return {
    // public API
    printNode,
    printList,
    printFile,
    printBundle,
    // internal API
    writeNode,
    writeList,
    writeFile: writeFile2,
    writeBundle,
    bundleFileInfo
  };
  function printNode(hint, node, sourceFile) {
    switch (hint) {
      case 0 /* SourceFile */:
        Debug.assert(isSourceFile(node), "Expected a SourceFile node.");
        break;
      case 2 /* IdentifierName */:
        Debug.assert(isIdentifier(node), "Expected an Identifier node.");
        break;
      case 1 /* Expression */:
        Debug.assert(isExpression(node), "Expected an Expression node.");
        break;
    }
    switch (node.kind) {
      case 311 /* SourceFile */:
        return printFile(node);
      case 312 /* Bundle */:
        return printBundle(node);
      case 313 /* UnparsedSource */:
        return printUnparsedSource(node);
    }
    writeNode(hint, node, sourceFile, beginPrint());
    return endPrint();
  }
  function printList(format, nodes, sourceFile) {
    writeList(format, nodes, sourceFile, beginPrint());
    return endPrint();
  }
  function printBundle(bundle) {
    writeBundle(
      bundle,
      beginPrint(),
      /*sourceMapGenerator*/
      void 0
    );
    return endPrint();
  }
  function printFile(sourceFile) {
    writeFile2(
      sourceFile,
      beginPrint(),
      /*sourceMapGenerator*/
      void 0
    );
    return endPrint();
  }
  function printUnparsedSource(unparsed) {
    writeUnparsedSource(unparsed, beginPrint());
    return endPrint();
  }
  function writeNode(hint, node, sourceFile, output) {
    const previousWriter = writer;
    setWriter(
      output,
      /*_sourceMapGenerator*/
      void 0
    );
    print(hint, node, sourceFile);
    reset2();
    writer = previousWriter;
  }
  function writeList(format, nodes, sourceFile, output) {
    const previousWriter = writer;
    setWriter(
      output,
      /*_sourceMapGenerator*/
      void 0
    );
    if (sourceFile) {
      setSourceFile(sourceFile);
    }
    emitList(
      /*parentNode*/
      void 0,
      nodes,
      format
    );
    reset2();
    writer = previousWriter;
  }
  function getTextPosWithWriteLine() {
    return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
  }
  function updateOrPushBundleFileTextLike(pos, end, kind) {
    const last2 = lastOrUndefined(bundleFileInfo.sections);
    if (last2 && last2.kind === kind) {
      last2.end = end;
    } else {
      bundleFileInfo.sections.push({ pos, end, kind });
    }
  }
  function recordBundleFileInternalSectionStart(node) {
    if (recordInternalSection && bundleFileInfo && currentSourceFile && (isDeclaration(node) || isVariableStatement(node)) && isInternalDeclaration(node, currentSourceFile) && sourceFileTextKind !== "internal" /* Internal */) {
      const prevSourceFileTextKind = sourceFileTextKind;
      recordBundleFileTextLikeSection(writer.getTextPos());
      sourceFileTextPos = getTextPosWithWriteLine();
      sourceFileTextKind = "internal" /* Internal */;
      return prevSourceFileTextKind;
    }
    return void 0;
  }
  function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
    if (prevSourceFileTextKind) {
      recordBundleFileTextLikeSection(writer.getTextPos());
      sourceFileTextPos = getTextPosWithWriteLine();
      sourceFileTextKind = prevSourceFileTextKind;
    }
  }
  function recordBundleFileTextLikeSection(end) {
    if (sourceFileTextPos < end) {
      updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
      return true;
    }
    return false;
  }
  function writeBundle(bundle, output, sourceMapGenerator2) {
    isOwnFileEmit = false;
    const previousWriter = writer;
    setWriter(output, sourceMapGenerator2);
    emitShebangIfNeeded(bundle);
    emitPrologueDirectivesIfNeeded(bundle);
    emitHelpers(bundle);
    emitSyntheticTripleSlashReferencesIfNeeded(bundle);
    for (const prepend of bundle.prepends) {
      writeLine();
      const pos = writer.getTextPos();
      const savedSections = bundleFileInfo && bundleFileInfo.sections;
      if (savedSections)
        bundleFileInfo.sections = [];
      print(
        4 /* Unspecified */,
        prepend,
        /*sourceFile*/
        void 0
      );
      if (bundleFileInfo) {
        const newSections = bundleFileInfo.sections;
        bundleFileInfo.sections = savedSections;
        if (prepend.oldFileOfCurrentEmit)
          bundleFileInfo.sections.push(...newSections);
        else {
          newSections.forEach((section) => Debug.assert(isBundleFileTextLike(section)));
          bundleFileInfo.sections.push({
            pos,
            end: writer.getTextPos(),
            kind: "prepend" /* Prepend */,
            data: relativeToBuildInfo(prepend.fileName),
            texts: newSections
          });
        }
      }
    }
    sourceFileTextPos = getTextPosWithWriteLine();
    for (const sourceFile of bundle.sourceFiles) {
      print(0 /* SourceFile */, sourceFile, sourceFile);
    }
    if (bundleFileInfo && bundle.sourceFiles.length) {
      const end = writer.getTextPos();
      if (recordBundleFileTextLikeSection(end)) {
        const prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
        if (prologues) {
          if (!bundleFileInfo.sources)
            bundleFileInfo.sources = {};
          bundleFileInfo.sources.prologues = prologues;
        }
        const helpers = getHelpersFromBundledSourceFiles(bundle);
        if (helpers) {
          if (!bundleFileInfo.sources)
            bundleFileInfo.sources = {};
          bundleFileInfo.sources.helpers = helpers;
        }
      }
    }
    reset2();
    writer = previousWriter;
  }
  function writeUnparsedSource(unparsed, output) {
    const previousWriter = writer;
    setWriter(
      output,
      /*_sourceMapGenerator*/
      void 0
    );
    print(
      4 /* Unspecified */,
      unparsed,
      /*sourceFile*/
      void 0
    );
    reset2();
    writer = previousWriter;
  }
  function writeFile2(sourceFile, output, sourceMapGenerator2) {
    isOwnFileEmit = true;
    const previousWriter = writer;
    setWriter(output, sourceMapGenerator2);
    emitShebangIfNeeded(sourceFile);
    emitPrologueDirectivesIfNeeded(sourceFile);
    print(0 /* SourceFile */, sourceFile, sourceFile);
    reset2();
    writer = previousWriter;
  }
  function beginPrint() {
    return ownWriter || (ownWriter = createTextWriter(newLine));
  }
  function endPrint() {
    const text = ownWriter.getText();
    ownWriter.clear();
    return text;
  }
  function print(hint, node, sourceFile) {
    if (sourceFile) {
      setSourceFile(sourceFile);
    }
    pipelineEmit(
      hint,
      node,
      /*parenthesizerRule*/
      void 0
    );
  }
  function setSourceFile(sourceFile) {
    currentSourceFile = sourceFile;
    currentLineMap = void 0;
    detachedCommentsInfo = void 0;
    if (sourceFile) {
      setSourceMapSource(sourceFile);
    }
  }
  function setWriter(_writer, _sourceMapGenerator) {
    if (_writer && printerOptions.omitTrailingSemicolon) {
      _writer = getTrailingSemicolonDeferringWriter(_writer);
    }
    writer = _writer;
    sourceMapGenerator = _sourceMapGenerator;
    sourceMapsDisabled = !writer || !sourceMapGenerator;
  }
  function reset2() {
    nodeIdToGeneratedName = [];
    nodeIdToGeneratedPrivateName = [];
    autoGeneratedIdToGeneratedName = [];
    generatedNames = /* @__PURE__ */ new Set();
    formattedNameTempFlagsStack = [];
    formattedNameTempFlags = /* @__PURE__ */ new Map();
    privateNameTempFlagsStack = [];
    privateNameTempFlags = 0 /* Auto */;
    tempFlagsStack = [];
    tempFlags = 0 /* Auto */;
    reservedNamesStack = [];
    reservedNames = void 0;
    reservedPrivateNamesStack = [];
    reservedPrivateNames = void 0;
    currentSourceFile = void 0;
    currentLineMap = void 0;
    detachedCommentsInfo = void 0;
    setWriter(
      /*output*/
      void 0,
      /*_sourceMapGenerator*/
      void 0
    );
  }
  function getCurrentLineMap() {
    return currentLineMap || (currentLineMap = getLineStarts(Debug.checkDefined(currentSourceFile)));
  }
  function emit(node, parenthesizerRule) {
    if (node === void 0)
      return;
    const prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
    pipelineEmit(4 /* Unspecified */, node, parenthesizerRule);
    recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
  }
  function emitIdentifierName(node) {
    if (node === void 0)
      return;
    pipelineEmit(
      2 /* IdentifierName */,
      node,
      /*parenthesizerRule*/
      void 0
    );
  }
  function emitExpression(node, parenthesizerRule) {
    if (node === void 0)
      return;
    pipelineEmit(1 /* Expression */, node, parenthesizerRule);
  }
  function emitJsxAttributeValue(node) {
    pipelineEmit(isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
  }
  function beforeEmitNode(node) {
    if (preserveSourceNewlines && getInternalEmitFlags(node) & 4 /* IgnoreSourceNewlines */) {
      preserveSourceNewlines = false;
    }
  }
  function afterEmitNode(savedPreserveSourceNewlines) {
    preserveSourceNewlines = savedPreserveSourceNewlines;
  }
  function pipelineEmit(emitHint, node, parenthesizerRule) {
    currentParenthesizerRule = parenthesizerRule;
    const pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
    pipelinePhase(emitHint, node);
    currentParenthesizerRule = void 0;
  }
  function shouldEmitComments(node) {
    return !commentsDisabled && !isSourceFile(node);
  }
  function shouldEmitSourceMaps(node) {
    return !sourceMapsDisabled && !isSourceFile(node) && !isInJsonFile(node) && !isUnparsedSource(node) && !isUnparsedPrepend(node);
  }
  function getPipelinePhase(phase, emitHint, node) {
    switch (phase) {
      case 0 /* Notification */:
        if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
          return pipelineEmitWithNotification;
        }
      case 1 /* Substitution */:
        if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) {
          if (currentParenthesizerRule) {
            lastSubstitution = currentParenthesizerRule(lastSubstitution);
          }
          return pipelineEmitWithSubstitution;
        }
      case 2 /* Comments */:
        if (shouldEmitComments(node)) {
          return pipelineEmitWithComments;
        }
      case 3 /* SourceMaps */:
        if (shouldEmitSourceMaps(node)) {
          return pipelineEmitWithSourceMaps;
        }
      case 4 /* Emit */:
        return pipelineEmitWithHint;
      default:
        return Debug.assertNever(phase);
    }
  }
  function getNextPipelinePhase(currentPhase, emitHint, node) {
    return getPipelinePhase(currentPhase + 1, emitHint, node);
  }
  function pipelineEmitWithNotification(hint, node) {
    const pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
    onEmitNode(hint, node, pipelinePhase);
  }
  function pipelineEmitWithHint(hint, node) {
    onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node);
    if (preserveSourceNewlines) {
      const savedPreserveSourceNewlines = preserveSourceNewlines;
      beforeEmitNode(node);
      pipelineEmitWithHintWorker(hint, node);
      afterEmitNode(savedPreserveSourceNewlines);
    } else {
      pipelineEmitWithHintWorker(hint, node);
    }
    onAfterEmitNode == null ? void 0 : onAfterEmitNode(node);
    currentParenthesizerRule = void 0;
  }
  function pipelineEmitWithHintWorker(hint, node, allowSnippets = true) {
    if (allowSnippets) {
      const snippet = getSnippetElement(node);
      if (snippet) {
        return emitSnippetNode(hint, node, snippet);
      }
    }
    if (hint === 0 /* SourceFile */)
      return emitSourceFile(cast(node, isSourceFile));
    if (hint === 2 /* IdentifierName */)
      return emitIdentifier(cast(node, isIdentifier));
    if (hint === 6 /* JsxAttributeValue */)
      return emitLiteral(
        cast(node, isStringLiteral),
        /*jsxAttributeEscape*/
        true
      );
    if (hint === 3 /* MappedTypeParameter */)
      return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration));
    if (hint === 5 /* EmbeddedStatement */) {
      Debug.assertNode(node, isEmptyStatement);
      return emitEmptyStatement(
        /*isEmbeddedStatement*/
        true
      );
    }
    if (hint === 4 /* Unspecified */) {
      switch (node.kind) {
        case 16 /* TemplateHead */:
        case 17 /* TemplateMiddle */:
        case 18 /* TemplateTail */:
          return emitLiteral(
            node,
            /*jsxAttributeEscape*/
            false
          );
        case 80 /* Identifier */:
          return emitIdentifier(node);
        case 81 /* PrivateIdentifier */:
          return emitPrivateIdentifier(node);
        case 165 /* QualifiedName */:
          return emitQualifiedName(node);
        case 166 /* ComputedPropertyName */:
          return emitComputedPropertyName(node);
        case 167 /* TypeParameter */:
          return emitTypeParameter(node);
        case 168 /* Parameter */:
          return emitParameter(node);
        case 169 /* Decorator */:
          return emitDecorator(node);
        case 170 /* PropertySignature */:
          return emitPropertySignature(node);
        case 171 /* PropertyDeclaration */:
          return emitPropertyDeclaration(node);
        case 172 /* MethodSignature */:
          return emitMethodSignature(node);
        case 173 /* MethodDeclaration */:
          return emitMethodDeclaration(node);
        case 174 /* ClassStaticBlockDeclaration */:
          return emitClassStaticBlockDeclaration(node);
        case 175 /* Constructor */:
          return emitConstructor(node);
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
          return emitAccessorDeclaration(node);
        case 178 /* CallSignature */:
          return emitCallSignature(node);
        case 179 /* ConstructSignature */:
          return emitConstructSignature(node);
        case 180 /* IndexSignature */:
          return emitIndexSignature(node);
        case 181 /* TypePredicate */:
          return emitTypePredicate(node);
        case 182 /* TypeReference */:
          return emitTypeReference(node);
        case 183 /* FunctionType */:
          return emitFunctionType(node);
        case 184 /* ConstructorType */:
          return emitConstructorType(node);
        case 185 /* TypeQuery */:
          return emitTypeQuery(node);
        case 186 /* TypeLiteral */:
          return emitTypeLiteral(node);
        case 187 /* ArrayType */:
          return emitArrayType(node);
        case 188 /* TupleType */:
          return emitTupleType(node);
        case 189 /* OptionalType */:
          return emitOptionalType(node);
        case 191 /* UnionType */:
          return emitUnionType(node);
        case 192 /* IntersectionType */:
          return emitIntersectionType(node);
        case 193 /* ConditionalType */:
          return emitConditionalType(node);
        case 194 /* InferType */:
          return emitInferType(node);
        case 195 /* ParenthesizedType */:
          return emitParenthesizedType(node);
        case 232 /* ExpressionWithTypeArguments */:
          return emitExpressionWithTypeArguments(node);
        case 196 /* ThisType */:
          return emitThisType();
        case 197 /* TypeOperator */:
          return emitTypeOperator(node);
        case 198 /* IndexedAccessType */:
          return emitIndexedAccessType(node);
        case 199 /* MappedType */:
          return emitMappedType(node);
        case 200 /* LiteralType */:
          return emitLiteralType(node);
        case 201 /* NamedTupleMember */:
          return emitNamedTupleMember(node);
        case 202 /* TemplateLiteralType */:
          return emitTemplateType(node);
        case 203 /* TemplateLiteralTypeSpan */:
          return emitTemplateTypeSpan(node);
        case 204 /* ImportType */:
          return emitImportTypeNode(node);
        case 205 /* ObjectBindingPattern */:
          return emitObjectBindingPattern(node);
        case 206 /* ArrayBindingPattern */:
          return emitArrayBindingPattern(node);
        case 207 /* BindingElement */:
          return emitBindingElement(node);
        case 238 /* TemplateSpan */:
          return emitTemplateSpan(node);
        case 239 /* SemicolonClassElement */:
          return emitSemicolonClassElement();
        case 240 /* Block */:
          return emitBlock(node);
        case 242 /* VariableStatement */:
          return emitVariableStatement(node);
        case 241 /* EmptyStatement */:
          return emitEmptyStatement(
            /*isEmbeddedStatement*/
            false
          );
        case 243 /* ExpressionStatement */:
          return emitExpressionStatement(node);
        case 244 /* IfStatement */:
          return emitIfStatement(node);
        case 245 /* DoStatement */:
          return emitDoStatement(node);
        case 246 /* WhileStatement */:
          return emitWhileStatement(node);
        case 247 /* ForStatement */:
          return emitForStatement(node);
        case 248 /* ForInStatement */:
          return emitForInStatement(node);
        case 249 /* ForOfStatement */:
          return emitForOfStatement(node);
        case 250 /* ContinueStatement */:
          return emitContinueStatement(node);
        case 251 /* BreakStatement */:
          return emitBreakStatement(node);
        case 252 /* ReturnStatement */:
          return emitReturnStatement(node);
        case 253 /* WithStatement */:
          return emitWithStatement(node);
        case 254 /* SwitchStatement */:
          return emitSwitchStatement(node);
        case 255 /* LabeledStatement */:
          return emitLabeledStatement(node);
        case 256 /* ThrowStatement */:
          return emitThrowStatement(node);
        case 257 /* TryStatement */:
          return emitTryStatement(node);
        case 258 /* DebuggerStatement */:
          return emitDebuggerStatement(node);
        case 259 /* VariableDeclaration */:
          return emitVariableDeclaration(node);
        case 260 /* VariableDeclarationList */:
          return emitVariableDeclarationList(node);
        case 261 /* FunctionDeclaration */:
          return emitFunctionDeclaration(node);
        case 262 /* ClassDeclaration */:
          return emitClassDeclaration(node);
        case 263 /* InterfaceDeclaration */:
          return emitInterfaceDeclaration(node);
        case 264 /* TypeAliasDeclaration */:
          return emitTypeAliasDeclaration(node);
        case 265 /* EnumDeclaration */:
          return emitEnumDeclaration(node);
        case 266 /* ModuleDeclaration */:
          return emitModuleDeclaration(node);
        case 267 /* ModuleBlock */:
          return emitModuleBlock(node);
        case 268 /* CaseBlock */:
          return emitCaseBlock(node);
        case 269 /* NamespaceExportDeclaration */:
          return emitNamespaceExportDeclaration(node);
        case 270 /* ImportEqualsDeclaration */:
          return emitImportEqualsDeclaration(node);
        case 271 /* ImportDeclaration */:
          return emitImportDeclaration(node);
        case 272 /* ImportClause */:
          return emitImportClause(node);
        case 273 /* NamespaceImport */:
          return emitNamespaceImport(node);
        case 279 /* NamespaceExport */:
          return emitNamespaceExport(node);
        case 274 /* NamedImports */:
          return emitNamedImports(node);
        case 275 /* ImportSpecifier */:
          return emitImportSpecifier(node);
        case 276 /* ExportAssignment */:
          return emitExportAssignment(node);
        case 277 /* ExportDeclaration */:
          return emitExportDeclaration(node);
        case 278 /* NamedExports */:
          return emitNamedExports(node);
        case 280 /* ExportSpecifier */:
          return emitExportSpecifier(node);
        case 299 /* AssertClause */:
          return emitAssertClause(node);
        case 300 /* AssertEntry */:
          return emitAssertEntry(node);
        case 281 /* MissingDeclaration */:
          return;
        case 282 /* ExternalModuleReference */:
          return emitExternalModuleReference(node);
        case 12 /* JsxText */:
          return emitJsxText(node);
        case 285 /* JsxOpeningElement */:
        case 288 /* JsxOpeningFragment */:
          return emitJsxOpeningElementOrFragment(node);
        case 286 /* JsxClosingElement */:
        case 289 /* JsxClosingFragment */:
          return emitJsxClosingElementOrFragment(node);
        case 290 /* JsxAttribute */:
          return emitJsxAttribute(node);
        case 291 /* JsxAttributes */:
          return emitJsxAttributes(node);
        case 292 /* JsxSpreadAttribute */:
          return emitJsxSpreadAttribute(node);
        case 293 /* JsxExpression */:
          return emitJsxExpression(node);
        case 294 /* JsxNamespacedName */:
          return emitJsxNamespacedName(node);
        case 295 /* CaseClause */:
          return emitCaseClause(node);
        case 296 /* DefaultClause */:
          return emitDefaultClause(node);
        case 297 /* HeritageClause */:
          return emitHeritageClause(node);
        case 298 /* CatchClause */:
          return emitCatchClause(node);
        case 302 /* PropertyAssignment */:
          return emitPropertyAssignment(node);
        case 303 /* ShorthandPropertyAssignment */:
          return emitShorthandPropertyAssignment(node);
        case 304 /* SpreadAssignment */:
          return emitSpreadAssignment(node);
        case 305 /* EnumMember */:
          return emitEnumMember(node);
        case 306 /* UnparsedPrologue */:
          return writeUnparsedNode(node);
        case 313 /* UnparsedSource */:
        case 307 /* UnparsedPrepend */:
          return emitUnparsedSourceOrPrepend(node);
        case 308 /* UnparsedText */:
        case 309 /* UnparsedInternalText */:
          return emitUnparsedTextLike(node);
        case 310 /* UnparsedSyntheticReference */:
          return emitUnparsedSyntheticReference(node);
        case 311 /* SourceFile */:
          return emitSourceFile(node);
        case 312 /* Bundle */:
          return Debug.fail("Bundles should be printed using printBundle");
        case 314 /* InputFiles */:
          return Debug.fail("InputFiles should not be printed");
        case 315 /* JSDocTypeExpression */:
          return emitJSDocTypeExpression(node);
        case 316 /* JSDocNameReference */:
          return emitJSDocNameReference(node);
        case 318 /* JSDocAllType */:
          return writePunctuation("*");
        case 319 /* JSDocUnknownType */:
          return writePunctuation("?");
        case 320 /* JSDocNullableType */:
          return emitJSDocNullableType(node);
        case 321 /* JSDocNonNullableType */:
          return emitJSDocNonNullableType(node);
        case 322 /* JSDocOptionalType */:
          return emitJSDocOptionalType(node);
        case 323 /* JSDocFunctionType */:
          return emitJSDocFunctionType(node);
        case 190 /* RestType */:
        case 324 /* JSDocVariadicType */:
          return emitRestOrJSDocVariadicType(node);
        case 325 /* JSDocNamepathType */:
          return;
        case 326 /* JSDoc */:
          return emitJSDoc(node);
        case 328 /* JSDocTypeLiteral */:
          return emitJSDocTypeLiteral(node);
        case 329 /* JSDocSignature */:
          return emitJSDocSignature(node);
        case 333 /* JSDocTag */:
        case 338 /* JSDocClassTag */:
        case 343 /* JSDocOverrideTag */:
          return emitJSDocSimpleTag(node);
        case 334 /* JSDocAugmentsTag */:
        case 335 /* JSDocImplementsTag */:
          return emitJSDocHeritageTag(node);
        case 336 /* JSDocAuthorTag */:
        case 337 /* JSDocDeprecatedTag */:
          return;
        case 339 /* JSDocPublicTag */:
        case 340 /* JSDocPrivateTag */:
        case 341 /* JSDocProtectedTag */:
        case 342 /* JSDocReadonlyTag */:
          return;
        case 344 /* JSDocCallbackTag */:
          return emitJSDocCallbackTag(node);
        case 345 /* JSDocOverloadTag */:
          return emitJSDocOverloadTag(node);
        case 347 /* JSDocParameterTag */:
        case 354 /* JSDocPropertyTag */:
          return emitJSDocPropertyLikeTag(node);
        case 346 /* JSDocEnumTag */:
        case 348 /* JSDocReturnTag */:
        case 349 /* JSDocThisTag */:
        case 350 /* JSDocTypeTag */:
        case 355 /* JSDocThrowsTag */:
        case 356 /* JSDocSatisfiesTag */:
          return emitJSDocSimpleTypedTag(node);
        case 351 /* JSDocTemplateTag */:
          return emitJSDocTemplateTag(node);
        case 352 /* JSDocTypedefTag */:
          return emitJSDocTypedefTag(node);
        case 353 /* JSDocSeeTag */:
          return emitJSDocSeeTag(node);
        case 358 /* NotEmittedStatement */:
          return;
      }
      if (isExpression(node)) {
        hint = 1 /* Expression */;
        if (substituteNode !== noEmitSubstitution) {
          const substitute = substituteNode(hint, node) || node;
          if (substitute !== node) {
            node = substitute;
            if (currentParenthesizerRule) {
              node = currentParenthesizerRule(node);
            }
          }
        }
      }
    }
    if (hint === 1 /* Expression */) {
      switch (node.kind) {
        case 9 /* NumericLiteral */:
        case 10 /* BigIntLiteral */:
          return emitNumericOrBigIntLiteral(node);
        case 11 /* StringLiteral */:
        case 14 /* RegularExpressionLiteral */:
        case 15 /* NoSubstitutionTemplateLiteral */:
          return emitLiteral(
            node,
            /*jsxAttributeEscape*/
            false
          );
        case 80 /* Identifier */:
          return emitIdentifier(node);
        case 81 /* PrivateIdentifier */:
          return emitPrivateIdentifier(node);
        case 208 /* ArrayLiteralExpression */:
          return emitArrayLiteralExpression(node);
        case 209 /* ObjectLiteralExpression */:
          return emitObjectLiteralExpression(node);
        case 210 /* PropertyAccessExpression */:
          return emitPropertyAccessExpression(node);
        case 211 /* ElementAccessExpression */:
          return emitElementAccessExpression(node);
        case 212 /* CallExpression */:
          return emitCallExpression(node);
        case 213 /* NewExpression */:
          return emitNewExpression(node);
        case 214 /* TaggedTemplateExpression */:
          return emitTaggedTemplateExpression(node);
        case 215 /* TypeAssertionExpression */:
          return emitTypeAssertionExpression(node);
        case 216 /* ParenthesizedExpression */:
          return emitParenthesizedExpression(node);
        case 217 /* FunctionExpression */:
          return emitFunctionExpression(node);
        case 218 /* ArrowFunction */:
          return emitArrowFunction(node);
        case 219 /* DeleteExpression */:
          return emitDeleteExpression(node);
        case 220 /* TypeOfExpression */:
          return emitTypeOfExpression(node);
        case 221 /* VoidExpression */:
          return emitVoidExpression(node);
        case 222 /* AwaitExpression */:
          return emitAwaitExpression(node);
        case 223 /* PrefixUnaryExpression */:
          return emitPrefixUnaryExpression(node);
        case 224 /* PostfixUnaryExpression */:
          return emitPostfixUnaryExpression(node);
        case 225 /* BinaryExpression */:
          return emitBinaryExpression(node);
        case 226 /* ConditionalExpression */:
          return emitConditionalExpression(node);
        case 227 /* TemplateExpression */:
          return emitTemplateExpression(node);
        case 228 /* YieldExpression */:
          return emitYieldExpression(node);
        case 229 /* SpreadElement */:
          return emitSpreadElement(node);
        case 230 /* ClassExpression */:
          return emitClassExpression(node);
        case 231 /* OmittedExpression */:
          return;
        case 233 /* AsExpression */:
          return emitAsExpression(node);
        case 234 /* NonNullExpression */:
          return emitNonNullExpression(node);
        case 232 /* ExpressionWithTypeArguments */:
          return emitExpressionWithTypeArguments(node);
        case 237 /* SatisfiesExpression */:
          return emitSatisfiesExpression(node);
        case 235 /* MetaProperty */:
          return emitMetaProperty(node);
        case 236 /* SyntheticExpression */:
          return Debug.fail("SyntheticExpression should never be printed.");
        case 281 /* MissingDeclaration */:
          return;
        case 283 /* JsxElement */:
          return emitJsxElement(node);
        case 284 /* JsxSelfClosingElement */:
          return emitJsxSelfClosingElement(node);
        case 287 /* JsxFragment */:
          return emitJsxFragment(node);
        case 357 /* SyntaxList */:
          return Debug.fail("SyntaxList should not be printed");
        case 358 /* NotEmittedStatement */:
          return;
        case 359 /* PartiallyEmittedExpression */:
          return emitPartiallyEmittedExpression(node);
        case 360 /* CommaListExpression */:
          return emitCommaList(node);
        case 361 /* SyntheticReferenceExpression */:
          return Debug.fail("SyntheticReferenceExpression should not be printed");
      }
    }
    if (isKeyword(node.kind))
      return writeTokenNode(node, writeKeyword);
    if (isTokenKind(node.kind))
      return writeTokenNode(node, writePunctuation);
    Debug.fail(`Unhandled SyntaxKind: ${Debug.formatSyntaxKind(node.kind)}.`);
  }
  function emitMappedTypeParameter(node) {
    emit(node.name);
    writeSpace();
    writeKeyword("in");
    writeSpace();
    emit(node.constraint);
  }
  function pipelineEmitWithSubstitution(hint, node) {
    const pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
    Debug.assertIsDefined(lastSubstitution);
    node = lastSubstitution;
    lastSubstitution = void 0;
    pipelinePhase(hint, node);
  }
  function getHelpersFromBundledSourceFiles(bundle) {
    let result;
    if (moduleKind === 0 /* None */ || printerOptions.noEmitHelpers) {
      return void 0;
    }
    const bundledHelpers2 = /* @__PURE__ */ new Map();
    for (const sourceFile of bundle.sourceFiles) {
      const shouldSkip = getExternalHelpersModuleName(sourceFile) !== void 0;
      const helpers = getSortedEmitHelpers(sourceFile);
      if (!helpers)
        continue;
      for (const helper of helpers) {
        if (!helper.scoped && !shouldSkip && !bundledHelpers2.get(helper.name)) {
          bundledHelpers2.set(helper.name, true);
          (result || (result = [])).push(helper.name);
        }
      }
    }
    return result;
  }
  function emitHelpers(node) {
    let helpersEmitted = false;
    const bundle = node.kind === 312 /* Bundle */ ? node : void 0;
    if (bundle && moduleKind === 0 /* None */) {
      return;
    }
    const numPrepends = bundle ? bundle.prepends.length : 0;
    const numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
    for (let i = 0; i < numNodes; i++) {
      const currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
      const sourceFile = isSourceFile(currentNode) ? currentNode : isUnparsedSource(currentNode) ? void 0 : currentSourceFile;
      const shouldSkip = printerOptions.noEmitHelpers || !!sourceFile && hasRecordedExternalHelpers(sourceFile);
      const shouldBundle = (isSourceFile(currentNode) || isUnparsedSource(currentNode)) && !isOwnFileEmit;
      const helpers = isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
      if (helpers) {
        for (const helper of helpers) {
          if (!helper.scoped) {
            if (shouldSkip)
              continue;
            if (shouldBundle) {
              if (bundledHelpers.get(helper.name)) {
                continue;
              }
              bundledHelpers.set(helper.name, true);
            }
          } else if (bundle) {
            continue;
          }
          const pos = getTextPosWithWriteLine();
          if (typeof helper.text === "string") {
            writeLines(helper.text);
          } else {
            writeLines(helper.text(makeFileLevelOptimisticUniqueName));
          }
          if (bundleFileInfo)
            bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
          helpersEmitted = true;
        }
      }
    }
    return helpersEmitted;
  }
  function getSortedEmitHelpers(node) {
    const helpers = getEmitHelpers(node);
    return helpers && stableSort(helpers, compareEmitHelpers);
  }
  function emitNumericOrBigIntLiteral(node) {
    emitLiteral(
      node,
      /*jsxAttributeEscape*/
      false
    );
  }
  function emitLiteral(node, jsxAttributeEscape) {
    const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
    if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind))) {
      writeLiteral(text);
    } else {
      writeStringLiteral(text);
    }
  }
  function emitUnparsedSourceOrPrepend(unparsed) {
    for (const text of unparsed.texts) {
      writeLine();
      emit(text);
    }
  }
  function writeUnparsedNode(unparsed) {
    writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
  }
  function emitUnparsedTextLike(unparsed) {
    const pos = getTextPosWithWriteLine();
    writeUnparsedNode(unparsed);
    if (bundleFileInfo) {
      updateOrPushBundleFileTextLike(
        pos,
        writer.getTextPos(),
        unparsed.kind === 308 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */
      );
    }
  }
  function emitUnparsedSyntheticReference(unparsed) {
    const pos = getTextPosWithWriteLine();
    writeUnparsedNode(unparsed);
    if (bundleFileInfo) {
      const section = clone(unparsed.section);
      section.pos = pos;
      section.end = writer.getTextPos();
      bundleFileInfo.sections.push(section);
    }
  }
  function emitSnippetNode(hint, node, snippet) {
    switch (snippet.kind) {
      case 1 /* Placeholder */:
        emitPlaceholder(hint, node, snippet);
        break;
      case 0 /* TabStop */:
        emitTabStop(hint, node, snippet);
        break;
    }
  }
  function emitPlaceholder(hint, node, snippet) {
    nonEscapingWrite(`\${${snippet.order}:`);
    pipelineEmitWithHintWorker(
      hint,
      node,
      /*allowSnippets*/
      false
    );
    nonEscapingWrite(`}`);
  }
  function emitTabStop(hint, node, snippet) {
    Debug.assert(
      node.kind === 241 /* EmptyStatement */,
      `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`
    );
    Debug.assert(
      hint !== 5 /* EmbeddedStatement */,
      `A tab stop cannot be attached to an embedded statement.`
    );
    nonEscapingWrite(`$${snippet.order}`);
  }
  function emitIdentifier(node) {
    const writeText = node.symbol ? writeSymbol : write;
    writeText(getTextOfNode2(
      node,
      /*includeTrivia*/
      false
    ), node.symbol);
    emitList(node, getIdentifierTypeArguments(node), 53776 /* TypeParameters */);
  }
  function emitPrivateIdentifier(node) {
    write(getTextOfNode2(
      node,
      /*includeTrivia*/
      false
    ));
  }
  function emitQualifiedName(node) {
    emitEntityName(node.left);
    writePunctuation(".");
    emit(node.right);
  }
  function emitEntityName(node) {
    if (node.kind === 80 /* Identifier */) {
      emitExpression(node);
    } else {
      emit(node);
    }
  }
  function emitComputedPropertyName(node) {
    const savedPrivateNameTempFlags = privateNameTempFlags;
    const savedReservedMemberNames = reservedPrivateNames;
    popPrivateNameGenerationScope();
    writePunctuation("[");
    emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName);
    writePunctuation("]");
    pushPrivateNameGenerationScope(savedPrivateNameTempFlags, savedReservedMemberNames);
  }
  function emitTypeParameter(node) {
    emitModifierList(node, node.modifiers);
    emit(node.name);
    if (node.constraint) {
      writeSpace();
      writeKeyword("extends");
      writeSpace();
      emit(node.constraint);
    }
    if (node.default) {
      writeSpace();
      writeOperator("=");
      writeSpace();
      emit(node.default);
    }
  }
  function emitParameter(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      true
    );
    emit(node.dotDotDotToken);
    emitNodeWithWriter(node.name, writeParameter);
    emit(node.questionToken);
    if (node.parent && node.parent.kind === 323 /* JSDocFunctionType */ && !node.name) {
      emit(node.type);
    } else {
      emitTypeAnnotation(node.type);
    }
    emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitDecorator(decorator) {
    writePunctuation("@");
    emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess);
  }
  function emitPropertySignature(node) {
    emitModifierList(node, node.modifiers);
    emitNodeWithWriter(node.name, writeProperty);
    emit(node.questionToken);
    emitTypeAnnotation(node.type);
    writeTrailingSemicolon();
  }
  function emitPropertyDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      true
    );
    emit(node.name);
    emit(node.questionToken);
    emit(node.exclamationToken);
    emitTypeAnnotation(node.type);
    emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
    writeTrailingSemicolon();
  }
  function emitMethodSignature(node) {
    pushNameGenerationScope(node);
    emitModifierList(node, node.modifiers);
    emit(node.name);
    emit(node.questionToken);
    emitTypeParameters(node, node.typeParameters);
    emitParameters(node, node.parameters);
    emitTypeAnnotation(node.type);
    writeTrailingSemicolon();
    popNameGenerationScope(node);
  }
  function emitMethodDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      true
    );
    emit(node.asteriskToken);
    emit(node.name);
    emit(node.questionToken);
    emitSignatureAndBody(node, emitSignatureHead);
  }
  function emitClassStaticBlockDeclaration(node) {
    writeKeyword("static");
    emitBlockFunctionBody(node.body);
  }
  function emitConstructor(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    writeKeyword("constructor");
    emitSignatureAndBody(node, emitSignatureHead);
  }
  function emitAccessorDeclaration(node) {
    const pos = emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      true
    );
    const token = node.kind === 176 /* GetAccessor */ ? 139 /* GetKeyword */ : 153 /* SetKeyword */;
    emitTokenWithComment(token, pos, writeKeyword, node);
    writeSpace();
    emit(node.name);
    emitSignatureAndBody(node, emitSignatureHead);
  }
  function emitCallSignature(node) {
    pushNameGenerationScope(node);
    emitTypeParameters(node, node.typeParameters);
    emitParameters(node, node.parameters);
    emitTypeAnnotation(node.type);
    writeTrailingSemicolon();
    popNameGenerationScope(node);
  }
  function emitConstructSignature(node) {
    pushNameGenerationScope(node);
    writeKeyword("new");
    writeSpace();
    emitTypeParameters(node, node.typeParameters);
    emitParameters(node, node.parameters);
    emitTypeAnnotation(node.type);
    writeTrailingSemicolon();
    popNameGenerationScope(node);
  }
  function emitIndexSignature(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    emitParametersForIndexSignature(node, node.parameters);
    emitTypeAnnotation(node.type);
    writeTrailingSemicolon();
  }
  function emitTemplateTypeSpan(node) {
    emit(node.type);
    emit(node.literal);
  }
  function emitSemicolonClassElement() {
    writeTrailingSemicolon();
  }
  function emitTypePredicate(node) {
    if (node.assertsModifier) {
      emit(node.assertsModifier);
      writeSpace();
    }
    emit(node.parameterName);
    if (node.type) {
      writeSpace();
      writeKeyword("is");
      writeSpace();
      emit(node.type);
    }
  }
  function emitTypeReference(node) {
    emit(node.typeName);
    emitTypeArguments(node, node.typeArguments);
  }
  function emitFunctionType(node) {
    pushNameGenerationScope(node);
    emitTypeParameters(node, node.typeParameters);
    emitParametersForArrow(node, node.parameters);
    writeSpace();
    writePunctuation("=>");
    writeSpace();
    emit(node.type);
    popNameGenerationScope(node);
  }
  function emitJSDocFunctionType(node) {
    writeKeyword("function");
    emitParameters(node, node.parameters);
    writePunctuation(":");
    emit(node.type);
  }
  function emitJSDocNullableType(node) {
    writePunctuation("?");
    emit(node.type);
  }
  function emitJSDocNonNullableType(node) {
    writePunctuation("!");
    emit(node.type);
  }
  function emitJSDocOptionalType(node) {
    emit(node.type);
    writePunctuation("=");
  }
  function emitConstructorType(node) {
    pushNameGenerationScope(node);
    emitModifierList(node, node.modifiers);
    writeKeyword("new");
    writeSpace();
    emitTypeParameters(node, node.typeParameters);
    emitParameters(node, node.parameters);
    writeSpace();
    writePunctuation("=>");
    writeSpace();
    emit(node.type);
    popNameGenerationScope(node);
  }
  function emitTypeQuery(node) {
    writeKeyword("typeof");
    writeSpace();
    emit(node.exprName);
    emitTypeArguments(node, node.typeArguments);
  }
  function emitTypeLiteral(node) {
    pushPrivateNameGenerationScope(
      0 /* Auto */,
      /*newReservedMemberNames*/
      void 0
    );
    writePunctuation("{");
    const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
    emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
    writePunctuation("}");
    popPrivateNameGenerationScope();
  }
  function emitArrayType(node) {
    emit(node.elementType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType);
    writePunctuation("[");
    writePunctuation("]");
  }
  function emitRestOrJSDocVariadicType(node) {
    writePunctuation("...");
    emit(node.type);
  }
  function emitTupleType(node) {
    emitTokenWithComment(23 /* OpenBracketToken */, node.pos, writePunctuation, node);
    const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */;
    emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */, parenthesizer.parenthesizeElementTypeOfTupleType);
    emitTokenWithComment(24 /* CloseBracketToken */, node.elements.end, writePunctuation, node);
  }
  function emitNamedTupleMember(node) {
    emit(node.dotDotDotToken);
    emit(node.name);
    emit(node.questionToken);
    emitTokenWithComment(59 /* ColonToken */, node.name.end, writePunctuation, node);
    writeSpace();
    emit(node.type);
  }
  function emitOptionalType(node) {
    emit(node.type, parenthesizer.parenthesizeTypeOfOptionalType);
    writePunctuation("?");
  }
  function emitUnionType(node) {
    emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeConstituentTypeOfUnionType);
  }
  function emitIntersectionType(node) {
    emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeConstituentTypeOfIntersectionType);
  }
  function emitConditionalType(node) {
    emit(node.checkType, parenthesizer.parenthesizeCheckTypeOfConditionalType);
    writeSpace();
    writeKeyword("extends");
    writeSpace();
    emit(node.extendsType, parenthesizer.parenthesizeExtendsTypeOfConditionalType);
    writeSpace();
    writePunctuation("?");
    writeSpace();
    emit(node.trueType);
    writeSpace();
    writePunctuation(":");
    writeSpace();
    emit(node.falseType);
  }
  function emitInferType(node) {
    writeKeyword("infer");
    writeSpace();
    emit(node.typeParameter);
  }
  function emitParenthesizedType(node) {
    writePunctuation("(");
    emit(node.type);
    writePunctuation(")");
  }
  function emitThisType() {
    writeKeyword("this");
  }
  function emitTypeOperator(node) {
    writeTokenText(node.operator, writeKeyword);
    writeSpace();
    const parenthesizerRule = node.operator === 148 /* ReadonlyKeyword */ ? parenthesizer.parenthesizeOperandOfReadonlyTypeOperator : parenthesizer.parenthesizeOperandOfTypeOperator;
    emit(node.type, parenthesizerRule);
  }
  function emitIndexedAccessType(node) {
    emit(node.objectType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType);
    writePunctuation("[");
    emit(node.indexType);
    writePunctuation("]");
  }
  function emitMappedType(node) {
    const emitFlags = getEmitFlags(node);
    writePunctuation("{");
    if (emitFlags & 1 /* SingleLine */) {
      writeSpace();
    } else {
      writeLine();
      increaseIndent();
    }
    if (node.readonlyToken) {
      emit(node.readonlyToken);
      if (node.readonlyToken.kind !== 148 /* ReadonlyKeyword */) {
        writeKeyword("readonly");
      }
      writeSpace();
    }
    writePunctuation("[");
    pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
    if (node.nameType) {
      writeSpace();
      writeKeyword("as");
      writeSpace();
      emit(node.nameType);
    }
    writePunctuation("]");
    if (node.questionToken) {
      emit(node.questionToken);
      if (node.questionToken.kind !== 58 /* QuestionToken */) {
        writePunctuation("?");
      }
    }
    writePunctuation(":");
    writeSpace();
    emit(node.type);
    writeTrailingSemicolon();
    if (emitFlags & 1 /* SingleLine */) {
      writeSpace();
    } else {
      writeLine();
      decreaseIndent();
    }
    emitList(node, node.members, 2 /* PreserveLines */);
    writePunctuation("}");
  }
  function emitLiteralType(node) {
    emitExpression(node.literal);
  }
  function emitTemplateType(node) {
    emit(node.head);
    emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
  }
  function emitImportTypeNode(node) {
    if (node.isTypeOf) {
      writeKeyword("typeof");
      writeSpace();
    }
    writeKeyword("import");
    writePunctuation("(");
    emit(node.argument);
    if (node.assertions) {
      writePunctuation(",");
      writeSpace();
      writePunctuation("{");
      writeSpace();
      writeKeyword("assert");
      writePunctuation(":");
      writeSpace();
      const elements = node.assertions.assertClause.elements;
      emitList(node.assertions.assertClause, elements, 526226 /* ImportClauseEntries */);
      writeSpace();
      writePunctuation("}");
    }
    writePunctuation(")");
    if (node.qualifier) {
      writePunctuation(".");
      emit(node.qualifier);
    }
    emitTypeArguments(node, node.typeArguments);
  }
  function emitObjectBindingPattern(node) {
    writePunctuation("{");
    emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
    writePunctuation("}");
  }
  function emitArrayBindingPattern(node) {
    writePunctuation("[");
    emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
    writePunctuation("]");
  }
  function emitBindingElement(node) {
    emit(node.dotDotDotToken);
    if (node.propertyName) {
      emit(node.propertyName);
      writePunctuation(":");
      writeSpace();
    }
    emit(node.name);
    emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitArrayLiteralExpression(node) {
    const elements = node.elements;
    const preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
    emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitObjectLiteralExpression(node) {
    pushPrivateNameGenerationScope(
      0 /* Auto */,
      /*newReservedMemberNames*/
      void 0
    );
    forEach(node.properties, generateMemberNames);
    const indentedFlag = getEmitFlags(node) & 131072 /* Indented */;
    if (indentedFlag) {
      increaseIndent();
    }
    const preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
    const allowTrailingComma = currentSourceFile && currentSourceFile.languageVersion >= 1 /* ES5 */ && !isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
    emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
    if (indentedFlag) {
      decreaseIndent();
    }
    popPrivateNameGenerationScope();
  }
  function emitPropertyAccessExpression(node) {
    emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
    const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(25 /* DotToken */), node.expression.end, node.name.pos);
    const linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
    const linesAfterDot = getLinesBetweenNodes(node, token, node.name);
    writeLinesAndIndent(
      linesBeforeDot,
      /*writeSpaceIfNotIndenting*/
      false
    );
    const shouldEmitDotDot = token.kind !== 29 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace();
    if (shouldEmitDotDot) {
      writePunctuation(".");
    }
    if (node.questionDotToken) {
      emit(token);
    } else {
      emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
    }
    writeLinesAndIndent(
      linesAfterDot,
      /*writeSpaceIfNotIndenting*/
      false
    );
    emit(node.name);
    decreaseIndentIf(linesBeforeDot, linesAfterDot);
  }
  function mayNeedDotDotForPropertyAccess(expression) {
    expression = skipPartiallyEmittedExpressions(expression);
    if (isNumericLiteral(expression)) {
      const text = getLiteralTextOfNode(
        expression,
        /*neverAsciiEscape*/
        true,
        /*jsxAttributeEscape*/
        false
      );
      return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !stringContains(text, tokenToString(25 /* DotToken */)) && !stringContains(text, String.fromCharCode(69 /* E */)) && !stringContains(text, String.fromCharCode(101 /* e */));
    } else if (isAccessExpression(expression)) {
      const constantValue = getConstantValue(expression);
      return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue;
    }
  }
  function emitElementAccessExpression(node) {
    emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
    emit(node.questionDotToken);
    emitTokenWithComment(23 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
    emitExpression(node.argumentExpression);
    emitTokenWithComment(24 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
  }
  function emitCallExpression(node) {
    const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */;
    if (indirectCall) {
      writePunctuation("(");
      writeLiteral("0");
      writePunctuation(",");
      writeSpace();
    }
    emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
    if (indirectCall) {
      writePunctuation(")");
    }
    emit(node.questionDotToken);
    emitTypeArguments(node, node.typeArguments);
    emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitNewExpression(node) {
    emitTokenWithComment(105 /* NewKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew);
    emitTypeArguments(node, node.typeArguments);
    emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitTaggedTemplateExpression(node) {
    const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */;
    if (indirectCall) {
      writePunctuation("(");
      writeLiteral("0");
      writePunctuation(",");
      writeSpace();
    }
    emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess);
    if (indirectCall) {
      writePunctuation(")");
    }
    emitTypeArguments(node, node.typeArguments);
    writeSpace();
    emitExpression(node.template);
  }
  function emitTypeAssertionExpression(node) {
    writePunctuation("<");
    emit(node.type);
    writePunctuation(">");
    emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
  }
  function emitParenthesizedExpression(node) {
    const openParenPos = emitTokenWithComment(21 /* OpenParenToken */, node.pos, writePunctuation, node);
    const indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
    emitExpression(
      node.expression,
      /*parenthesizerRule*/
      void 0
    );
    writeLineSeparatorsAfter(node.expression, node);
    decreaseIndentIf(indented);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
  }
  function emitFunctionExpression(node) {
    generateNameIfNeeded(node.name);
    emitFunctionDeclarationOrExpression(node);
  }
  function emitArrowFunction(node) {
    emitModifierList(node, node.modifiers);
    emitSignatureAndBody(node, emitArrowFunctionHead);
  }
  function emitArrowFunctionHead(node) {
    emitTypeParameters(node, node.typeParameters);
    emitParametersForArrow(node, node.parameters);
    emitTypeAnnotation(node.type);
    writeSpace();
    emit(node.equalsGreaterThanToken);
  }
  function emitDeleteExpression(node) {
    emitTokenWithComment(91 /* DeleteKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
  }
  function emitTypeOfExpression(node) {
    emitTokenWithComment(114 /* TypeOfKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
  }
  function emitVoidExpression(node) {
    emitTokenWithComment(116 /* VoidKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
  }
  function emitAwaitExpression(node) {
    emitTokenWithComment(135 /* AwaitKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary);
  }
  function emitPrefixUnaryExpression(node) {
    writeTokenText(node.operator, writeOperator);
    if (shouldEmitWhitespaceBeforeOperand(node)) {
      writeSpace();
    }
    emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary);
  }
  function shouldEmitWhitespaceBeforeOperand(node) {
    const operand = node.operand;
    return operand.kind === 223 /* PrefixUnaryExpression */ && (node.operator === 40 /* PlusToken */ && (operand.operator === 40 /* PlusToken */ || operand.operator === 46 /* PlusPlusToken */) || node.operator === 41 /* MinusToken */ && (operand.operator === 41 /* MinusToken */ || operand.operator === 47 /* MinusMinusToken */));
  }
  function emitPostfixUnaryExpression(node) {
    emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary);
    writeTokenText(node.operator, writeOperator);
  }
  function createEmitBinaryExpression() {
    return createBinaryExpressionTrampoline(
      onEnter,
      onLeft,
      onOperator,
      onRight,
      onExit,
      /*foldState*/
      void 0
    );
    function onEnter(node, state) {
      if (state) {
        state.stackIndex++;
        state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines;
        state.containerPosStack[state.stackIndex] = containerPos;
        state.containerEndStack[state.stackIndex] = containerEnd;
        state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd;
        const emitComments2 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node);
        const emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node);
        onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node);
        if (emitComments2)
          emitCommentsBeforeNode(node);
        if (emitSourceMaps)
          emitSourceMapsBeforeNode(node);
        beforeEmitNode(node);
      } else {
        state = {
          stackIndex: 0,
          preserveSourceNewlinesStack: [void 0],
          containerPosStack: [-1],
          containerEndStack: [-1],
          declarationListContainerEndStack: [-1],
          shouldEmitCommentsStack: [false],
          shouldEmitSourceMapsStack: [false]
        };
      }
      return state;
    }
    function onLeft(next, _workArea, parent2) {
      return maybeEmitExpression(next, parent2, "left");
    }
    function onOperator(operatorToken, _state, node) {
      const isCommaOperator = operatorToken.kind !== 28 /* CommaToken */;
      const linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken);
      const linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right);
      writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
      emitLeadingCommentsOfPosition(operatorToken.pos);
      writeTokenNode(operatorToken, operatorToken.kind === 103 /* InKeyword */ ? writeKeyword : writeOperator);
      emitTrailingCommentsOfPosition(
        operatorToken.end,
        /*prefixSpace*/
        true
      );
      writeLinesAndIndent(
        linesAfterOperator,
        /*writeSpaceIfNotIndenting*/
        true
      );
    }
    function onRight(next, _workArea, parent2) {
      return maybeEmitExpression(next, parent2, "right");
    }
    function onExit(node, state) {
      const linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
      const linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
      decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
      if (state.stackIndex > 0) {
        const savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex];
        const savedContainerPos = state.containerPosStack[state.stackIndex];
        const savedContainerEnd = state.containerEndStack[state.stackIndex];
        const savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex];
        const shouldEmitComments2 = state.shouldEmitCommentsStack[state.stackIndex];
        const shouldEmitSourceMaps2 = state.shouldEmitSourceMapsStack[state.stackIndex];
        afterEmitNode(savedPreserveSourceNewlines);
        if (shouldEmitSourceMaps2)
          emitSourceMapsAfterNode(node);
        if (shouldEmitComments2)
          emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
        onAfterEmitNode == null ? void 0 : onAfterEmitNode(node);
        state.stackIndex--;
      }
    }
    function maybeEmitExpression(next, parent2, side) {
      const parenthesizerRule = side === "left" ? parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent2.operatorToken.kind) : parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent2.operatorToken.kind);
      let pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
      if (pipelinePhase === pipelineEmitWithSubstitution) {
        Debug.assertIsDefined(lastSubstitution);
        next = parenthesizerRule(cast(lastSubstitution, isExpression));
        pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next);
        lastSubstitution = void 0;
      }
      if (pipelinePhase === pipelineEmitWithComments || pipelinePhase === pipelineEmitWithSourceMaps || pipelinePhase === pipelineEmitWithHint) {
        if (isBinaryExpression(next)) {
          return next;
        }
      }
      currentParenthesizerRule = parenthesizerRule;
      pipelinePhase(1 /* Expression */, next);
    }
  }
  function emitConditionalExpression(node) {
    const linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
    const linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
    const linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
    const linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
    emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression);
    writeLinesAndIndent(
      linesBeforeQuestion,
      /*writeSpaceIfNotIndenting*/
      true
    );
    emit(node.questionToken);
    writeLinesAndIndent(
      linesAfterQuestion,
      /*writeSpaceIfNotIndenting*/
      true
    );
    emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression);
    decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
    writeLinesAndIndent(
      linesBeforeColon,
      /*writeSpaceIfNotIndenting*/
      true
    );
    emit(node.colonToken);
    writeLinesAndIndent(
      linesAfterColon,
      /*writeSpaceIfNotIndenting*/
      true
    );
    emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression);
    decreaseIndentIf(linesBeforeColon, linesAfterColon);
  }
  function emitTemplateExpression(node) {
    emit(node.head);
    emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
  }
  function emitYieldExpression(node) {
    emitTokenWithComment(127 /* YieldKeyword */, node.pos, writeKeyword, node);
    emit(node.asteriskToken);
    emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma);
  }
  function emitSpreadElement(node) {
    emitTokenWithComment(26 /* DotDotDotToken */, node.pos, writePunctuation, node);
    emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitClassExpression(node) {
    generateNameIfNeeded(node.name);
    emitClassDeclarationOrExpression(node);
  }
  function emitExpressionWithTypeArguments(node) {
    emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
    emitTypeArguments(node, node.typeArguments);
  }
  function emitAsExpression(node) {
    emitExpression(
      node.expression,
      /*parenthesizerRule*/
      void 0
    );
    if (node.type) {
      writeSpace();
      writeKeyword("as");
      writeSpace();
      emit(node.type);
    }
  }
  function emitNonNullExpression(node) {
    emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
    writeOperator("!");
  }
  function emitSatisfiesExpression(node) {
    emitExpression(
      node.expression,
      /*parenthesizerRule*/
      void 0
    );
    if (node.type) {
      writeSpace();
      writeKeyword("satisfies");
      writeSpace();
      emit(node.type);
    }
  }
  function emitMetaProperty(node) {
    writeToken(node.keywordToken, node.pos, writePunctuation);
    writePunctuation(".");
    emit(node.name);
  }
  function emitTemplateSpan(node) {
    emitExpression(node.expression);
    emit(node.literal);
  }
  function emitBlock(node) {
    emitBlockStatements(
      node,
      /*forceSingleLine*/
      !node.multiLine && isEmptyBlock(node)
    );
  }
  function emitBlockStatements(node, forceSingleLine) {
    emitTokenWithComment(
      19 /* OpenBraceToken */,
      node.pos,
      writePunctuation,
      /*contextNode*/
      node
    );
    const format = forceSingleLine || getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
    emitList(node, node.statements, format);
    emitTokenWithComment(
      20 /* CloseBraceToken */,
      node.statements.end,
      writePunctuation,
      /*contextNode*/
      node,
      /*indentLeading*/
      !!(format & 1 /* MultiLine */)
    );
  }
  function emitVariableStatement(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    emit(node.declarationList);
    writeTrailingSemicolon();
  }
  function emitEmptyStatement(isEmbeddedStatement) {
    if (isEmbeddedStatement) {
      writePunctuation(";");
    } else {
      writeTrailingSemicolon();
    }
  }
  function emitExpressionStatement(node) {
    emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement);
    if (!currentSourceFile || !isJsonSourceFile(currentSourceFile) || nodeIsSynthesized(node.expression)) {
      writeTrailingSemicolon();
    }
  }
  function emitIfStatement(node) {
    const openParenPos = emitTokenWithComment(101 /* IfKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
    emitExpression(node.expression);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node);
    emitEmbeddedStatement(node, node.thenStatement);
    if (node.elseStatement) {
      writeLineOrSpace(node, node.thenStatement, node.elseStatement);
      emitTokenWithComment(93 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
      if (node.elseStatement.kind === 244 /* IfStatement */) {
        writeSpace();
        emit(node.elseStatement);
      } else {
        emitEmbeddedStatement(node, node.elseStatement);
      }
    }
  }
  function emitWhileClause(node, startPos) {
    const openParenPos = emitTokenWithComment(117 /* WhileKeyword */, startPos, writeKeyword, node);
    writeSpace();
    emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
    emitExpression(node.expression);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node);
  }
  function emitDoStatement(node) {
    emitTokenWithComment(92 /* DoKeyword */, node.pos, writeKeyword, node);
    emitEmbeddedStatement(node, node.statement);
    if (isBlock(node.statement) && !preserveSourceNewlines) {
      writeSpace();
    } else {
      writeLineOrSpace(node, node.statement, node.expression);
    }
    emitWhileClause(node, node.statement.end);
    writeTrailingSemicolon();
  }
  function emitWhileStatement(node) {
    emitWhileClause(node, node.pos);
    emitEmbeddedStatement(node, node.statement);
  }
  function emitForStatement(node) {
    const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    let pos = emitTokenWithComment(
      21 /* OpenParenToken */,
      openParenPos,
      writePunctuation,
      /*contextNode*/
      node
    );
    emitForBinding(node.initializer);
    pos = emitTokenWithComment(27 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
    emitExpressionWithLeadingSpace(node.condition);
    pos = emitTokenWithComment(27 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
    emitExpressionWithLeadingSpace(node.incrementor);
    emitTokenWithComment(22 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
    emitEmbeddedStatement(node, node.statement);
  }
  function emitForInStatement(node) {
    const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
    emitForBinding(node.initializer);
    writeSpace();
    emitTokenWithComment(103 /* InKeyword */, node.initializer.end, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node);
    emitEmbeddedStatement(node, node.statement);
  }
  function emitForOfStatement(node) {
    const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitWithTrailingSpace(node.awaitModifier);
    emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
    emitForBinding(node.initializer);
    writeSpace();
    emitTokenWithComment(164 /* OfKeyword */, node.initializer.end, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node);
    emitEmbeddedStatement(node, node.statement);
  }
  function emitForBinding(node) {
    if (node !== void 0) {
      if (node.kind === 260 /* VariableDeclarationList */) {
        emit(node);
      } else {
        emitExpression(node);
      }
    }
  }
  function emitContinueStatement(node) {
    emitTokenWithComment(88 /* ContinueKeyword */, node.pos, writeKeyword, node);
    emitWithLeadingSpace(node.label);
    writeTrailingSemicolon();
  }
  function emitBreakStatement(node) {
    emitTokenWithComment(83 /* BreakKeyword */, node.pos, writeKeyword, node);
    emitWithLeadingSpace(node.label);
    writeTrailingSemicolon();
  }
  function emitTokenWithComment(token, pos, writer2, contextNode, indentLeading) {
    const node = getParseTreeNode(contextNode);
    const isSimilarNode = node && node.kind === contextNode.kind;
    const startPos = pos;
    if (isSimilarNode && currentSourceFile) {
      pos = skipTrivia(currentSourceFile.text, pos);
    }
    if (isSimilarNode && contextNode.pos !== startPos) {
      const needsIndent = indentLeading && currentSourceFile && !positionsAreOnSameLine(startPos, pos, currentSourceFile);
      if (needsIndent) {
        increaseIndent();
      }
      emitLeadingCommentsOfPosition(startPos);
      if (needsIndent) {
        decreaseIndent();
      }
    }
    pos = writeTokenText(token, writer2, pos);
    if (isSimilarNode && contextNode.end !== pos) {
      const isJsxExprContext = contextNode.kind === 293 /* JsxExpression */;
      emitTrailingCommentsOfPosition(
        pos,
        /*prefixSpace*/
        !isJsxExprContext,
        /*forceNoNewline*/
        isJsxExprContext
      );
    }
    return pos;
  }
  function commentWillEmitNewLine(node) {
    return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine;
  }
  function willEmitLeadingNewLine(node) {
    if (!currentSourceFile)
      return false;
    if (some(getLeadingCommentRanges(currentSourceFile.text, node.pos), commentWillEmitNewLine))
      return true;
    if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine))
      return true;
    if (isPartiallyEmittedExpression(node)) {
      if (node.pos !== node.expression.pos) {
        if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine))
          return true;
      }
      return willEmitLeadingNewLine(node.expression);
    }
    return false;
  }
  function parenthesizeExpressionForNoAsi(node) {
    if (!commentsDisabled && isPartiallyEmittedExpression(node) && willEmitLeadingNewLine(node)) {
      const parseNode = getParseTreeNode(node);
      if (parseNode && isParenthesizedExpression(parseNode)) {
        const parens = factory.createParenthesizedExpression(node.expression);
        setOriginalNode(parens, node);
        setTextRange(parens, parseNode);
        return parens;
      }
      return factory.createParenthesizedExpression(node);
    }
    return node;
  }
  function parenthesizeExpressionForNoAsiAndDisallowedComma(node) {
    return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node));
  }
  function emitReturnStatement(node) {
    emitTokenWithComment(
      107 /* ReturnKeyword */,
      node.pos,
      writeKeyword,
      /*contextNode*/
      node
    );
    emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi);
    writeTrailingSemicolon();
  }
  function emitWithStatement(node) {
    const openParenPos = emitTokenWithComment(118 /* WithKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
    emitExpression(node.expression);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node);
    emitEmbeddedStatement(node, node.statement);
  }
  function emitSwitchStatement(node) {
    const openParenPos = emitTokenWithComment(109 /* SwitchKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
    emitExpression(node.expression);
    emitTokenWithComment(22 /* CloseParenToken */, node.expression.end, writePunctuation, node);
    writeSpace();
    emit(node.caseBlock);
  }
  function emitLabeledStatement(node) {
    emit(node.label);
    emitTokenWithComment(59 /* ColonToken */, node.label.end, writePunctuation, node);
    writeSpace();
    emit(node.statement);
  }
  function emitThrowStatement(node) {
    emitTokenWithComment(111 /* ThrowKeyword */, node.pos, writeKeyword, node);
    emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi);
    writeTrailingSemicolon();
  }
  function emitTryStatement(node) {
    emitTokenWithComment(113 /* TryKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emit(node.tryBlock);
    if (node.catchClause) {
      writeLineOrSpace(node, node.tryBlock, node.catchClause);
      emit(node.catchClause);
    }
    if (node.finallyBlock) {
      writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock);
      emitTokenWithComment(98 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
      writeSpace();
      emit(node.finallyBlock);
    }
  }
  function emitDebuggerStatement(node) {
    writeToken(89 /* DebuggerKeyword */, node.pos, writeKeyword);
    writeTrailingSemicolon();
  }
  function emitVariableDeclaration(node) {
    var _a, _b, _c;
    emit(node.name);
    emit(node.exclamationToken);
    emitTypeAnnotation(node.type);
    emitInitializer(node.initializer, ((_a = node.type) == null ? void 0 : _a.end) ?? ((_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) ?? node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitVariableDeclarationList(node) {
    writeKeyword(isLet(node) ? "let" : isVarConst(node) ? "const" : "var");
    writeSpace();
    emitList(node, node.declarations, 528 /* VariableDeclarationList */);
  }
  function emitFunctionDeclaration(node) {
    emitFunctionDeclarationOrExpression(node);
  }
  function emitFunctionDeclarationOrExpression(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    writeKeyword("function");
    emit(node.asteriskToken);
    writeSpace();
    emitIdentifierName(node.name);
    emitSignatureAndBody(node, emitSignatureHead);
  }
  function emitSignatureAndBody(node, emitSignatureHead2) {
    const body = node.body;
    if (body) {
      if (isBlock(body)) {
        const indentedFlag = getEmitFlags(node) & 131072 /* Indented */;
        if (indentedFlag) {
          increaseIndent();
        }
        pushNameGenerationScope(node);
        forEach(node.parameters, generateNames);
        generateNames(node.body);
        emitSignatureHead2(node);
        emitBlockFunctionBody(body);
        popNameGenerationScope(node);
        if (indentedFlag) {
          decreaseIndent();
        }
      } else {
        emitSignatureHead2(node);
        writeSpace();
        emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction);
      }
    } else {
      emitSignatureHead2(node);
      writeTrailingSemicolon();
    }
  }
  function emitSignatureHead(node) {
    emitTypeParameters(node, node.typeParameters);
    emitParameters(node, node.parameters);
    emitTypeAnnotation(node.type);
  }
  function shouldEmitBlockFunctionBodyOnSingleLine(body) {
    if (getEmitFlags(body) & 1 /* SingleLine */) {
      return true;
    }
    if (body.multiLine) {
      return false;
    }
    if (!nodeIsSynthesized(body) && currentSourceFile && !rangeIsOnSingleLine(body, currentSourceFile)) {
      return false;
    }
    if (getLeadingLineTerminatorCount(body, firstOrUndefined(body.statements), 2 /* PreserveLines */) || getClosingLineTerminatorCount(body, lastOrUndefined(body.statements), 2 /* PreserveLines */, body.statements)) {
      return false;
    }
    let previousStatement;
    for (const statement of body.statements) {
      if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
        return false;
      }
      previousStatement = statement;
    }
    return true;
  }
  function emitBlockFunctionBody(body) {
    onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(body);
    writeSpace();
    writePunctuation("{");
    increaseIndent();
    const emitBlockFunctionBody2 = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker;
    emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody2);
    decreaseIndent();
    writeToken(20 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
    onAfterEmitNode == null ? void 0 : onAfterEmitNode(body);
  }
  function emitBlockFunctionBodyOnSingleLine(body) {
    emitBlockFunctionBodyWorker(
      body,
      /*emitBlockFunctionBodyOnSingleLine*/
      true
    );
  }
  function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine2) {
    const statementOffset = emitPrologueDirectives(body.statements);
    const pos = writer.getTextPos();
    emitHelpers(body);
    if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine2) {
      decreaseIndent();
      emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
      increaseIndent();
    } else {
      emitList(
        body,
        body.statements,
        1 /* MultiLineFunctionBodyStatements */,
        /*parenthesizerRule*/
        void 0,
        statementOffset
      );
    }
  }
  function emitClassDeclaration(node) {
    emitClassDeclarationOrExpression(node);
  }
  function emitClassDeclarationOrExpression(node) {
    pushPrivateNameGenerationScope(
      0 /* Auto */,
      /*newReservedMemberNames*/
      void 0
    );
    forEach(node.members, generateMemberNames);
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      true
    );
    emitTokenWithComment(86 /* ClassKeyword */, moveRangePastModifiers(node).pos, writeKeyword, node);
    if (node.name) {
      writeSpace();
      emitIdentifierName(node.name);
    }
    const indentedFlag = getEmitFlags(node) & 131072 /* Indented */;
    if (indentedFlag) {
      increaseIndent();
    }
    emitTypeParameters(node, node.typeParameters);
    emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
    writeSpace();
    writePunctuation("{");
    emitList(node, node.members, 129 /* ClassMembers */);
    writePunctuation("}");
    if (indentedFlag) {
      decreaseIndent();
    }
    popPrivateNameGenerationScope();
  }
  function emitInterfaceDeclaration(node) {
    pushPrivateNameGenerationScope(
      0 /* Auto */,
      /*newReservedMemberNames*/
      void 0
    );
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    writeKeyword("interface");
    writeSpace();
    emit(node.name);
    emitTypeParameters(node, node.typeParameters);
    emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
    writeSpace();
    writePunctuation("{");
    emitList(node, node.members, 129 /* InterfaceMembers */);
    writePunctuation("}");
    popPrivateNameGenerationScope();
  }
  function emitTypeAliasDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    writeKeyword("type");
    writeSpace();
    emit(node.name);
    emitTypeParameters(node, node.typeParameters);
    writeSpace();
    writePunctuation("=");
    writeSpace();
    emit(node.type);
    writeTrailingSemicolon();
  }
  function emitEnumDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    writeKeyword("enum");
    writeSpace();
    emit(node.name);
    writeSpace();
    writePunctuation("{");
    emitList(node, node.members, 145 /* EnumMembers */);
    writePunctuation("}");
  }
  function emitModuleDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    if (~node.flags & 1024 /* GlobalAugmentation */) {
      writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
      writeSpace();
    }
    emit(node.name);
    let body = node.body;
    if (!body)
      return writeTrailingSemicolon();
    while (body && isModuleDeclaration(body)) {
      writePunctuation(".");
      emit(body.name);
      body = body.body;
    }
    writeSpace();
    emit(body);
  }
  function emitModuleBlock(node) {
    pushNameGenerationScope(node);
    forEach(node.statements, generateNames);
    emitBlockStatements(
      node,
      /*forceSingleLine*/
      isEmptyBlock(node)
    );
    popNameGenerationScope(node);
  }
  function emitCaseBlock(node) {
    emitTokenWithComment(19 /* OpenBraceToken */, node.pos, writePunctuation, node);
    emitList(node, node.clauses, 129 /* CaseBlockClauses */);
    emitTokenWithComment(
      20 /* CloseBraceToken */,
      node.clauses.end,
      writePunctuation,
      node,
      /*indentLeading*/
      true
    );
  }
  function emitImportEqualsDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    emitTokenWithComment(102 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
    writeSpace();
    if (node.isTypeOnly) {
      emitTokenWithComment(156 /* TypeKeyword */, node.pos, writeKeyword, node);
      writeSpace();
    }
    emit(node.name);
    writeSpace();
    emitTokenWithComment(64 /* EqualsToken */, node.name.end, writePunctuation, node);
    writeSpace();
    emitModuleReference(node.moduleReference);
    writeTrailingSemicolon();
  }
  function emitModuleReference(node) {
    if (node.kind === 80 /* Identifier */) {
      emitExpression(node);
    } else {
      emit(node);
    }
  }
  function emitImportDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    emitTokenWithComment(102 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
    writeSpace();
    if (node.importClause) {
      emit(node.importClause);
      writeSpace();
      emitTokenWithComment(160 /* FromKeyword */, node.importClause.end, writeKeyword, node);
      writeSpace();
    }
    emitExpression(node.moduleSpecifier);
    if (node.assertClause) {
      emitWithLeadingSpace(node.assertClause);
    }
    writeTrailingSemicolon();
  }
  function emitImportClause(node) {
    if (node.isTypeOnly) {
      emitTokenWithComment(156 /* TypeKeyword */, node.pos, writeKeyword, node);
      writeSpace();
    }
    emit(node.name);
    if (node.name && node.namedBindings) {
      emitTokenWithComment(28 /* CommaToken */, node.name.end, writePunctuation, node);
      writeSpace();
    }
    emit(node.namedBindings);
  }
  function emitNamespaceImport(node) {
    const asPos = emitTokenWithComment(42 /* AsteriskToken */, node.pos, writePunctuation, node);
    writeSpace();
    emitTokenWithComment(130 /* AsKeyword */, asPos, writeKeyword, node);
    writeSpace();
    emit(node.name);
  }
  function emitNamedImports(node) {
    emitNamedImportsOrExports(node);
  }
  function emitImportSpecifier(node) {
    emitImportOrExportSpecifier(node);
  }
  function emitExportAssignment(node) {
    const nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    if (node.isExportEquals) {
      emitTokenWithComment(64 /* EqualsToken */, nextPos, writeOperator, node);
    } else {
      emitTokenWithComment(90 /* DefaultKeyword */, nextPos, writeKeyword, node);
    }
    writeSpace();
    emitExpression(node.expression, node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault);
    writeTrailingSemicolon();
  }
  function emitExportDeclaration(node) {
    emitDecoratorsAndModifiers(
      node,
      node.modifiers,
      /*allowDecorators*/
      false
    );
    let nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    if (node.isTypeOnly) {
      nextPos = emitTokenWithComment(156 /* TypeKeyword */, nextPos, writeKeyword, node);
      writeSpace();
    }
    if (node.exportClause) {
      emit(node.exportClause);
    } else {
      nextPos = emitTokenWithComment(42 /* AsteriskToken */, nextPos, writePunctuation, node);
    }
    if (node.moduleSpecifier) {
      writeSpace();
      const fromPos = node.exportClause ? node.exportClause.end : nextPos;
      emitTokenWithComment(160 /* FromKeyword */, fromPos, writeKeyword, node);
      writeSpace();
      emitExpression(node.moduleSpecifier);
    }
    if (node.assertClause) {
      emitWithLeadingSpace(node.assertClause);
    }
    writeTrailingSemicolon();
  }
  function emitAssertClause(node) {
    emitTokenWithComment(132 /* AssertKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    const elements = node.elements;
    emitList(node, elements, 526226 /* ImportClauseEntries */);
  }
  function emitAssertEntry(node) {
    emit(node.name);
    writePunctuation(":");
    writeSpace();
    const value = node.value;
    if ((getEmitFlags(value) & 1024 /* NoLeadingComments */) === 0) {
      const commentRange = getCommentRange(value);
      emitTrailingCommentsOfPosition(commentRange.pos);
    }
    emit(value);
  }
  function emitNamespaceExportDeclaration(node) {
    let nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    nextPos = emitTokenWithComment(130 /* AsKeyword */, nextPos, writeKeyword, node);
    writeSpace();
    nextPos = emitTokenWithComment(145 /* NamespaceKeyword */, nextPos, writeKeyword, node);
    writeSpace();
    emit(node.name);
    writeTrailingSemicolon();
  }
  function emitNamespaceExport(node) {
    const asPos = emitTokenWithComment(42 /* AsteriskToken */, node.pos, writePunctuation, node);
    writeSpace();
    emitTokenWithComment(130 /* AsKeyword */, asPos, writeKeyword, node);
    writeSpace();
    emit(node.name);
  }
  function emitNamedExports(node) {
    emitNamedImportsOrExports(node);
  }
  function emitExportSpecifier(node) {
    emitImportOrExportSpecifier(node);
  }
  function emitNamedImportsOrExports(node) {
    writePunctuation("{");
    emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
    writePunctuation("}");
  }
  function emitImportOrExportSpecifier(node) {
    if (node.isTypeOnly) {
      writeKeyword("type");
      writeSpace();
    }
    if (node.propertyName) {
      emit(node.propertyName);
      writeSpace();
      emitTokenWithComment(130 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
      writeSpace();
    }
    emit(node.name);
  }
  function emitExternalModuleReference(node) {
    writeKeyword("require");
    writePunctuation("(");
    emitExpression(node.expression);
    writePunctuation(")");
  }
  function emitJsxElement(node) {
    emit(node.openingElement);
    emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
    emit(node.closingElement);
  }
  function emitJsxSelfClosingElement(node) {
    writePunctuation("<");
    emitJsxTagName(node.tagName);
    emitTypeArguments(node, node.typeArguments);
    writeSpace();
    emit(node.attributes);
    writePunctuation("/>");
  }
  function emitJsxFragment(node) {
    emit(node.openingFragment);
    emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
    emit(node.closingFragment);
  }
  function emitJsxOpeningElementOrFragment(node) {
    writePunctuation("<");
    if (isJsxOpeningElement(node)) {
      const indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
      emitJsxTagName(node.tagName);
      emitTypeArguments(node, node.typeArguments);
      if (node.attributes.properties && node.attributes.properties.length > 0) {
        writeSpace();
      }
      emit(node.attributes);
      writeLineSeparatorsAfter(node.attributes, node);
      decreaseIndentIf(indented);
    }
    writePunctuation(">");
  }
  function emitJsxText(node) {
    writer.writeLiteral(node.text);
  }
  function emitJsxClosingElementOrFragment(node) {
    writePunctuation("</");
    if (isJsxClosingElement(node)) {
      emitJsxTagName(node.tagName);
    }
    writePunctuation(">");
  }
  function emitJsxAttributes(node) {
    emitList(node, node.properties, 262656 /* JsxElementAttributes */);
  }
  function emitJsxAttribute(node) {
    emit(node.name);
    emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
  }
  function emitJsxSpreadAttribute(node) {
    writePunctuation("{...");
    emitExpression(node.expression);
    writePunctuation("}");
  }
  function hasTrailingCommentsAtPosition(pos) {
    let result = false;
    forEachTrailingCommentRange((currentSourceFile == null ? void 0 : currentSourceFile.text) || "", pos + 1, () => result = true);
    return result;
  }
  function hasLeadingCommentsAtPosition(pos) {
    let result = false;
    forEachLeadingCommentRange((currentSourceFile == null ? void 0 : currentSourceFile.text) || "", pos + 1, () => result = true);
    return result;
  }
  function hasCommentsAtPosition(pos) {
    return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos);
  }
  function emitJsxExpression(node) {
    var _a;
    if (node.expression || !commentsDisabled && !nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos)) {
      const isMultiline = currentSourceFile && !nodeIsSynthesized(node) && getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== getLineAndCharacterOfPosition(currentSourceFile, node.end).line;
      if (isMultiline) {
        writer.increaseIndent();
      }
      const end = emitTokenWithComment(19 /* OpenBraceToken */, node.pos, writePunctuation, node);
      emit(node.dotDotDotToken);
      emitExpression(node.expression);
      emitTokenWithComment(20 /* CloseBraceToken */, ((_a = node.expression) == null ? void 0 : _a.end) || end, writePunctuation, node);
      if (isMultiline) {
        writer.decreaseIndent();
      }
    }
  }
  function emitJsxNamespacedName(node) {
    emitIdentifierName(node.namespace);
    writePunctuation(":");
    emitIdentifierName(node.name);
  }
  function emitJsxTagName(node) {
    if (node.kind === 80 /* Identifier */) {
      emitExpression(node);
    } else {
      emit(node);
    }
  }
  function emitCaseClause(node) {
    emitTokenWithComment(84 /* CaseKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
    emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
  }
  function emitDefaultClause(node) {
    const pos = emitTokenWithComment(90 /* DefaultKeyword */, node.pos, writeKeyword, node);
    emitCaseOrDefaultClauseRest(node, node.statements, pos);
  }
  function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
    const emitAsSingleStatement = statements.length === 1 && // treat synthesized nodes as located on the same line for emit purposes
    (!currentSourceFile || nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
    let format = 163969 /* CaseOrDefaultClauseStatements */;
    if (emitAsSingleStatement) {
      writeToken(59 /* ColonToken */, colonPos, writePunctuation, parentNode);
      writeSpace();
      format &= ~(1 /* MultiLine */ | 128 /* Indented */);
    } else {
      emitTokenWithComment(59 /* ColonToken */, colonPos, writePunctuation, parentNode);
    }
    emitList(parentNode, statements, format);
  }
  function emitHeritageClause(node) {
    writeSpace();
    writeTokenText(node.token, writeKeyword);
    writeSpace();
    emitList(node, node.types, 528 /* HeritageClauseTypes */);
  }
  function emitCatchClause(node) {
    const openParenPos = emitTokenWithComment(85 /* CatchKeyword */, node.pos, writeKeyword, node);
    writeSpace();
    if (node.variableDeclaration) {
      emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, node);
      emit(node.variableDeclaration);
      emitTokenWithComment(22 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
      writeSpace();
    }
    emit(node.block);
  }
  function emitPropertyAssignment(node) {
    emit(node.name);
    writePunctuation(":");
    writeSpace();
    const initializer = node.initializer;
    if ((getEmitFlags(initializer) & 1024 /* NoLeadingComments */) === 0) {
      const commentRange = getCommentRange(initializer);
      emitTrailingCommentsOfPosition(commentRange.pos);
    }
    emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitShorthandPropertyAssignment(node) {
    emit(node.name);
    if (node.objectAssignmentInitializer) {
      writeSpace();
      writePunctuation("=");
      writeSpace();
      emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma);
    }
  }
  function emitSpreadAssignment(node) {
    if (node.expression) {
      emitTokenWithComment(26 /* DotDotDotToken */, node.pos, writePunctuation, node);
      emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
    }
  }
  function emitEnumMember(node) {
    emit(node.name);
    emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma);
  }
  function emitJSDoc(node) {
    write("/**");
    if (node.comment) {
      const text = getTextOfJSDocComment(node.comment);
      if (text) {
        const lines = text.split(/\r\n?|\n/g);
        for (const line of lines) {
          writeLine();
          writeSpace();
          writePunctuation("*");
          writeSpace();
          write(line);
        }
      }
    }
    if (node.tags) {
      if (node.tags.length === 1 && node.tags[0].kind === 350 /* JSDocTypeTag */ && !node.comment) {
        writeSpace();
        emit(node.tags[0]);
      } else {
        emitList(node, node.tags, 33 /* JSDocComment */);
      }
    }
    writeSpace();
    write("*/");
  }
  function emitJSDocSimpleTypedTag(tag) {
    emitJSDocTagName(tag.tagName);
    emitJSDocTypeExpression(tag.typeExpression);
    emitJSDocComment(tag.comment);
  }
  function emitJSDocSeeTag(tag) {
    emitJSDocTagName(tag.tagName);
    emit(tag.name);
    emitJSDocComment(tag.comment);
  }
  function emitJSDocNameReference(node) {
    writeSpace();
    writePunctuation("{");
    emit(node.name);
    writePunctuation("}");
  }
  function emitJSDocHeritageTag(tag) {
    emitJSDocTagName(tag.tagName);
    writeSpace();
    writePunctuation("{");
    emit(tag.class);
    writePunctuation("}");
    emitJSDocComment(tag.comment);
  }
  function emitJSDocTemplateTag(tag) {
    emitJSDocTagName(tag.tagName);
    emitJSDocTypeExpression(tag.constraint);
    writeSpace();
    emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
    emitJSDocComment(tag.comment);
  }
  function emitJSDocTypedefTag(tag) {
    emitJSDocTagName(tag.tagName);
    if (tag.typeExpression) {
      if (tag.typeExpression.kind === 315 /* JSDocTypeExpression */) {
        emitJSDocTypeExpression(tag.typeExpression);
      } else {
        writeSpace();
        writePunctuation("{");
        write("Object");
        if (tag.typeExpression.isArrayType) {
          writePunctuation("[");
          writePunctuation("]");
        }
        writePunctuation("}");
      }
    }
    if (tag.fullName) {
      writeSpace();
      emit(tag.fullName);
    }
    emitJSDocComment(tag.comment);
    if (tag.typeExpression && tag.typeExpression.kind === 328 /* JSDocTypeLiteral */) {
      emitJSDocTypeLiteral(tag.typeExpression);
    }
  }
  function emitJSDocCallbackTag(tag) {
    emitJSDocTagName(tag.tagName);
    if (tag.name) {
      writeSpace();
      emit(tag.name);
    }
    emitJSDocComment(tag.comment);
    emitJSDocSignature(tag.typeExpression);
  }
  function emitJSDocOverloadTag(tag) {
    emitJSDocComment(tag.comment);
    emitJSDocSignature(tag.typeExpression);
  }
  function emitJSDocSimpleTag(tag) {
    emitJSDocTagName(tag.tagName);
    emitJSDocComment(tag.comment);
  }
  function emitJSDocTypeLiteral(lit) {
    emitList(lit, factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
  }
  function emitJSDocSignature(sig) {
    if (sig.typeParameters) {
      emitList(sig, factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
    }
    if (sig.parameters) {
      emitList(sig, factory.createNodeArray(sig.parameters), 33 /* JSDocComment */);
    }
    if (sig.type) {
      writeLine();
      writeSpace();
      writePunctuation("*");
      writeSpace();
      emit(sig.type);
    }
  }
  function emitJSDocPropertyLikeTag(param) {
    emitJSDocTagName(param.tagName);
    emitJSDocTypeExpression(param.typeExpression);
    writeSpace();
    if (param.isBracketed) {
      writePunctuation("[");
    }
    emit(param.name);
    if (param.isBracketed) {
      writePunctuation("]");
    }
    emitJSDocComment(param.comment);
  }
  function emitJSDocTagName(tagName) {
    writePunctuation("@");
    emit(tagName);
  }
  function emitJSDocComment(comment) {
    const text = getTextOfJSDocComment(comment);
    if (text) {
      writeSpace();
      write(text);
    }
  }
  function emitJSDocTypeExpression(typeExpression) {
    if (typeExpression) {
      writeSpace();
      writePunctuation("{");
      emit(typeExpression.type);
      writePunctuation("}");
    }
  }
  function emitSourceFile(node) {
    writeLine();
    const statements = node.statements;
    const shouldEmitDetachedComment = statements.length === 0 || !isPrologueDirective(statements[0]) || nodeIsSynthesized(statements[0]);
    if (shouldEmitDetachedComment) {
      emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
      return;
    }
    emitSourceFileWorker(node);
  }
  function emitSyntheticTripleSlashReferencesIfNeeded(node) {
    emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
    for (const prepend of node.prepends) {
      if (isUnparsedSource(prepend) && prepend.syntheticReferences) {
        for (const ref of prepend.syntheticReferences) {
          emit(ref);
          writeLine();
        }
      }
    }
  }
  function emitTripleSlashDirectivesIfNeeded(node) {
    if (node.isDeclarationFile)
      emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
  }
  function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs2) {
    if (hasNoDefaultLib) {
      const pos = writer.getTextPos();
      writeComment(`/// <reference no-default-lib="true"/>`);
      if (bundleFileInfo)
        bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
      writeLine();
    }
    if (currentSourceFile && currentSourceFile.moduleName) {
      writeComment(`/// <amd-module name="${currentSourceFile.moduleName}" />`);
      writeLine();
    }
    if (currentSourceFile && currentSourceFile.amdDependencies) {
      for (const dep of currentSourceFile.amdDependencies) {
        if (dep.name) {
          writeComment(`/// <amd-dependency name="${dep.name}" path="${dep.path}" />`);
        } else {
          writeComment(`/// <amd-dependency path="${dep.path}" />`);
        }
        writeLine();
      }
    }
    for (const directive of files) {
      const pos = writer.getTextPos();
      writeComment(`/// <reference path="${directive.fileName}" />`);
      if (bundleFileInfo)
        bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
      writeLine();
    }
    for (const directive of types) {
      const pos = writer.getTextPos();
      const resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile == null ? void 0 : currentSourceFile.impliedNodeFormat) ? `resolution-mode="${directive.resolutionMode === 99 /* ESNext */ ? "import" : "require"}"` : "";
      writeComment(`/// <reference types="${directive.fileName}" ${resolutionMode}/>`);
      if (bundleFileInfo)
        bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: !directive.resolutionMode ? "type" /* Type */ : directive.resolutionMode === 99 /* ESNext */ ? "type-import" /* TypeResolutionModeImport */ : "type-require" /* TypeResolutionModeRequire */, data: directive.fileName });
      writeLine();
    }
    for (const directive of libs2) {
      const pos = writer.getTextPos();
      writeComment(`/// <reference lib="${directive.fileName}" />`);
      if (bundleFileInfo)
        bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
      writeLine();
    }
  }
  function emitSourceFileWorker(node) {
    const statements = node.statements;
    pushNameGenerationScope(node);
    forEach(node.statements, generateNames);
    emitHelpers(node);
    const index = findIndex(statements, (statement) => !isPrologueDirective(statement));
    emitTripleSlashDirectivesIfNeeded(node);
    emitList(
      node,
      statements,
      1 /* MultiLine */,
      /*parenthesizerRule*/
      void 0,
      index === -1 ? statements.length : index
    );
    popNameGenerationScope(node);
  }
  function emitPartiallyEmittedExpression(node) {
    const emitFlags = getEmitFlags(node);
    if (!(emitFlags & 1024 /* NoLeadingComments */) && node.pos !== node.expression.pos) {
      emitTrailingCommentsOfPosition(node.expression.pos);
    }
    emitExpression(node.expression);
    if (!(emitFlags & 2048 /* NoTrailingComments */) && node.end !== node.expression.end) {
      emitLeadingCommentsOfPosition(node.expression.end);
    }
  }
  function emitCommaList(node) {
    emitExpressionList(
      node,
      node.elements,
      528 /* CommaListElements */,
      /*parenthesizerRule*/
      void 0
    );
  }
  function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
    let needsToSetSourceFile = !!sourceFile;
    for (let i = 0; i < statements.length; i++) {
      const statement = statements[i];
      if (isPrologueDirective(statement)) {
        const shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
        if (shouldEmitPrologueDirective) {
          if (needsToSetSourceFile) {
            needsToSetSourceFile = false;
            setSourceFile(sourceFile);
          }
          writeLine();
          const pos = writer.getTextPos();
          emit(statement);
          if (recordBundleFileSection && bundleFileInfo)
            bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
          if (seenPrologueDirectives) {
            seenPrologueDirectives.add(statement.expression.text);
          }
        }
      } else {
        return i;
      }
    }
    return statements.length;
  }
  function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
    for (const prologue of prologues) {
      if (!seenPrologueDirectives.has(prologue.data)) {
        writeLine();
        const pos = writer.getTextPos();
        emit(prologue);
        if (bundleFileInfo)
          bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
        if (seenPrologueDirectives) {
          seenPrologueDirectives.add(prologue.data);
        }
      }
    }
  }
  function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
    if (isSourceFile(sourceFileOrBundle)) {
      emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
    } else {
      const seenPrologueDirectives = /* @__PURE__ */ new Set();
      for (const prepend of sourceFileOrBundle.prepends) {
        emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
      }
      for (const sourceFile of sourceFileOrBundle.sourceFiles) {
        emitPrologueDirectives(
          sourceFile.statements,
          sourceFile,
          seenPrologueDirectives,
          /*recordBundleFileSection*/
          true
        );
      }
      setSourceFile(void 0);
    }
  }
  function getPrologueDirectivesFromBundledSourceFiles(bundle) {
    const seenPrologueDirectives = /* @__PURE__ */ new Set();
    let prologues;
    for (let index = 0; index < bundle.sourceFiles.length; index++) {
      const sourceFile = bundle.sourceFiles[index];
      let directives;
      let end = 0;
      for (const statement of sourceFile.statements) {
        if (!isPrologueDirective(statement))
          break;
        if (seenPrologueDirectives.has(statement.expression.text))
          continue;
        seenPrologueDirectives.add(statement.expression.text);
        (directives || (directives = [])).push({
          pos: statement.pos,
          end: statement.end,
          expression: {
            pos: statement.expression.pos,
            end: statement.expression.end,
            text: statement.expression.text
          }
        });
        end = end < statement.end ? statement.end : end;
      }
      if (directives)
        (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives });
    }
    return prologues;
  }
  function emitShebangIfNeeded(sourceFileOrBundle) {
    if (isSourceFile(sourceFileOrBundle) || isUnparsedSource(sourceFileOrBundle)) {
      const shebang = getShebang(sourceFileOrBundle.text);
      if (shebang) {
        writeComment(shebang);
        writeLine();
        return true;
      }
    } else {
      for (const prepend of sourceFileOrBundle.prepends) {
        Debug.assertNode(prepend, isUnparsedSource);
        if (emitShebangIfNeeded(prepend)) {
          return true;
        }
      }
      for (const sourceFile of sourceFileOrBundle.sourceFiles) {
        if (emitShebangIfNeeded(sourceFile)) {
          return true;
        }
      }
    }
  }
  function emitNodeWithWriter(node, writer2) {
    if (!node)
      return;
    const savedWrite = write;
    write = writer2;
    emit(node);
    write = savedWrite;
  }
  function emitDecoratorsAndModifiers(node, modifiers, allowDecorators) {
    if (modifiers == null ? void 0 : modifiers.length) {
      if (every(modifiers, isModifier)) {
        return emitModifierList(node, modifiers);
      }
      if (every(modifiers, isDecorator)) {
        if (allowDecorators) {
          return emitDecoratorList(node, modifiers);
        }
        return node.pos;
      }
      onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(modifiers);
      let lastMode;
      let mode;
      let start2 = 0;
      let pos = 0;
      let lastModifier;
      while (start2 < modifiers.length) {
        while (pos < modifiers.length) {
          lastModifier = modifiers[pos];
          mode = isDecorator(lastModifier) ? "decorators" : "modifiers";
          if (lastMode === void 0) {
            lastMode = mode;
          } else if (mode !== lastMode) {
            break;
          }
          pos++;
        }
        const textRange = { pos: -1, end: -1 };
        if (start2 === 0)
          textRange.pos = modifiers.pos;
        if (pos === modifiers.length - 1)
          textRange.end = modifiers.end;
        if (lastMode === "modifiers" || allowDecorators) {
          emitNodeListItems(
            emit,
            node,
            modifiers,
            lastMode === "modifiers" ? 2359808 /* Modifiers */ : 2146305 /* Decorators */,
            /*parenthesizerRule*/
            void 0,
            start2,
            pos - start2,
            /*hasTrailingComma*/
            false,
            textRange
          );
        }
        start2 = pos;
        lastMode = mode;
        pos++;
      }
      onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(modifiers);
      if (lastModifier && !positionIsSynthesized(lastModifier.end)) {
        return lastModifier.end;
      }
    }
    return node.pos;
  }
  function emitModifierList(node, modifiers) {
    emitList(node, modifiers, 2359808 /* Modifiers */);
    const lastModifier = lastOrUndefined(modifiers);
    return lastModifier && !positionIsSynthesized(lastModifier.end) ? lastModifier.end : node.pos;
  }
  function emitTypeAnnotation(node) {
    if (node) {
      writePunctuation(":");
      writeSpace();
      emit(node);
    }
  }
  function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) {
    if (node) {
      writeSpace();
      emitTokenWithComment(64 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
      writeSpace();
      emitExpression(node, parenthesizerRule);
    }
  }
  function emitNodeWithPrefix(prefix, prefixWriter, node, emit2) {
    if (node) {
      prefixWriter(prefix);
      emit2(node);
    }
  }
  function emitWithLeadingSpace(node) {
    if (node) {
      writeSpace();
      emit(node);
    }
  }
  function emitExpressionWithLeadingSpace(node, parenthesizerRule) {
    if (node) {
      writeSpace();
      emitExpression(node, parenthesizerRule);
    }
  }
  function emitWithTrailingSpace(node) {
    if (node) {
      emit(node);
      writeSpace();
    }
  }
  function emitEmbeddedStatement(parent2, node) {
    if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent2, node, 0 /* None */)) {
      writeSpace();
      emit(node);
    } else {
      writeLine();
      increaseIndent();
      if (isEmptyStatement(node)) {
        pipelineEmit(5 /* EmbeddedStatement */, node);
      } else {
        emit(node);
      }
      decreaseIndent();
    }
  }
  function emitDecoratorList(parentNode, decorators) {
    emitList(parentNode, decorators, 2146305 /* Decorators */);
    const lastDecorator = lastOrUndefined(decorators);
    return lastDecorator && !positionIsSynthesized(lastDecorator.end) ? lastDecorator.end : parentNode.pos;
  }
  function emitTypeArguments(parentNode, typeArguments) {
    emitList(parentNode, typeArguments, 53776 /* TypeArguments */, typeArgumentParenthesizerRuleSelector);
  }
  function emitTypeParameters(parentNode, typeParameters) {
    if (isFunctionLike(parentNode) && parentNode.typeArguments) {
      return emitTypeArguments(parentNode, parentNode.typeArguments);
    }
    emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
  }
  function emitParameters(parentNode, parameters) {
    emitList(parentNode, parameters, 2576 /* Parameters */);
  }
  function canEmitSimpleArrowHead(parentNode, parameters) {
    const parameter = singleOrUndefined(parameters);
    return parameter && parameter.pos === parentNode.pos && isArrowFunction(parentNode) && !parentNode.type && !some(parentNode.modifiers) && !some(parentNode.typeParameters) && !some(parameter.modifiers) && !parameter.dotDotDotToken && !parameter.questionToken && !parameter.type && !parameter.initializer && isIdentifier(parameter.name);
  }
  function emitParametersForArrow(parentNode, parameters) {
    if (canEmitSimpleArrowHead(parentNode, parameters)) {
      emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
    } else {
      emitParameters(parentNode, parameters);
    }
  }
  function emitParametersForIndexSignature(parentNode, parameters) {
    emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
  }
  function writeDelimiter(format) {
    switch (format & 60 /* DelimitersMask */) {
      case 0 /* None */:
        break;
      case 16 /* CommaDelimited */:
        writePunctuation(",");
        break;
      case 4 /* BarDelimited */:
        writeSpace();
        writePunctuation("|");
        break;
      case 32 /* AsteriskDelimited */:
        writeSpace();
        writePunctuation("*");
        writeSpace();
        break;
      case 8 /* AmpersandDelimited */:
        writeSpace();
        writePunctuation("&");
        break;
    }
  }
  function emitList(parentNode, children, format, parenthesizerRule, start2, count) {
    emitNodeList(
      emit,
      parentNode,
      children,
      format | (parentNode && getEmitFlags(parentNode) & 2 /* MultiLine */ ? 65536 /* PreferNewLine */ : 0),
      parenthesizerRule,
      start2,
      count
    );
  }
  function emitExpressionList(parentNode, children, format, parenthesizerRule, start2, count) {
    emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start2, count);
  }
  function emitNodeList(emit2, parentNode, children, format, parenthesizerRule, start2 = 0, count = children ? children.length - start2 : 0) {
    const isUndefined = children === void 0;
    if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
      return;
    }
    const isEmpty = children === void 0 || start2 >= children.length || count === 0;
    if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
      onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children);
      onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(children);
      return;
    }
    if (format & 15360 /* BracketsMask */) {
      writePunctuation(getOpeningBracket(format));
      if (isEmpty && children) {
        emitTrailingCommentsOfPosition(
          children.pos,
          /*prefixSpace*/
          true
        );
      }
    }
    onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children);
    if (isEmpty) {
      if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)))) {
        writeLine();
      } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
        writeSpace();
      }
    } else {
      emitNodeListItems(emit2, parentNode, children, format, parenthesizerRule, start2, count, children.hasTrailingComma, children);
    }
    onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(children);
    if (format & 15360 /* BracketsMask */) {
      if (isEmpty && children) {
        emitLeadingCommentsOfPosition(children.end);
      }
      writePunctuation(getClosingBracket(format));
    }
  }
  function emitNodeListItems(emit2, parentNode, children, format, parenthesizerRule, start2, count, hasTrailingComma, childrenTextRange) {
    const mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
    let shouldEmitInterveningComments = mayEmitInterveningComments;
    const leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start2], format);
    if (leadingLineTerminatorCount) {
      writeLine(leadingLineTerminatorCount);
      shouldEmitInterveningComments = false;
    } else if (format & 256 /* SpaceBetweenBraces */) {
      writeSpace();
    }
    if (format & 128 /* Indented */) {
      increaseIndent();
    }
    const emitListItem = getEmitListItem(emit2, parenthesizerRule);
    let previousSibling;
    let previousSourceFileTextKind;
    let shouldDecreaseIndentAfterEmit = false;
    for (let i = 0; i < count; i++) {
      const child = children[start2 + i];
      if (format & 32 /* AsteriskDelimited */) {
        writeLine();
        writeDelimiter(format);
      } else if (previousSibling) {
        if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) {
          const previousSiblingEmitFlags = getEmitFlags(previousSibling);
          if (!(previousSiblingEmitFlags & 2048 /* NoTrailingComments */)) {
            emitLeadingCommentsOfPosition(previousSibling.end);
          }
        }
        writeDelimiter(format);
        recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
        const separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
        if (separatingLineTerminatorCount > 0) {
          if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
            increaseIndent();
            shouldDecreaseIndentAfterEmit = true;
          }
          writeLine(separatingLineTerminatorCount);
          shouldEmitInterveningComments = false;
        } else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
          writeSpace();
        }
      }
      previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
      if (shouldEmitInterveningComments) {
        const commentRange = getCommentRange(child);
        emitTrailingCommentsOfPosition(commentRange.pos);
      } else {
        shouldEmitInterveningComments = mayEmitInterveningComments;
      }
      nextListElementPos = child.pos;
      emitListItem(child, emit2, parenthesizerRule, i);
      if (shouldDecreaseIndentAfterEmit) {
        decreaseIndent();
        shouldDecreaseIndentAfterEmit = false;
      }
      previousSibling = child;
    }
    const emitFlags = previousSibling ? getEmitFlags(previousSibling) : 0;
    const skipTrailingComments = commentsDisabled || !!(emitFlags & 2048 /* NoTrailingComments */);
    const emitTrailingComma = hasTrailingComma && format & 64 /* AllowTrailingComma */ && format & 16 /* CommaDelimited */;
    if (emitTrailingComma) {
      if (previousSibling && !skipTrailingComments) {
        emitTokenWithComment(28 /* CommaToken */, previousSibling.end, writePunctuation, previousSibling);
      } else {
        writePunctuation(",");
      }
    }
    if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && format & 60 /* DelimitersMask */ && !skipTrailingComments) {
      emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange == null ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end);
    }
    if (format & 128 /* Indented */) {
      decreaseIndent();
    }
    recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
    const closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start2 + count - 1], format, childrenTextRange);
    if (closingLineTerminatorCount) {
      writeLine(closingLineTerminatorCount);
    } else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
      writeSpace();
    }
  }
  function writeLiteral(s) {
    writer.writeLiteral(s);
  }
  function writeStringLiteral(s) {
    writer.writeStringLiteral(s);
  }
  function writeBase(s) {
    writer.write(s);
  }
  function writeSymbol(s, sym) {
    writer.writeSymbol(s, sym);
  }
  function writePunctuation(s) {
    writer.writePunctuation(s);
  }
  function writeTrailingSemicolon() {
    writer.writeTrailingSemicolon(";");
  }
  function writeKeyword(s) {
    writer.writeKeyword(s);
  }
  function writeOperator(s) {
    writer.writeOperator(s);
  }
  function writeParameter(s) {
    writer.writeParameter(s);
  }
  function writeComment(s) {
    writer.writeComment(s);
  }
  function writeSpace() {
    writer.writeSpace(" ");
  }
  function writeProperty(s) {
    writer.writeProperty(s);
  }
  function nonEscapingWrite(s) {
    if (writer.nonEscapingWrite) {
      writer.nonEscapingWrite(s);
    } else {
      writer.write(s);
    }
  }
  function writeLine(count = 1) {
    for (let i = 0; i < count; i++) {
      writer.writeLine(i > 0);
    }
  }
  function increaseIndent() {
    writer.increaseIndent();
  }
  function decreaseIndent() {
    writer.decreaseIndent();
  }
  function writeToken(token, pos, writer2, contextNode) {
    return !sourceMapsDisabled ? emitTokenWithSourceMap(contextNode, token, writer2, pos, writeTokenText) : writeTokenText(token, writer2, pos);
  }
  function writeTokenNode(node, writer2) {
    if (onBeforeEmitToken) {
      onBeforeEmitToken(node);
    }
    writer2(tokenToString(node.kind));
    if (onAfterEmitToken) {
      onAfterEmitToken(node);
    }
  }
  function writeTokenText(token, writer2, pos) {
    const tokenString = tokenToString(token);
    writer2(tokenString);
    return pos < 0 ? pos : pos + tokenString.length;
  }
  function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) {
    if (getEmitFlags(parentNode) & 1 /* SingleLine */) {
      writeSpace();
    } else if (preserveSourceNewlines) {
      const lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode);
      if (lines) {
        writeLine(lines);
      } else {
        writeSpace();
      }
    } else {
      writeLine();
    }
  }
  function writeLines(text) {
    const lines = text.split(/\r\n?|\n/g);
    const indentation = guessIndentation(lines);
    for (const lineText of lines) {
      const line = indentation ? lineText.slice(indentation) : lineText;
      if (line.length) {
        writeLine();
        write(line);
      }
    }
  }
  function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
    if (lineCount) {
      increaseIndent();
      writeLine(lineCount);
    } else if (writeSpaceIfNotIndenting) {
      writeSpace();
    }
  }
  function decreaseIndentIf(value1, value2) {
    if (value1) {
      decreaseIndent();
    }
    if (value2) {
      decreaseIndent();
    }
  }
  function getLeadingLineTerminatorCount(parentNode, firstChild, format) {
    if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
      if (format & 65536 /* PreferNewLine */) {
        return 1;
      }
      if (firstChild === void 0) {
        return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
      }
      if (firstChild.pos === nextListElementPos) {
        return 0;
      }
      if (firstChild.kind === 12 /* JsxText */) {
        return 0;
      }
      if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode))) {
        if (preserveSourceNewlines) {
          return getEffectiveLines(
            (includeComments) => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(
              firstChild.pos,
              parentNode.pos,
              currentSourceFile,
              includeComments
            )
          );
        }
        return rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1;
      }
      if (synthesizedNodeStartsOnNewLine(firstChild, format)) {
        return 1;
      }
    }
    return format & 1 /* MultiLine */ ? 1 : 0;
  }
  function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
    if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
      if (previousNode === void 0 || nextNode === void 0) {
        return 0;
      }
      if (nextNode.kind === 12 /* JsxText */) {
        return 0;
      } else if (currentSourceFile && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) {
        if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) {
          return getEffectiveLines(
            (includeComments) => getLinesBetweenRangeEndAndRangeStart(
              previousNode,
              nextNode,
              currentSourceFile,
              includeComments
            )
          );
        } else if (!preserveSourceNewlines && originalNodesHaveSameParent(previousNode, nextNode)) {
          return rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
        }
        return format & 65536 /* PreferNewLine */ ? 1 : 0;
      } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
        return 1;
      }
    } else if (getStartsOnNewLine(nextNode)) {
      return 1;
    }
    return format & 1 /* MultiLine */ ? 1 : 0;
  }
  function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) {
    if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
      if (format & 65536 /* PreferNewLine */) {
        return 1;
      }
      if (lastChild === void 0) {
        return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
      }
      if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
        if (preserveSourceNewlines) {
          const end = childrenTextRange && !positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end;
          return getEffectiveLines(
            (includeComments) => getLinesBetweenPositionAndNextNonWhitespaceCharacter(
              end,
              parentNode.end,
              currentSourceFile,
              includeComments
            )
          );
        }
        return rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
      }
      if (synthesizedNodeStartsOnNewLine(lastChild, format)) {
        return 1;
      }
    }
    if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
      return 1;
    }
    return 0;
  }
  function getEffectiveLines(getLineDifference) {
    Debug.assert(!!preserveSourceNewlines);
    const lines = getLineDifference(
      /*includeComments*/
      true
    );
    if (lines === 0) {
      return getLineDifference(
        /*includeComments*/
        false
      );
    }
    return lines;
  }
  function writeLineSeparatorsAndIndentBefore(node, parent2) {
    const leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent2, node, 0 /* None */);
    if (leadingNewlines) {
      writeLinesAndIndent(
        leadingNewlines,
        /*writeSpaceIfNotIndenting*/
        false
      );
    }
    return !!leadingNewlines;
  }
  function writeLineSeparatorsAfter(node, parent2) {
    const trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(
      parent2,
      node,
      0 /* None */,
      /*childrenTextRange*/
      void 0
    );
    if (trailingNewlines) {
      writeLine(trailingNewlines);
    }
  }
  function synthesizedNodeStartsOnNewLine(node, format) {
    if (nodeIsSynthesized(node)) {
      const startsOnNewLine = getStartsOnNewLine(node);
      if (startsOnNewLine === void 0) {
        return (format & 65536 /* PreferNewLine */) !== 0;
      }
      return startsOnNewLine;
    }
    return (format & 65536 /* PreferNewLine */) !== 0;
  }
  function getLinesBetweenNodes(parent2, node1, node2) {
    if (getEmitFlags(parent2) & 262144 /* NoIndentation */) {
      return 0;
    }
    parent2 = skipSynthesizedParentheses(parent2);
    node1 = skipSynthesizedParentheses(node1);
    node2 = skipSynthesizedParentheses(node2);
    if (getStartsOnNewLine(node2)) {
      return 1;
    }
    if (currentSourceFile && !nodeIsSynthesized(parent2) && !nodeIsSynthesized(node1) && !nodeIsSynthesized(node2)) {
      if (preserveSourceNewlines) {
        return getEffectiveLines(
          (includeComments) => getLinesBetweenRangeEndAndRangeStart(
            node1,
            node2,
            currentSourceFile,
            includeComments
          )
        );
      }
      return rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
    }
    return 0;
  }
  function isEmptyBlock(block) {
    return block.statements.length === 0 && (!currentSourceFile || rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile));
  }
  function skipSynthesizedParentheses(node) {
    while (node.kind === 216 /* ParenthesizedExpression */ && nodeIsSynthesized(node)) {
      node = node.expression;
    }
    return node;
  }
  function getTextOfNode2(node, includeTrivia) {
    if (isGeneratedIdentifier(node) || isGeneratedPrivateIdentifier(node)) {
      return generateName(node);
    }
    if (isStringLiteral(node) && node.textSourceNode) {
      return getTextOfNode2(node.textSourceNode, includeTrivia);
    }
    const sourceFile = currentSourceFile;
    const canUseSourceFile = !!sourceFile && !!node.parent && !nodeIsSynthesized(node);
    if (isMemberName(node)) {
      if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) {
        return idText(node);
      }
    } else if (isJsxNamespacedName(node)) {
      if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) {
        return getTextOfJsxNamespacedName(node);
      }
    } else {
      Debug.assertNode(node, isLiteralExpression);
      if (!canUseSourceFile) {
        return node.text;
      }
    }
    return getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia);
  }
  function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
    if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) {
      const textSourceNode = node.textSourceNode;
      if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) {
        const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode);
        return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`;
      } else {
        return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
      }
    }
    const flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0) | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0) | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0) | (printerOptions.target && printerOptions.target === 99 /* ESNext */ ? 8 /* AllowNumericSeparator */ : 0);
    return getLiteralText(node, currentSourceFile, flags);
  }
  function pushNameGenerationScope(node) {
    if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) {
      return;
    }
    tempFlagsStack.push(tempFlags);
    tempFlags = 0 /* Auto */;
    formattedNameTempFlagsStack.push(formattedNameTempFlags);
    formattedNameTempFlags = void 0;
    reservedNamesStack.push(reservedNames);
  }
  function popNameGenerationScope(node) {
    if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) {
      return;
    }
    tempFlags = tempFlagsStack.pop();
    formattedNameTempFlags = formattedNameTempFlagsStack.pop();
    reservedNames = reservedNamesStack.pop();
  }
  function reserveNameInNestedScopes(name) {
    if (!reservedNames || reservedNames === lastOrUndefined(reservedNamesStack)) {
      reservedNames = /* @__PURE__ */ new Set();
    }
    reservedNames.add(name);
  }
  function pushPrivateNameGenerationScope(newPrivateNameTempFlags, newReservedMemberNames) {
    privateNameTempFlagsStack.push(privateNameTempFlags);
    privateNameTempFlags = newPrivateNameTempFlags;
    reservedPrivateNamesStack.push(reservedNames);
    reservedPrivateNames = newReservedMemberNames;
  }
  function popPrivateNameGenerationScope() {
    privateNameTempFlags = privateNameTempFlagsStack.pop();
    reservedPrivateNames = reservedPrivateNamesStack.pop();
  }
  function reservePrivateNameInNestedScopes(name) {
    if (!reservedPrivateNames || reservedPrivateNames === lastOrUndefined(reservedPrivateNamesStack)) {
      reservedPrivateNames = /* @__PURE__ */ new Set();
    }
    reservedPrivateNames.add(name);
  }
  function generateNames(node) {
    if (!node)
      return;
    switch (node.kind) {
      case 240 /* Block */:
        forEach(node.statements, generateNames);
        break;
      case 255 /* LabeledStatement */:
      case 253 /* WithStatement */:
      case 245 /* DoStatement */:
      case 246 /* WhileStatement */:
        generateNames(node.statement);
        break;
      case 244 /* IfStatement */:
        generateNames(node.thenStatement);
        generateNames(node.elseStatement);
        break;
      case 247 /* ForStatement */:
      case 249 /* ForOfStatement */:
      case 248 /* ForInStatement */:
        generateNames(node.initializer);
        generateNames(node.statement);
        break;
      case 254 /* SwitchStatement */:
        generateNames(node.caseBlock);
        break;
      case 268 /* CaseBlock */:
        forEach(node.clauses, generateNames);
        break;
      case 295 /* CaseClause */:
      case 296 /* DefaultClause */:
        forEach(node.statements, generateNames);
        break;
      case 257 /* TryStatement */:
        generateNames(node.tryBlock);
        generateNames(node.catchClause);
        generateNames(node.finallyBlock);
        break;
      case 298 /* CatchClause */:
        generateNames(node.variableDeclaration);
        generateNames(node.block);
        break;
      case 242 /* VariableStatement */:
        generateNames(node.declarationList);
        break;
      case 260 /* VariableDeclarationList */:
        forEach(node.declarations, generateNames);
        break;
      case 259 /* VariableDeclaration */:
      case 168 /* Parameter */:
      case 207 /* BindingElement */:
      case 262 /* ClassDeclaration */:
        generateNameIfNeeded(node.name);
        break;
      case 261 /* FunctionDeclaration */:
        generateNameIfNeeded(node.name);
        if (getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) {
          forEach(node.parameters, generateNames);
          generateNames(node.body);
        }
        break;
      case 205 /* ObjectBindingPattern */:
      case 206 /* ArrayBindingPattern */:
        forEach(node.elements, generateNames);
        break;
      case 271 /* ImportDeclaration */:
        generateNames(node.importClause);
        break;
      case 272 /* ImportClause */:
        generateNameIfNeeded(node.name);
        generateNames(node.namedBindings);
        break;
      case 273 /* NamespaceImport */:
        generateNameIfNeeded(node.name);
        break;
      case 279 /* NamespaceExport */:
        generateNameIfNeeded(node.name);
        break;
      case 274 /* NamedImports */:
        forEach(node.elements, generateNames);
        break;
      case 275 /* ImportSpecifier */:
        generateNameIfNeeded(node.propertyName || node.name);
        break;
    }
  }
  function generateMemberNames(node) {
    if (!node)
      return;
    switch (node.kind) {
      case 302 /* PropertyAssignment */:
      case 303 /* ShorthandPropertyAssignment */:
      case 171 /* PropertyDeclaration */:
      case 173 /* MethodDeclaration */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        generateNameIfNeeded(node.name);
        break;
    }
  }
  function generateNameIfNeeded(name) {
    if (name) {
      if (isGeneratedIdentifier(name) || isGeneratedPrivateIdentifier(name)) {
        generateName(name);
      } else if (isBindingPattern(name)) {
        generateNames(name);
      }
    }
  }
  function generateName(name) {
    const autoGenerate = name.emitNode.autoGenerate;
    if ((autoGenerate.flags & 7 /* KindMask */) === 4 /* Node */) {
      return generateNameCached(getNodeForGeneratedName(name), isPrivateIdentifier(name), autoGenerate.flags, autoGenerate.prefix, autoGenerate.suffix);
    } else {
      const autoGenerateId = autoGenerate.id;
      return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
    }
  }
  function generateNameCached(node, privateName, flags, prefix, suffix) {
    const nodeId = getNodeId(node);
    const cache = privateName ? nodeIdToGeneratedPrivateName : nodeIdToGeneratedName;
    return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags ?? 0 /* None */, formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix)));
  }
  function isUniqueName(name, privateName) {
    return isFileLevelUniqueNameInCurrentFile(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name);
  }
  function isReservedName(name, privateName) {
    return privateName ? !!(reservedPrivateNames == null ? void 0 : reservedPrivateNames.has(name)) : !!(reservedNames == null ? void 0 : reservedNames.has(name));
  }
  function isFileLevelUniqueNameInCurrentFile(name, _isPrivate) {
    return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
  }
  function isUniqueLocalName(name, container) {
    for (let node = container; node && isNodeDescendantOf(node, container); node = node.nextContainer) {
      if (canHaveLocals(node) && node.locals) {
        const local = node.locals.get(escapeLeadingUnderscores(name));
        if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
          return false;
        }
      }
    }
    return true;
  }
  function getTempFlags(formattedNameKey) {
    switch (formattedNameKey) {
      case "":
        return tempFlags;
      case "#":
        return privateNameTempFlags;
      default:
        return (formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) ?? 0 /* Auto */;
    }
  }
  function setTempFlags(formattedNameKey, flags) {
    switch (formattedNameKey) {
      case "":
        tempFlags = flags;
        break;
      case "#":
        privateNameTempFlags = flags;
        break;
      default:
        formattedNameTempFlags ?? (formattedNameTempFlags = /* @__PURE__ */ new Map());
        formattedNameTempFlags.set(formattedNameKey, flags);
        break;
    }
  }
  function makeTempVariableName(flags, reservedInNestedScopes, privateName, prefix, suffix) {
    if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* hash */) {
      prefix = prefix.slice(1);
    }
    const key = formatGeneratedName(privateName, prefix, "", suffix);
    let tempFlags2 = getTempFlags(key);
    if (flags && !(tempFlags2 & flags)) {
      const name = flags === 268435456 /* _i */ ? "_i" : "_n";
      const fullName = formatGeneratedName(privateName, prefix, name, suffix);
      if (isUniqueName(fullName, privateName)) {
        tempFlags2 |= flags;
        if (privateName) {
          reservePrivateNameInNestedScopes(fullName);
        } else if (reservedInNestedScopes) {
          reserveNameInNestedScopes(fullName);
        }
        setTempFlags(key, tempFlags2);
        return fullName;
      }
    }
    while (true) {
      const count = tempFlags2 & 268435455 /* CountMask */;
      tempFlags2++;
      if (count !== 8 && count !== 13) {
        const name = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26);
        const fullName = formatGeneratedName(privateName, prefix, name, suffix);
        if (isUniqueName(fullName, privateName)) {
          if (privateName) {
            reservePrivateNameInNestedScopes(fullName);
          } else if (reservedInNestedScopes) {
            reserveNameInNestedScopes(fullName);
          }
          setTempFlags(key, tempFlags2);
          return fullName;
        }
      }
    }
  }
  function makeUniqueName2(baseName, checkFn = isUniqueName, optimistic, scoped, privateName, prefix, suffix) {
    if (baseName.length > 0 && baseName.charCodeAt(0) === 35 /* hash */) {
      baseName = baseName.slice(1);
    }
    if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* hash */) {
      prefix = prefix.slice(1);
    }
    if (optimistic) {
      const fullName = formatGeneratedName(privateName, prefix, baseName, suffix);
      if (checkFn(fullName, privateName)) {
        if (privateName) {
          reservePrivateNameInNestedScopes(fullName);
        } else if (scoped) {
          reserveNameInNestedScopes(fullName);
        } else {
          generatedNames.add(fullName);
        }
        return fullName;
      }
    }
    if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
      baseName += "_";
    }
    let i = 1;
    while (true) {
      const fullName = formatGeneratedName(privateName, prefix, baseName + i, suffix);
      if (checkFn(fullName, privateName)) {
        if (privateName) {
          reservePrivateNameInNestedScopes(fullName);
        } else if (scoped) {
          reserveNameInNestedScopes(fullName);
        } else {
          generatedNames.add(fullName);
        }
        return fullName;
      }
      i++;
    }
  }
  function makeFileLevelOptimisticUniqueName(name) {
    return makeUniqueName2(
      name,
      isFileLevelUniqueNameInCurrentFile,
      /*optimistic*/
      true,
      /*scoped*/
      false,
      /*privateName*/
      false,
      /*prefix*/
      "",
      /*suffix*/
      ""
    );
  }
  function generateNameForModuleOrEnum(node) {
    const name = getTextOfNode2(node.name);
    return isUniqueLocalName(name, tryCast(node, canHaveLocals)) ? name : makeUniqueName2(
      name,
      isUniqueName,
      /*optimistic*/
      false,
      /*scoped*/
      false,
      /*privateName*/
      false,
      /*prefix*/
      "",
      /*suffix*/
      ""
    );
  }
  function generateNameForImportOrExportDeclaration(node) {
    const expr = getExternalModuleName(node);
    const baseName = isStringLiteral(expr) ? makeIdentifierFromModuleName(expr.text) : "module";
    return makeUniqueName2(
      baseName,
      isUniqueName,
      /*optimistic*/
      false,
      /*scoped*/
      false,
      /*privateName*/
      false,
      /*prefix*/
      "",
      /*suffix*/
      ""
    );
  }
  function generateNameForExportDefault() {
    return makeUniqueName2(
      "default",
      isUniqueName,
      /*optimistic*/
      false,
      /*scoped*/
      false,
      /*privateName*/
      false,
      /*prefix*/
      "",
      /*suffix*/
      ""
    );
  }
  function generateNameForClassExpression() {
    return makeUniqueName2(
      "class",
      isUniqueName,
      /*optimistic*/
      false,
      /*scoped*/
      false,
      /*privateName*/
      false,
      /*prefix*/
      "",
      /*suffix*/
      ""
    );
  }
  function generateNameForMethodOrAccessor(node, privateName, prefix, suffix) {
    if (isIdentifier(node.name)) {
      return generateNameCached(node.name, privateName);
    }
    return makeTempVariableName(
      0 /* Auto */,
      /*reservedInNestedScopes*/
      false,
      privateName,
      prefix,
      suffix
    );
  }
  function generateNameForNode(node, privateName, flags, prefix, suffix) {
    switch (node.kind) {
      case 80 /* Identifier */:
      case 81 /* PrivateIdentifier */:
        return makeUniqueName2(
          getTextOfNode2(node),
          isUniqueName,
          !!(flags & 16 /* Optimistic */),
          !!(flags & 8 /* ReservedInNestedScopes */),
          privateName,
          prefix,
          suffix
        );
      case 266 /* ModuleDeclaration */:
      case 265 /* EnumDeclaration */:
        Debug.assert(!prefix && !suffix && !privateName);
        return generateNameForModuleOrEnum(node);
      case 271 /* ImportDeclaration */:
      case 277 /* ExportDeclaration */:
        Debug.assert(!prefix && !suffix && !privateName);
        return generateNameForImportOrExportDeclaration(node);
      case 261 /* FunctionDeclaration */:
      case 262 /* ClassDeclaration */: {
        Debug.assert(!prefix && !suffix && !privateName);
        const name = node.name;
        if (name && !isGeneratedIdentifier(name)) {
          return generateNameForNode(
            name,
            /*privateName*/
            false,
            flags,
            prefix,
            suffix
          );
        }
        return generateNameForExportDefault();
      }
      case 276 /* ExportAssignment */:
        Debug.assert(!prefix && !suffix && !privateName);
        return generateNameForExportDefault();
      case 230 /* ClassExpression */:
        Debug.assert(!prefix && !suffix && !privateName);
        return generateNameForClassExpression();
      case 173 /* MethodDeclaration */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        return generateNameForMethodOrAccessor(node, privateName, prefix, suffix);
      case 166 /* ComputedPropertyName */:
        return makeTempVariableName(
          0 /* Auto */,
          /*reservedInNestedScopes*/
          true,
          privateName,
          prefix,
          suffix
        );
      default:
        return makeTempVariableName(
          0 /* Auto */,
          /*reservedInNestedScopes*/
          false,
          privateName,
          prefix,
          suffix
        );
    }
  }
  function makeName(name) {
    const autoGenerate = name.emitNode.autoGenerate;
    const prefix = formatGeneratedNamePart(autoGenerate.prefix, generateName);
    const suffix = formatGeneratedNamePart(autoGenerate.suffix);
    switch (autoGenerate.flags & 7 /* KindMask */) {
      case 1 /* Auto */:
        return makeTempVariableName(0 /* Auto */, !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), isPrivateIdentifier(name), prefix, suffix);
      case 2 /* Loop */:
        Debug.assertNode(name, isIdentifier);
        return makeTempVariableName(
          268435456 /* _i */,
          !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */),
          /*privateName*/
          false,
          prefix,
          suffix
        );
      case 3 /* Unique */:
        return makeUniqueName2(
          idText(name),
          autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueNameInCurrentFile : isUniqueName,
          !!(autoGenerate.flags & 16 /* Optimistic */),
          !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */),
          isPrivateIdentifier(name),
          prefix,
          suffix
        );
    }
    return Debug.fail(`Unsupported GeneratedIdentifierKind: ${Debug.formatEnum(
      autoGenerate.flags & 7 /* KindMask */,
      GeneratedIdentifierFlags,
      /*isFlags*/
      true
    )}.`);
  }
  function pipelineEmitWithComments(hint, node) {
    const pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
    const savedContainerPos = containerPos;
    const savedContainerEnd = containerEnd;
    const savedDeclarationListContainerEnd = declarationListContainerEnd;
    emitCommentsBeforeNode(node);
    pipelinePhase(hint, node);
    emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
  }
  function emitCommentsBeforeNode(node) {
    const emitFlags = getEmitFlags(node);
    const commentRange = getCommentRange(node);
    emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end);
    if (emitFlags & 4096 /* NoNestedComments */) {
      commentsDisabled = true;
    }
  }
  function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) {
    const emitFlags = getEmitFlags(node);
    const commentRange = getCommentRange(node);
    if (emitFlags & 4096 /* NoNestedComments */) {
      commentsDisabled = false;
    }
    emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
    const typeNode = getTypeNode(node);
    if (typeNode) {
      emitTrailingCommentsOfNode(node, emitFlags, typeNode.pos, typeNode.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd);
    }
  }
  function emitLeadingCommentsOfNode(node, emitFlags, pos, end) {
    enterComment();
    hasWrittenComment = false;
    const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0 || node.kind === 12 /* JsxText */;
    const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 12 /* JsxText */;
    if ((pos > 0 || end > 0) && pos !== end) {
      if (!skipLeadingComments) {
        emitLeadingComments(
          pos,
          /*isEmittedNode*/
          node.kind !== 358 /* NotEmittedStatement */
        );
      }
      if (!skipLeadingComments || pos >= 0 && (emitFlags & 1024 /* NoLeadingComments */) !== 0) {
        containerPos = pos;
      }
      if (!skipTrailingComments || end >= 0 && (emitFlags & 2048 /* NoTrailingComments */) !== 0) {
        containerEnd = end;
        if (node.kind === 260 /* VariableDeclarationList */) {
          declarationListContainerEnd = end;
        }
      }
    }
    forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
    exitComment();
  }
  function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) {
    enterComment();
    const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 12 /* JsxText */;
    forEach(getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
    if ((pos > 0 || end > 0) && pos !== end) {
      containerPos = savedContainerPos;
      containerEnd = savedContainerEnd;
      declarationListContainerEnd = savedDeclarationListContainerEnd;
      if (!skipTrailingComments && node.kind !== 358 /* NotEmittedStatement */) {
        emitTrailingComments(end);
      }
    }
    exitComment();
  }
  function emitLeadingSynthesizedComment(comment) {
    if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) {
      writer.writeLine();
    }
    writeSynthesizedComment(comment);
    if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
      writer.writeLine();
    } else {
      writer.writeSpace(" ");
    }
  }
  function emitTrailingSynthesizedComment(comment) {
    if (!writer.isAtStartOfLine()) {
      writer.writeSpace(" ");
    }
    writeSynthesizedComment(comment);
    if (comment.hasTrailingNewLine) {
      writer.writeLine();
    }
  }
  function writeSynthesizedComment(comment) {
    const text = formatSynthesizedComment(comment);
    const lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? computeLineStarts(text) : void 0;
    writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
  }
  function formatSynthesizedComment(comment) {
    return comment.kind === 3 /* MultiLineCommentTrivia */ ? `/*${comment.text}*/` : `//${comment.text}`;
  }
  function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
    enterComment();
    const { pos, end } = detachedRange;
    const emitFlags = getEmitFlags(node);
    const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0;
    const skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0;
    if (!skipLeadingComments) {
      emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
    }
    exitComment();
    if (emitFlags & 4096 /* NoNestedComments */ && !commentsDisabled) {
      commentsDisabled = true;
      emitCallback(node);
      commentsDisabled = false;
    } else {
      emitCallback(node);
    }
    enterComment();
    if (!skipTrailingComments) {
      emitLeadingComments(
        detachedRange.end,
        /*isEmittedNode*/
        true
      );
      if (hasWrittenComment && !writer.isAtStartOfLine()) {
        writer.writeLine();
      }
    }
    exitComment();
  }
  function originalNodesHaveSameParent(nodeA, nodeB) {
    nodeA = getOriginalNode(nodeA);
    return nodeA.parent && nodeA.parent === getOriginalNode(nodeB).parent;
  }
  function siblingNodePositionsAreComparable(previousNode, nextNode) {
    if (nextNode.pos < previousNode.end) {
      return false;
    }
    previousNode = getOriginalNode(previousNode);
    nextNode = getOriginalNode(nextNode);
    const parent2 = previousNode.parent;
    if (!parent2 || parent2 !== nextNode.parent) {
      return false;
    }
    const parentNodeArray = getContainingNodeArray(previousNode);
    const prevNodeIndex = parentNodeArray == null ? void 0 : parentNodeArray.indexOf(previousNode);
    return prevNodeIndex !== void 0 && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1;
  }
  function emitLeadingComments(pos, isEmittedNode) {
    hasWrittenComment = false;
    if (isEmittedNode) {
      if (pos === 0 && (currentSourceFile == null ? void 0 : currentSourceFile.isDeclarationFile)) {
        forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
      } else {
        forEachLeadingCommentToEmit(pos, emitLeadingComment);
      }
    } else if (pos === 0) {
      forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
    }
  }
  function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
    if (isTripleSlashComment(commentPos, commentEnd)) {
      emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
    }
  }
  function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
    if (!isTripleSlashComment(commentPos, commentEnd)) {
      emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
    }
  }
  function shouldWriteComment(text, pos) {
    if (printerOptions.onlyPrintJsDocStyle) {
      return isJSDocLikeText(text, pos) || isPinnedComment(text, pos);
    }
    return true;
  }
  function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
    if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos))
      return;
    if (!hasWrittenComment) {
      emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
      hasWrittenComment = true;
    }
    emitPos(commentPos);
    writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
    emitPos(commentEnd);
    if (hasTrailingNewLine) {
      writer.writeLine();
    } else if (kind === 3 /* MultiLineCommentTrivia */) {
      writer.writeSpace(" ");
    }
  }
  function emitLeadingCommentsOfPosition(pos) {
    if (commentsDisabled || pos === -1) {
      return;
    }
    emitLeadingComments(
      pos,
      /*isEmittedNode*/
      true
    );
  }
  function emitTrailingComments(pos) {
    forEachTrailingCommentToEmit(pos, emitTrailingComment);
  }
  function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
    if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos))
      return;
    if (!writer.isAtStartOfLine()) {
      writer.writeSpace(" ");
    }
    emitPos(commentPos);
    writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
    emitPos(commentEnd);
    if (hasTrailingNewLine) {
      writer.writeLine();
    }
  }
  function emitTrailingCommentsOfPosition(pos, prefixSpace, forceNoNewline) {
    if (commentsDisabled) {
      return;
    }
    enterComment();
    forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : forceNoNewline ? emitTrailingCommentOfPositionNoNewline : emitTrailingCommentOfPosition);
    exitComment();
  }
  function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) {
    if (!currentSourceFile)
      return;
    emitPos(commentPos);
    writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
    emitPos(commentEnd);
    if (kind === 2 /* SingleLineCommentTrivia */) {
      writer.writeLine();
    }
  }
  function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
    if (!currentSourceFile)
      return;
    emitPos(commentPos);
    writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
    emitPos(commentEnd);
    if (hasTrailingNewLine) {
      writer.writeLine();
    } else {
      writer.writeSpace(" ");
    }
  }
  function forEachLeadingCommentToEmit(pos, cb) {
    if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
      if (hasDetachedComments(pos)) {
        forEachLeadingCommentWithoutDetachedComments(cb);
      } else {
        forEachLeadingCommentRange(
          currentSourceFile.text,
          pos,
          cb,
          /*state*/
          pos
        );
      }
    }
  }
  function forEachTrailingCommentToEmit(end, cb) {
    if (currentSourceFile && (containerEnd === -1 || end !== containerEnd && end !== declarationListContainerEnd)) {
      forEachTrailingCommentRange(currentSourceFile.text, end, cb);
    }
  }
  function hasDetachedComments(pos) {
    return detachedCommentsInfo !== void 0 && last(detachedCommentsInfo).nodePos === pos;
  }
  function forEachLeadingCommentWithoutDetachedComments(cb) {
    if (!currentSourceFile)
      return;
    const pos = last(detachedCommentsInfo).detachedCommentEndPos;
    if (detachedCommentsInfo.length - 1) {
      detachedCommentsInfo.pop();
    } else {
      detachedCommentsInfo = void 0;
    }
    forEachLeadingCommentRange(
      currentSourceFile.text,
      pos,
      cb,
      /*state*/
      pos
    );
  }
  function emitDetachedCommentsAndUpdateCommentsInfo(range) {
    const currentDetachedCommentInfo = currentSourceFile && emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
    if (currentDetachedCommentInfo) {
      if (detachedCommentsInfo) {
        detachedCommentsInfo.push(currentDetachedCommentInfo);
      } else {
        detachedCommentsInfo = [currentDetachedCommentInfo];
      }
    }
  }
  function emitComment(text, lineMap, writer2, commentPos, commentEnd, newLine2) {
    if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos))
      return;
    emitPos(commentPos);
    writeCommentRange(text, lineMap, writer2, commentPos, commentEnd, newLine2);
    emitPos(commentEnd);
  }
  function isTripleSlashComment(commentPos, commentEnd) {
    return !!currentSourceFile && isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
  }
  function getParsedSourceMap(node) {
    if (node.parsedSourceMap === void 0 && node.sourceMapText !== void 0) {
      node.parsedSourceMap = tryParseRawSourceMap(node.sourceMapText) || false;
    }
    return node.parsedSourceMap || void 0;
  }
  function pipelineEmitWithSourceMaps(hint, node) {
    const pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
    emitSourceMapsBeforeNode(node);
    pipelinePhase(hint, node);
    emitSourceMapsAfterNode(node);
  }
  function emitSourceMapsBeforeNode(node) {
    const emitFlags = getEmitFlags(node);
    const sourceMapRange = getSourceMapRange(node);
    if (isUnparsedNode(node)) {
      Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers");
      const parsed = getParsedSourceMap(node.parent);
      if (parsed && sourceMapGenerator) {
        sourceMapGenerator.appendSourceMap(
          writer.getLine(),
          writer.getColumn(),
          parsed,
          node.parent.sourceMapPath,
          node.parent.getLineAndCharacterOfPosition(node.pos),
          node.parent.getLineAndCharacterOfPosition(node.end)
        );
      }
    } else {
      const source = sourceMapRange.source || sourceMapSource;
      if (node.kind !== 358 /* NotEmittedStatement */ && (emitFlags & 32 /* NoLeadingSourceMap */) === 0 && sourceMapRange.pos >= 0) {
        emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos));
      }
      if (emitFlags & 128 /* NoNestedSourceMaps */) {
        sourceMapsDisabled = true;
      }
    }
  }
  function emitSourceMapsAfterNode(node) {
    const emitFlags = getEmitFlags(node);
    const sourceMapRange = getSourceMapRange(node);
    if (!isUnparsedNode(node)) {
      if (emitFlags & 128 /* NoNestedSourceMaps */) {
        sourceMapsDisabled = false;
      }
      if (node.kind !== 358 /* NotEmittedStatement */ && (emitFlags & 64 /* NoTrailingSourceMap */) === 0 && sourceMapRange.end >= 0) {
        emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end);
      }
    }
  }
  function skipSourceTrivia(source, pos) {
    return source.skipTrivia ? source.skipTrivia(pos) : skipTrivia(source.text, pos);
  }
  function emitPos(pos) {
    if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
      return;
    }
    const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos);
    sourceMapGenerator.addMapping(
      writer.getLine(),
      writer.getColumn(),
      sourceMapSourceIndex,
      sourceLine,
      sourceCharacter,
      /*nameIndex*/
      void 0
    );
  }
  function emitSourcePos(source, pos) {
    if (source !== sourceMapSource) {
      const savedSourceMapSource = sourceMapSource;
      const savedSourceMapSourceIndex = sourceMapSourceIndex;
      setSourceMapSource(source);
      emitPos(pos);
      resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex);
    } else {
      emitPos(pos);
    }
  }
  function emitTokenWithSourceMap(node, token, writer2, tokenPos, emitCallback) {
    if (sourceMapsDisabled || node && isInJsonFile(node)) {
      return emitCallback(token, writer2, tokenPos);
    }
    const emitNode = node && node.emitNode;
    const emitFlags = emitNode && emitNode.flags || 0 /* None */;
    const range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
    const source = range && range.source || sourceMapSource;
    tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
    if ((emitFlags & 256 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
      emitSourcePos(source, tokenPos);
    }
    tokenPos = emitCallback(token, writer2, tokenPos);
    if (range)
      tokenPos = range.end;
    if ((emitFlags & 512 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
      emitSourcePos(source, tokenPos);
    }
    return tokenPos;
  }
  function setSourceMapSource(source) {
    if (sourceMapsDisabled) {
      return;
    }
    sourceMapSource = source;
    if (source === mostRecentlyAddedSourceMapSource) {
      sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex;
      return;
    }
    if (isJsonSourceMapSource(source)) {
      return;
    }
    sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
    if (printerOptions.inlineSources) {
      sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
    }
    mostRecentlyAddedSourceMapSource = source;
    mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex;
  }
  function resetSourceMapSource(source, sourceIndex) {
    sourceMapSource = source;
    sourceMapSourceIndex = sourceIndex;
  }
  function isJsonSourceMapSource(sourceFile) {
    return fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
  }
}
function createBracketsMap() {
  const brackets2 = [];
  brackets2[1024 /* Braces */] = ["{", "}"];
  brackets2[2048 /* Parenthesis */] = ["(", ")"];
  brackets2[4096 /* AngleBrackets */] = ["<", ">"];
  brackets2[8192 /* SquareBrackets */] = ["[", "]"];
  return brackets2;
}
function getOpeningBracket(format) {
  return brackets[format & 15360 /* BracketsMask */][0];
}
function getClosingBracket(format) {
  return brackets[format & 15360 /* BracketsMask */][1];
}
function emitListItemNoParenthesizer(node, emit, _parenthesizerRule, _index) {
  emit(node);
}
function emitListItemWithParenthesizerRuleSelector(node, emit, parenthesizerRuleSelector, index) {
  emit(node, parenthesizerRuleSelector.select(index));
}
function emitListItemWithParenthesizerRule(node, emit, parenthesizerRule, _index) {
  emit(node, parenthesizerRule);
}
function getEmitListItem(emit, parenthesizerRule) {
  return emit.length === 1 ? emitListItemNoParenthesizer : typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector : emitListItemWithParenthesizerRule;
}

// src/compiler/watchUtilities.ts
function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
  if (!host.getDirectories || !host.readDirectory) {
    return void 0;
  }
  const cachedReadDirectoryResult = /* @__PURE__ */ new Map();
  const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
  return {
    useCaseSensitiveFileNames,
    fileExists,
    readFile: (path, encoding) => host.readFile(path, encoding),
    directoryExists: host.directoryExists && directoryExists,
    getDirectories,
    readDirectory,
    createDirectory: host.createDirectory && createDirectory,
    writeFile: host.writeFile && writeFile2,
    addOrDeleteFileOrDirectory,
    addOrDeleteFile,
    clearCache,
    realpath: host.realpath && realpath
  };
  function toPath3(fileName) {
    return toPath(fileName, currentDirectory, getCanonicalFileName);
  }
  function getCachedFileSystemEntries(rootDirPath) {
    return cachedReadDirectoryResult.get(ensureTrailingDirectorySeparator(rootDirPath));
  }
  function getCachedFileSystemEntriesForBaseDir(path) {
    const entries = getCachedFileSystemEntries(getDirectoryPath(path));
    if (!entries) {
      return entries;
    }
    if (!entries.sortedAndCanonicalizedFiles) {
      entries.sortedAndCanonicalizedFiles = entries.files.map(getCanonicalFileName).sort();
      entries.sortedAndCanonicalizedDirectories = entries.directories.map(getCanonicalFileName).sort();
    }
    return entries;
  }
  function getBaseNameOfFileName(fileName) {
    return getBaseFileName(normalizePath(fileName));
  }
  function createCachedFileSystemEntries(rootDir, rootDirPath) {
    var _a;
    if (!host.realpath || ensureTrailingDirectorySeparator(toPath3(host.realpath(rootDir))) === rootDirPath) {
      const resultFromHost = {
        files: map(host.readDirectory(
          rootDir,
          /*extensions*/
          void 0,
          /*exclude*/
          void 0,
          /*include*/
          ["*.*"]
        ), getBaseNameOfFileName) || [],
        directories: host.getDirectories(rootDir) || []
      };
      cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
      return resultFromHost;
    }
    if ((_a = host.directoryExists) == null ? void 0 : _a.call(host, rootDir)) {
      cachedReadDirectoryResult.set(rootDirPath, false);
      return false;
    }
    return void 0;
  }
  function tryReadDirectory2(rootDir, rootDirPath) {
    rootDirPath = ensureTrailingDirectorySeparator(rootDirPath);
    const cachedResult = getCachedFileSystemEntries(rootDirPath);
    if (cachedResult) {
      return cachedResult;
    }
    try {
      return createCachedFileSystemEntries(rootDir, rootDirPath);
    } catch (_e) {
      Debug.assert(!cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(rootDirPath)));
      return void 0;
    }
  }
  function hasEntry(entries, name) {
    const index = binarySearch(entries, name, identity, compareStringsCaseSensitive);
    return index >= 0;
  }
  function writeFile2(fileName, data, writeByteOrderMark) {
    const path = toPath3(fileName);
    const result = getCachedFileSystemEntriesForBaseDir(path);
    if (result) {
      updateFilesOfFileSystemEntry(
        result,
        getBaseNameOfFileName(fileName),
        /*fileExists*/
        true
      );
    }
    return host.writeFile(fileName, data, writeByteOrderMark);
  }
  function fileExists(fileName) {
    const path = toPath3(fileName);
    const result = getCachedFileSystemEntriesForBaseDir(path);
    return result && hasEntry(result.sortedAndCanonicalizedFiles, getCanonicalFileName(getBaseNameOfFileName(fileName))) || host.fileExists(fileName);
  }
  function directoryExists(dirPath) {
    const path = toPath3(dirPath);
    return cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
  }
  function createDirectory(dirPath) {
    const path = toPath3(dirPath);
    const result = getCachedFileSystemEntriesForBaseDir(path);
    if (result) {
      const baseName = getBaseNameOfFileName(dirPath);
      const canonicalizedBaseName = getCanonicalFileName(baseName);
      const canonicalizedDirectories = result.sortedAndCanonicalizedDirectories;
      if (insertSorted(canonicalizedDirectories, canonicalizedBaseName, compareStringsCaseSensitive)) {
        result.directories.push(baseName);
      }
    }
    host.createDirectory(dirPath);
  }
  function getDirectories(rootDir) {
    const rootDirPath = toPath3(rootDir);
    const result = tryReadDirectory2(rootDir, rootDirPath);
    if (result) {
      return result.directories.slice();
    }
    return host.getDirectories(rootDir);
  }
  function readDirectory(rootDir, extensions, excludes, includes, depth) {
    const rootDirPath = toPath3(rootDir);
    const rootResult = tryReadDirectory2(rootDir, rootDirPath);
    let rootSymLinkResult;
    if (rootResult !== void 0) {
      return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
    }
    return host.readDirectory(rootDir, extensions, excludes, includes, depth);
    function getFileSystemEntries(dir) {
      const path = toPath3(dir);
      if (path === rootDirPath) {
        return rootResult || getFileSystemEntriesFromHost(dir, path);
      }
      const result = tryReadDirectory2(dir, path);
      return result !== void 0 ? result || getFileSystemEntriesFromHost(dir, path) : emptyFileSystemEntries;
    }
    function getFileSystemEntriesFromHost(dir, path) {
      if (rootSymLinkResult && path === rootDirPath)
        return rootSymLinkResult;
      const result = {
        files: map(host.readDirectory(
          dir,
          /*extensions*/
          void 0,
          /*exclude*/
          void 0,
          /*include*/
          ["*.*"]
        ), getBaseNameOfFileName) || emptyArray,
        directories: host.getDirectories(dir) || emptyArray
      };
      if (path === rootDirPath)
        rootSymLinkResult = result;
      return result;
    }
  }
  function realpath(s) {
    return host.realpath ? host.realpath(s) : s;
  }
  function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
    const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
    if (existingResult !== void 0) {
      clearCache();
      return void 0;
    }
    const parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
    if (!parentResult) {
      return void 0;
    }
    if (!host.directoryExists) {
      clearCache();
      return void 0;
    }
    const baseName = getBaseNameOfFileName(fileOrDirectory);
    const fsQueryResult = {
      fileExists: host.fileExists(fileOrDirectoryPath),
      directoryExists: host.directoryExists(fileOrDirectoryPath)
    };
    if (fsQueryResult.directoryExists || hasEntry(parentResult.sortedAndCanonicalizedDirectories, getCanonicalFileName(baseName))) {
      clearCache();
    } else {
      updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
    }
    return fsQueryResult;
  }
  function addOrDeleteFile(fileName, filePath, eventKind) {
    if (eventKind === 1 /* Changed */) {
      return;
    }
    const parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
    if (parentResult) {
      updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === 0 /* Created */);
    }
  }
  function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists2) {
    const canonicalizedFiles = parentResult.sortedAndCanonicalizedFiles;
    const canonicalizedBaseName = getCanonicalFileName(baseName);
    if (fileExists2) {
      if (insertSorted(canonicalizedFiles, canonicalizedBaseName, compareStringsCaseSensitive)) {
        parentResult.files.push(baseName);
      }
    } else {
      const sortedIndex = binarySearch(canonicalizedFiles, canonicalizedBaseName, identity, compareStringsCaseSensitive);
      if (sortedIndex >= 0) {
        canonicalizedFiles.splice(sortedIndex, 1);
        const unsortedIndex = parentResult.files.findIndex((entry) => getCanonicalFileName(entry) === canonicalizedBaseName);
        parentResult.files.splice(unsortedIndex, 1);
      }
    }
  }
  function clearCache() {
    cachedReadDirectoryResult.clear();
  }
}
var ConfigFileProgramReloadLevel = /* @__PURE__ */ ((ConfigFileProgramReloadLevel2) => {
  ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["None"] = 0] = "None";
  ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["Partial"] = 1] = "Partial";
  ConfigFileProgramReloadLevel2[ConfigFileProgramReloadLevel2["Full"] = 2] = "Full";
  return ConfigFileProgramReloadLevel2;
})(ConfigFileProgramReloadLevel || {});
function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath3) {
  var _a;
  const extendedConfigs = arrayToMap(((_a = options == null ? void 0 : options.configFile) == null ? void 0 : _a.extendedSourceFiles) || emptyArray, toPath3);
  extendedConfigFilesMap.forEach((watcher, extendedConfigFilePath) => {
    if (!extendedConfigs.has(extendedConfigFilePath)) {
      watcher.projects.delete(projectPath);
      watcher.close();
    }
  });
  extendedConfigs.forEach((extendedConfigFileName, extendedConfigFilePath) => {
    const existing = extendedConfigFilesMap.get(extendedConfigFilePath);
    if (existing) {
      existing.projects.add(projectPath);
    } else {
      extendedConfigFilesMap.set(extendedConfigFilePath, {
        projects: /* @__PURE__ */ new Set([projectPath]),
        watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath),
        close: () => {
          const existing2 = extendedConfigFilesMap.get(extendedConfigFilePath);
          if (!existing2 || existing2.projects.size !== 0)
            return;
          existing2.watcher.close();
          extendedConfigFilesMap.delete(extendedConfigFilePath);
        }
      });
    }
  });
}
function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) {
  extendedConfigFilesMap.forEach((watcher) => {
    if (watcher.projects.delete(projectPath))
      watcher.close();
  });
}
function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3) {
  if (!extendedConfigCache.delete(extendedConfigFilePath))
    return;
  extendedConfigCache.forEach(({ extendedResult }, key) => {
    var _a;
    if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some((extendedFile) => toPath3(extendedFile) === extendedConfigFilePath)) {
      cleanExtendedConfigCache(extendedConfigCache, key, toPath3);
    }
  });
}
function updatePackageJsonWatch(lookups, packageJsonWatches, createPackageJsonWatch) {
  const newMap = new Map(lookups);
  mutateMap(
    packageJsonWatches,
    newMap,
    {
      createNewValue: createPackageJsonWatch,
      onDeleteValue: closeFileWatcher
    }
  );
}
function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
  const missingFilePaths = program.getMissingFilePaths();
  const newMissingFilePathMap = arrayToMap(missingFilePaths, identity, returnTrue);
  mutateMap(
    missingFileWatches,
    newMissingFilePathMap,
    {
      // Watch the missing files
      createNewValue: createMissingFileWatch,
      // Files that are no longer missing (e.g. because they are no longer required)
      // should no longer be watched.
      onDeleteValue: closeFileWatcher
    }
  );
}
function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
  mutateMap(
    existingWatchedForWildcards,
    wildcardDirectories,
    {
      // Create new watch and recursive info
      createNewValue: createWildcardDirectoryWatcher,
      // Close existing watch thats not needed any more
      onDeleteValue: closeFileWatcherOf,
      // Close existing watch that doesnt match in the flags
      onExistingValue: updateWildcardDirectoryWatcher
    }
  );
  function createWildcardDirectoryWatcher(directory, flags) {
    return {
      watcher: watchDirectory(directory, flags),
      flags
    };
  }
  function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
    if (existingWatcher.flags === flags) {
      return;
    }
    existingWatcher.watcher.close();
    existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
  }
}
function isIgnoredFileFromWildCardWatching({
  watchedDirPath,
  fileOrDirectory,
  fileOrDirectoryPath,
  configFileName,
  options,
  program,
  extraFileExtensions,
  currentDirectory,
  useCaseSensitiveFileNames,
  writeLog,
  toPath: toPath3
}) {
  const newPath = removeIgnoredPath(fileOrDirectoryPath);
  if (!newPath) {
    writeLog(`Project: ${configFileName} Detected ignored path: ${fileOrDirectory}`);
    return true;
  }
  fileOrDirectoryPath = newPath;
  if (fileOrDirectoryPath === watchedDirPath)
    return false;
  if (hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) {
    writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`);
    return true;
  }
  if (isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
    writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`);
    return true;
  }
  if (!program)
    return false;
  if (outFile(options) || options.outDir)
    return false;
  if (isDeclarationFileName(fileOrDirectoryPath)) {
    if (options.declarationDir)
      return false;
  } else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) {
    return false;
  }
  const filePathWithoutExtension = removeFileExtension(fileOrDirectoryPath);
  const realProgram = isArray(program) ? void 0 : isBuilderProgram(program) ? program.getProgramOrUndefined() : program;
  const builderProgram = !realProgram && !isArray(program) ? program : void 0;
  if (hasSourceFile(filePathWithoutExtension + ".ts" /* Ts */) || hasSourceFile(filePathWithoutExtension + ".tsx" /* Tsx */)) {
    writeLog(`Project: ${configFileName} Detected output file: ${fileOrDirectory}`);
    return true;
  }
  return false;
  function hasSourceFile(file) {
    return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file);
  }
}
function isBuilderProgram(program) {
  return !!program.getState;
}
function isEmittedFileOfProgram(program, file) {
  if (!program) {
    return false;
  }
  return program.isEmittedFile(file);
}
var WatchLogLevel = /* @__PURE__ */ ((WatchLogLevel2) => {
  WatchLogLevel2[WatchLogLevel2["None"] = 0] = "None";
  WatchLogLevel2[WatchLogLevel2["TriggerOnly"] = 1] = "TriggerOnly";
  WatchLogLevel2[WatchLogLevel2["Verbose"] = 2] = "Verbose";
  return WatchLogLevel2;
})(WatchLogLevel || {});
function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) {
  setSysLog(watchLogLevel === 2 /* Verbose */ ? log : noop);
  const plainInvokeFactory = {
    watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options),
    watchDirectory: (directory, callback, flags, options) => host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options)
  };
  const triggerInvokingFactory = watchLogLevel !== 0 /* None */ ? {
    watchFile: createTriggerLoggingAddWatch("watchFile"),
    watchDirectory: createTriggerLoggingAddWatch("watchDirectory")
  } : void 0;
  const factory2 = watchLogLevel === 2 /* Verbose */ ? {
    watchFile: createFileWatcherWithLogging,
    watchDirectory: createDirectoryWatcherWithLogging
  } : triggerInvokingFactory || plainInvokeFactory;
  const excludeWatcherFactory = watchLogLevel === 2 /* Verbose */ ? createExcludeWatcherWithLogging : returnNoopFileWatcher;
  return {
    watchFile: createExcludeHandlingAddWatch("watchFile"),
    watchDirectory: createExcludeHandlingAddWatch("watchDirectory")
  };
  function createExcludeHandlingAddWatch(key) {
    return (file, cb, flags, options, detailInfo1, detailInfo2) => {
      var _a;
      return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call(
        /*thisArgs*/
        void 0,
        file,
        cb,
        flags,
        options,
        detailInfo1,
        detailInfo2
      ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2);
    };
  }
  function useCaseSensitiveFileNames() {
    return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames();
  }
  function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) {
    log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`);
    return {
      close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`)
    };
  }
  function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
    log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`);
    const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2);
    return {
      close: () => {
        log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`);
        watcher.close();
      }
    };
  }
  function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
    const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`;
    log(watchInfo);
    const start2 = timestamp();
    const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2);
    const elapsed = timestamp() - start2;
    log(`Elapsed:: ${elapsed}ms ${watchInfo}`);
    return {
      close: () => {
        const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`;
        log(watchInfo2);
        const start3 = timestamp();
        watcher.close();
        const elapsed2 = timestamp() - start3;
        log(`Elapsed:: ${elapsed2}ms ${watchInfo2}`);
      }
    };
  }
  function createTriggerLoggingAddWatch(key) {
    return (file, cb, flags, options, detailInfo1, detailInfo2) => plainInvokeFactory[key].call(
      /*thisArgs*/
      void 0,
      file,
      (...args) => {
        const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`;
        log(triggerredInfo);
        const start2 = timestamp();
        cb.call(
          /*thisArg*/
          void 0,
          ...args
        );
        const elapsed = timestamp() - start2;
        log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`);
      },
      flags,
      options,
      detailInfo1,
      detailInfo2
    );
  }
  function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) {
    return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`;
  }
}
function getFallbackOptions(options) {
  const fallbackPolling = options == null ? void 0 : options.fallbackPolling;
  return {
    watchFile: fallbackPolling !== void 0 ? fallbackPolling : 1 /* PriorityPollingInterval */
  };
}
function closeFileWatcherOf(objWithWatcher) {
  objWithWatcher.watcher.close();
}

// src/compiler/program.ts
function findConfigFile(searchPath, fileExists, configName = "tsconfig.json") {
  return forEachAncestorDirectory(searchPath, (ancestor) => {
    const fileName = combinePaths(ancestor, configName);
    return fileExists(fileName) ? fileName : void 0;
  });
}
function resolveTripleslashReference(moduleName, containingFile) {
  const basePath = getDirectoryPath(containingFile);
  const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
  return normalizePath(referencedFileName);
}
function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
  let commonPathComponents;
  const failed = forEach(fileNames, (sourceFile) => {
    const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory);
    sourcePathComponents.pop();
    if (!commonPathComponents) {
      commonPathComponents = sourcePathComponents;
      return;
    }
    const n = Math.min(commonPathComponents.length, sourcePathComponents.length);
    for (let i = 0; i < n; i++) {
      if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
        if (i === 0) {
          return true;
        }
        commonPathComponents.length = i;
        break;
      }
    }
    if (sourcePathComponents.length < commonPathComponents.length) {
      commonPathComponents.length = sourcePathComponents.length;
    }
  });
  if (failed) {
    return "";
  }
  if (!commonPathComponents) {
    return currentDirectory;
  }
  return getPathFromPathComponents(commonPathComponents);
}
function createCompilerHost(options, setParentNodes) {
  return createCompilerHostWorker(options, setParentNodes);
}
function createGetSourceFile(readFile, getCompilerOptions, setParentNodes) {
  return (fileName, languageVersionOrOptions, onError) => {
    let text;
    try {
      mark("beforeIORead");
      text = readFile(fileName, getCompilerOptions().charset);
      mark("afterIORead");
      measure("I/O Read", "beforeIORead", "afterIORead");
    } catch (e) {
      if (onError) {
        onError(e.message);
      }
      text = "";
    }
    return text !== void 0 ? createSourceFile(fileName, text, languageVersionOrOptions, setParentNodes) : void 0;
  };
}
function createWriteFileMeasuringIO(actualWriteFile, createDirectory, directoryExists) {
  return (fileName, data, writeByteOrderMark, onError) => {
    try {
      mark("beforeIOWrite");
      writeFileEnsuringDirectories(
        fileName,
        data,
        writeByteOrderMark,
        actualWriteFile,
        createDirectory,
        directoryExists
      );
      mark("afterIOWrite");
      measure("I/O Write", "beforeIOWrite", "afterIOWrite");
    } catch (e) {
      if (onError) {
        onError(e.message);
      }
    }
  };
}
function createCompilerHostWorker(options, setParentNodes, system = sys) {
  const existingDirectories = /* @__PURE__ */ new Map();
  const getCanonicalFileName = createGetCanonicalFileName(system.useCaseSensitiveFileNames);
  function directoryExists(directoryPath) {
    if (existingDirectories.has(directoryPath)) {
      return true;
    }
    if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
      existingDirectories.set(directoryPath, true);
      return true;
    }
    return false;
  }
  function getDefaultLibLocation() {
    return getDirectoryPath(normalizePath(system.getExecutingFilePath()));
  }
  const newLine = getNewLineCharacter(options);
  const realpath = system.realpath && ((path) => system.realpath(path));
  const compilerHost = {
    getSourceFile: createGetSourceFile((fileName) => compilerHost.readFile(fileName), () => options, setParentNodes),
    getDefaultLibLocation,
    getDefaultLibFileName: (options2) => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options2)),
    writeFile: createWriteFileMeasuringIO(
      (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark),
      (path) => (compilerHost.createDirectory || system.createDirectory)(path),
      (path) => directoryExists(path)
    ),
    getCurrentDirectory: memoize(() => system.getCurrentDirectory()),
    useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames,
    getCanonicalFileName,
    getNewLine: () => newLine,
    fileExists: (fileName) => system.fileExists(fileName),
    readFile: (fileName) => system.readFile(fileName),
    trace: (s) => system.write(s + newLine),
    directoryExists: (directoryName) => system.directoryExists(directoryName),
    getEnvironmentVariable: (name) => system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : "",
    getDirectories: (path) => system.getDirectories(path),
    realpath,
    readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth),
    createDirectory: (d) => system.createDirectory(d),
    createHash: maybeBind(system, system.createHash)
  };
  return compilerHost;
}
function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) {
  const originalReadFile = host.readFile;
  const originalFileExists = host.fileExists;
  const originalDirectoryExists = host.directoryExists;
  const originalCreateDirectory = host.createDirectory;
  const originalWriteFile = host.writeFile;
  const readFileCache = /* @__PURE__ */ new Map();
  const fileExistsCache = /* @__PURE__ */ new Map();
  const directoryExistsCache = /* @__PURE__ */ new Map();
  const sourceFileCache = /* @__PURE__ */ new Map();
  const readFileWithCache = (fileName) => {
    const key = toPath3(fileName);
    const value = readFileCache.get(key);
    if (value !== void 0)
      return value !== false ? value : void 0;
    return setReadFileCache(key, fileName);
  };
  const setReadFileCache = (key, fileName) => {
    const newValue = originalReadFile.call(host, fileName);
    readFileCache.set(key, newValue !== void 0 ? newValue : false);
    return newValue;
  };
  host.readFile = (fileName) => {
    const key = toPath3(fileName);
    const value = readFileCache.get(key);
    if (value !== void 0)
      return value !== false ? value : void 0;
    if (!fileExtensionIs(fileName, ".json" /* Json */) && !isBuildInfoFile(fileName)) {
      return originalReadFile.call(host, fileName);
    }
    return setReadFileCache(key, fileName);
  };
  const getSourceFileWithCache = getSourceFile ? (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
    const key = toPath3(fileName);
    const impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : void 0;
    const forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat);
    const value = forImpliedNodeFormat == null ? void 0 : forImpliedNodeFormat.get(key);
    if (value)
      return value;
    const sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
    if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".json" /* Json */))) {
      sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || /* @__PURE__ */ new Map()).set(key, sourceFile));
    }
    return sourceFile;
  } : void 0;
  host.fileExists = (fileName) => {
    const key = toPath3(fileName);
    const value = fileExistsCache.get(key);
    if (value !== void 0)
      return value;
    const newValue = originalFileExists.call(host, fileName);
    fileExistsCache.set(key, !!newValue);
    return newValue;
  };
  if (originalWriteFile) {
    host.writeFile = (fileName, data, ...rest) => {
      const key = toPath3(fileName);
      fileExistsCache.delete(key);
      const value = readFileCache.get(key);
      if (value !== void 0 && value !== data) {
        readFileCache.delete(key);
        sourceFileCache.forEach((map2) => map2.delete(key));
      } else if (getSourceFileWithCache) {
        sourceFileCache.forEach((map2) => {
          const sourceFile = map2.get(key);
          if (sourceFile && sourceFile.text !== data) {
            map2.delete(key);
          }
        });
      }
      originalWriteFile.call(host, fileName, data, ...rest);
    };
  }
  if (originalDirectoryExists) {
    host.directoryExists = (directory) => {
      const key = toPath3(directory);
      const value = directoryExistsCache.get(key);
      if (value !== void 0)
        return value;
      const newValue = originalDirectoryExists.call(host, directory);
      directoryExistsCache.set(key, !!newValue);
      return newValue;
    };
    if (originalCreateDirectory) {
      host.createDirectory = (directory) => {
        const key = toPath3(directory);
        directoryExistsCache.delete(key);
        originalCreateDirectory.call(host, directory);
      };
    }
  }
  return {
    originalReadFile,
    originalFileExists,
    originalDirectoryExists,
    originalCreateDirectory,
    originalWriteFile,
    getSourceFileWithCache,
    readFileWithCache
  };
}
function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
  let diagnostics;
  diagnostics = addRange(diagnostics, program.getConfigFileParsingDiagnostics());
  diagnostics = addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
  diagnostics = addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
  diagnostics = addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
  diagnostics = addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
  if (getEmitDeclarations(program.getCompilerOptions())) {
    diagnostics = addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
  }
  return sortAndDeduplicateDiagnostics(diagnostics || emptyArray);
}
function formatDiagnostics(diagnostics, host) {
  let output = "";
  for (const diagnostic of diagnostics) {
    output += formatDiagnostic(diagnostic, host);
  }
  return output;
}
function formatDiagnostic(diagnostic, host) {
  const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`;
  if (diagnostic.file) {
    const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
    const fileName = diagnostic.file.fileName;
    const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), (fileName2) => host.getCanonicalFileName(fileName2));
    return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage;
  }
  return errorMessage;
}
var ForegroundColorEscapeSequences = /* @__PURE__ */ ((ForegroundColorEscapeSequences2) => {
  ForegroundColorEscapeSequences2["Grey"] = "\x1B[90m";
  ForegroundColorEscapeSequences2["Red"] = "\x1B[91m";
  ForegroundColorEscapeSequences2["Yellow"] = "\x1B[93m";
  ForegroundColorEscapeSequences2["Blue"] = "\x1B[94m";
  ForegroundColorEscapeSequences2["Cyan"] = "\x1B[96m";
  return ForegroundColorEscapeSequences2;
})(ForegroundColorEscapeSequences || {});
var gutterStyleSequence = "\x1B[7m";
var gutterSeparator = " ";
var resetEscapeSequence = "\x1B[0m";
var ellipsis = "...";
var halfIndent = "  ";
var indent = "    ";
function getCategoryFormat(category) {
  switch (category) {
    case 1 /* Error */:
      return "\x1B[91m" /* Red */;
    case 0 /* Warning */:
      return "\x1B[93m" /* Yellow */;
    case 2 /* Suggestion */:
      return Debug.fail("Should never get an Info diagnostic on the command line.");
    case 3 /* Message */:
      return "\x1B[94m" /* Blue */;
  }
}
function formatColorAndReset(text, formatStyle) {
  return formatStyle + text + resetEscapeSequence;
}
function formatCodeSpan(file, start2, length2, indent3, squiggleColor, host) {
  const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start2);
  const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start2 + length2);
  const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line;
  const hasMoreThanFiveLines = lastLine - firstLine >= 4;
  let gutterWidth = (lastLine + 1 + "").length;
  if (hasMoreThanFiveLines) {
    gutterWidth = Math.max(ellipsis.length, gutterWidth);
  }
  let context = "";
  for (let i = firstLine; i <= lastLine; i++) {
    context += host.getNewLine();
    if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
      context += indent3 + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
      i = lastLine - 1;
    }
    const lineStart = getPositionOfLineAndCharacter(file, i, 0);
    const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
    let lineContent = file.text.slice(lineStart, lineEnd);
    lineContent = trimStringEnd(lineContent);
    lineContent = lineContent.replace(/\t/g, " ");
    context += indent3 + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
    context += lineContent + host.getNewLine();
    context += indent3 + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
    context += squiggleColor;
    if (i === firstLine) {
      const lastCharForLine = i === lastLine ? lastLineChar : void 0;
      context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
      context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
    } else if (i === lastLine) {
      context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
    } else {
      context += lineContent.replace(/./g, "~");
    }
    context += resetEscapeSequence;
  }
  return context;
}
function formatLocation(file, start2, host, color = formatColorAndReset) {
  const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start2);
  const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), (fileName) => host.getCanonicalFileName(fileName)) : file.fileName;
  let output = "";
  output += color(relativeFileName, "\x1B[96m" /* Cyan */);
  output += ":";
  output += color(`${firstLine + 1}`, "\x1B[93m" /* Yellow */);
  output += ":";
  output += color(`${firstLineChar + 1}`, "\x1B[93m" /* Yellow */);
  return output;
}
function formatDiagnosticsWithColorAndContext(diagnostics, host) {
  let output = "";
  for (const diagnostic of diagnostics) {
    if (diagnostic.file) {
      const { file, start: start2 } = diagnostic;
      output += formatLocation(file, start2, host);
      output += " - ";
    }
    output += formatColorAndReset(diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
    output += formatColorAndReset(` TS${diagnostic.code}: `, "\x1B[90m" /* Grey */);
    output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
    if (diagnostic.file && diagnostic.code !== Diagnostics.File_appears_to_be_binary.code) {
      output += host.getNewLine();
      output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host);
    }
    if (diagnostic.relatedInformation) {
      output += host.getNewLine();
      for (const { file, start: start2, length: length2, messageText } of diagnostic.relatedInformation) {
        if (file) {
          output += host.getNewLine();
          output += halfIndent + formatLocation(file, start2, host);
          output += formatCodeSpan(file, start2, length2, indent, "\x1B[96m" /* Cyan */, host);
        }
        output += host.getNewLine();
        output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
      }
    }
    output += host.getNewLine();
  }
  return output;
}
function flattenDiagnosticMessageText(diag2, newLine, indent3 = 0) {
  if (isString(diag2)) {
    return diag2;
  } else if (diag2 === void 0) {
    return "";
  }
  let result = "";
  if (indent3) {
    result += newLine;
    for (let i = 0; i < indent3; i++) {
      result += "  ";
    }
  }
  result += diag2.messageText;
  indent3++;
  if (diag2.next) {
    for (const kid of diag2.next) {
      result += flattenDiagnosticMessageText(kid, newLine, indent3);
    }
  }
  return result;
}
function getModeForFileReference(ref, containingFileMode) {
  return (isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode;
}
function getModeForResolutionAtIndex(file, index) {
  if (file.impliedNodeFormat === void 0)
    return void 0;
  return getModeForUsageLocation(file, getModuleNameStringLiteralAt(file, index));
}
function isExclusivelyTypeOnlyImportOrExport(decl) {
  var _a;
  if (isExportDeclaration(decl)) {
    return decl.isTypeOnly;
  }
  if ((_a = decl.importClause) == null ? void 0 : _a.isTypeOnly) {
    return true;
  }
  return false;
}
function getModeForUsageLocation(file, usage) {
  var _a, _b;
  if (file.impliedNodeFormat === void 0)
    return void 0;
  if (isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent)) {
    const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent);
    if (isTypeOnly) {
      const override = getResolutionModeOverrideForClause(usage.parent.assertClause);
      if (override) {
        return override;
      }
    }
  }
  if (usage.parent.parent && isImportTypeNode(usage.parent.parent)) {
    const override = getResolutionModeOverrideForClause((_a = usage.parent.parent.assertions) == null ? void 0 : _a.assertClause);
    if (override) {
      return override;
    }
  }
  if (file.impliedNodeFormat !== 99 /* ESNext */) {
    return isImportCall(walkUpParenthesizedExpressions(usage.parent)) ? 99 /* ESNext */ : 1 /* CommonJS */;
  }
  const exprParentParent = (_b = walkUpParenthesizedExpressions(usage.parent)) == null ? void 0 : _b.parent;
  return exprParentParent && isImportEqualsDeclaration(exprParentParent) ? 1 /* CommonJS */ : 99 /* ESNext */;
}
function getResolutionModeOverrideForClause(clause, grammarErrorOnNode) {
  if (!clause)
    return void 0;
  if (length(clause.elements) !== 1) {
    grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(clause, Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require);
    return void 0;
  }
  const elem = clause.elements[0];
  if (!isStringLiteralLike(elem.name))
    return void 0;
  if (elem.name.text !== "resolution-mode") {
    grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.name, Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions);
    return void 0;
  }
  if (!isStringLiteralLike(elem.value))
    return void 0;
  if (elem.value.text !== "import" && elem.value.text !== "require") {
    grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.value, Diagnostics.resolution_mode_should_be_either_require_or_import);
    return void 0;
  }
  return elem.value.text === "import" ? 99 /* ESNext */ : 1 /* CommonJS */;
}
var emptyResolution = {
  resolvedModule: void 0,
  resolvedTypeReferenceDirective: void 0
};
function getModuleResolutionName(literal) {
  return literal.text;
}
var moduleResolutionNameAndModeGetter = {
  getName: getModuleResolutionName,
  getMode: (entry, file) => getModeForUsageLocation(file, entry)
};
function createModuleResolutionLoader(containingFile, redirectedReference, options, host, cache) {
  return {
    nameAndMode: moduleResolutionNameAndModeGetter,
    resolve: (moduleName, resolutionMode) => resolveModuleName(
      moduleName,
      containingFile,
      options,
      host,
      cache,
      redirectedReference,
      resolutionMode
    )
  };
}
function getTypeReferenceResolutionName(entry) {
  return !isString(entry) ? toFileNameLowerCase(entry.fileName) : entry;
}
var typeReferenceResolutionNameAndModeGetter = {
  getName: getTypeReferenceResolutionName,
  getMode: (entry, file) => getModeForFileReference(entry, file == null ? void 0 : file.impliedNodeFormat)
};
function createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, host, cache) {
  return {
    nameAndMode: typeReferenceResolutionNameAndModeGetter,
    resolve: (typeRef, resoluionMode) => resolveTypeReferenceDirective(
      typeRef,
      containingFile,
      options,
      host,
      redirectedReference,
      cache,
      resoluionMode
    )
  };
}
function loadWithModeAwareCache(entries, containingFile, redirectedReference, options, containingSourceFile, host, resolutionCache, createLoader) {
  if (entries.length === 0)
    return emptyArray;
  const resolutions = [];
  const cache = /* @__PURE__ */ new Map();
  const loader = createLoader(containingFile, redirectedReference, options, host, resolutionCache);
  for (const entry of entries) {
    const name = loader.nameAndMode.getName(entry);
    const mode = loader.nameAndMode.getMode(entry, containingSourceFile);
    const key = createModeAwareCacheKey(name, mode);
    let result = cache.get(key);
    if (!result) {
      cache.set(key, result = loader.resolve(name, mode));
    }
    resolutions.push(result);
  }
  return resolutions;
}
function forEachResolvedProjectReference(resolvedProjectReferences, cb) {
  return forEachProjectReference(
    /*projectReferences*/
    void 0,
    resolvedProjectReferences,
    (resolvedRef, parent2) => resolvedRef && cb(resolvedRef, parent2)
  );
}
function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
  let seenResolvedRefs;
  return worker(
    projectReferences,
    resolvedProjectReferences,
    /*parent*/
    void 0
  );
  function worker(projectReferences2, resolvedProjectReferences2, parent2) {
    if (cbRef) {
      const result = cbRef(projectReferences2, parent2);
      if (result)
        return result;
    }
    return forEach(resolvedProjectReferences2, (resolvedRef, index) => {
      if (resolvedRef && (seenResolvedRefs == null ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) {
        return void 0;
      }
      const result = cbResolvedRef(resolvedRef, parent2, index);
      if (result || !resolvedRef)
        return result;
      (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path);
      return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef);
    });
  }
}
var inferredTypesContainingFile = "__inferred type names__.ts";
function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) {
  const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory;
  return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`);
}
function getLibraryNameFromLibFileName(libFileName) {
  const components = libFileName.split(".");
  let path = components[1];
  let i = 2;
  while (components[i] && components[i] !== "d") {
    path += (i === 2 ? "/" : "-") + components[i];
    i++;
  }
  return "@typescript/lib-" + path;
}
function getLibFileNameFromLibReference(libReference) {
  const libName = toFileNameLowerCase(libReference.fileName);
  const libFileName = libMap.get(libName);
  return { libName, libFileName };
}
function isReferencedFile(reason) {
  switch (reason == null ? void 0 : reason.kind) {
    case 3 /* Import */:
    case 4 /* ReferenceFile */:
    case 5 /* TypeReferenceDirective */:
    case 7 /* LibReferenceDirective */:
      return true;
    default:
      return false;
  }
}
function isReferenceFileLocation(location) {
  return location.pos !== void 0;
}
function getReferencedFileLocation(getSourceFileByPath, ref) {
  var _a, _b, _c, _d, _e, _f;
  const file = Debug.checkDefined(getSourceFileByPath(ref.file));
  const { kind, index } = ref;
  let pos, end, packageId, resolutionMode;
  switch (kind) {
    case 3 /* Import */:
      const importLiteral = getModuleNameStringLiteralAt(file, index);
      packageId = (_c = (_b = (_a = file.resolvedModules) == null ? void 0 : _a.get(importLiteral.text, getModeForResolutionAtIndex(file, index))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.packageId;
      if (importLiteral.pos === -1)
        return { file, packageId, text: importLiteral.text };
      pos = skipTrivia(file.text, importLiteral.pos);
      end = importLiteral.end;
      break;
    case 4 /* ReferenceFile */:
      ({ pos, end } = file.referencedFiles[index]);
      break;
    case 5 /* TypeReferenceDirective */:
      ({ pos, end, resolutionMode } = file.typeReferenceDirectives[index]);
      packageId = (_f = (_e = (_d = file.resolvedTypeReferenceDirectiveNames) == null ? void 0 : _d.get(toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) == null ? void 0 : _e.resolvedTypeReferenceDirective) == null ? void 0 : _f.packageId;
      break;
    case 7 /* LibReferenceDirective */:
      ({ pos, end } = file.libReferenceDirectives[index]);
      break;
    default:
      return Debug.assertNever(kind);
  }
  return { file, pos, end, packageId };
}
function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) {
  if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames()))
    return false;
  if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames))
    return false;
  let seenResolvedRefs;
  if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate))
    return false;
  if (program.getSourceFiles().some(sourceFileNotUptoDate))
    return false;
  if (program.getMissingFilePaths().some(fileExists))
    return false;
  const currentOptions = program.getCompilerOptions();
  if (!compareDataObjects(currentOptions, newOptions))
    return false;
  if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName)))
    return false;
  if (currentOptions.configFile && newOptions.configFile)
    return currentOptions.configFile.text === newOptions.configFile.text;
  return true;
  function sourceFileNotUptoDate(sourceFile) {
    return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolutions(sourceFile.path);
  }
  function sourceFileVersionUptoDate(sourceFile) {
    return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
  }
  function projectReferenceUptoDate(oldRef, newRef, index) {
    return projectReferenceIsEqualTo(oldRef, newRef) && resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
  }
  function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
    if (oldResolvedRef) {
      if (contains(seenResolvedRefs, oldResolvedRef))
        return true;
      const refPath2 = resolveProjectReferencePath(oldRef);
      const newParsedCommandLine = getParsedCommandLine(refPath2);
      if (!newParsedCommandLine)
        return false;
      if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile)
        return false;
      if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames))
        return false;
      (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
      return !forEach(oldResolvedRef.references, (childResolvedRef, index) => !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]));
    }
    const refPath = resolveProjectReferencePath(oldRef);
    return !getParsedCommandLine(refPath);
  }
}
function getConfigFileParsingDiagnostics(configFileParseResult) {
  return configFileParseResult.options.configFile ? [...configFileParseResult.options.configFile.parseDiagnostics, ...configFileParseResult.errors] : configFileParseResult.errors;
}
function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, options) {
  const result = getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options);
  return typeof result === "object" ? result.impliedNodeFormat : result;
}
function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) {
  switch (getEmitModuleResolutionKind(options)) {
    case 3 /* Node16 */:
    case 99 /* NodeNext */:
      return fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".mjs" /* Mjs */]) ? 99 /* ESNext */ : fileExtensionIsOneOf(fileName, [".d.cts" /* Dcts */, ".cts" /* Cts */, ".cjs" /* Cjs */]) ? 1 /* CommonJS */ : fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */]) ? lookupFromPackageJson() : void 0;
    default:
      return void 0;
  }
  function lookupFromPackageJson() {
    const state = getTemporaryModuleResolutionState(packageJsonInfoCache, host, options);
    const packageJsonLocations = [];
    state.failedLookupLocations = packageJsonLocations;
    state.affectingLocations = packageJsonLocations;
    const packageJsonScope = getPackageScopeForPath(fileName, state);
    const impliedNodeFormat = (packageJsonScope == null ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? 99 /* ESNext */ : 1 /* CommonJS */;
    return { impliedNodeFormat, packageJsonLocations, packageJsonScope };
  }
}
var plainJSErrors = /* @__PURE__ */ new Set([
  // binder errors
  Diagnostics.Cannot_redeclare_block_scoped_variable_0.code,
  Diagnostics.A_module_cannot_have_multiple_default_exports.code,
  Diagnostics.Another_export_default_is_here.code,
  Diagnostics.The_first_export_default_is_here.code,
  Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code,
  Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code,
  Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code,
  Diagnostics.constructor_is_a_reserved_word.code,
  Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code,
  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.code,
  Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code,
  Diagnostics.Invalid_use_of_0_in_strict_mode.code,
  Diagnostics.A_label_is_not_allowed_here.code,
  Diagnostics.with_statements_are_not_allowed_in_strict_mode.code,
  // grammar errors
  Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code,
  Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code,
  Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code,
  Diagnostics.A_class_member_cannot_have_the_0_keyword.code,
  Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code,
  Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code,
  Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code,
  Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code,
  Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code,
  Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code,
  Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code,
  Diagnostics.A_destructuring_declaration_must_have_an_initializer.code,
  Diagnostics.A_get_accessor_cannot_have_parameters.code,
  Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code,
  Diagnostics.A_rest_element_cannot_have_a_property_name.code,
  Diagnostics.A_rest_element_cannot_have_an_initializer.code,
  Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code,
  Diagnostics.A_rest_parameter_cannot_have_an_initializer.code,
  Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code,
  Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code,
  Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code,
  Diagnostics.A_set_accessor_cannot_have_rest_parameter.code,
  Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code,
  Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code,
  Diagnostics.An_export_declaration_cannot_have_modifiers.code,
  Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code,
  Diagnostics.An_import_declaration_cannot_have_modifiers.code,
  Diagnostics.An_object_member_cannot_be_declared_optional.code,
  Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code,
  Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code,
  Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code,
  Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code,
  Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code,
  Diagnostics.Classes_can_only_extend_a_single_class.code,
  Diagnostics.Classes_may_not_have_a_field_named_constructor.code,
  Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code,
  Diagnostics.Duplicate_label_0.code,
  Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code,
  Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code,
  Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code,
  Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code,
  Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code,
  Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code,
  Diagnostics.Jump_target_cannot_cross_function_boundary.code,
  Diagnostics.Line_terminator_not_permitted_before_arrow.code,
  Diagnostics.Modifiers_cannot_appear_here.code,
  Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code,
  Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code,
  Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
  Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code,
  Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code,
  Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code,
  Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code,
  Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code,
  Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code,
  Diagnostics.Trailing_comma_not_allowed.code,
  Diagnostics.Variable_declaration_list_cannot_be_empty.code,
  Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code,
  Diagnostics._0_expected.code,
  Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code,
  Diagnostics._0_list_cannot_be_empty.code,
  Diagnostics._0_modifier_already_seen.code,
  Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code,
  Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code,
  Diagnostics._0_modifier_cannot_appear_on_a_parameter.code,
  Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code,
  Diagnostics._0_modifier_cannot_be_used_here.code,
  Diagnostics._0_modifier_must_precede_1_modifier.code,
  Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code,
  Diagnostics.const_declarations_must_be_initialized.code,
  Diagnostics.extends_clause_already_seen.code,
  Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code,
  Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code,
  Diagnostics.Class_constructor_may_not_be_a_generator.code,
  Diagnostics.Class_constructor_may_not_be_an_accessor.code,
  Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code
]);
function shouldProgramCreateNewSourceFiles(program, newOptions) {
  if (!program)
    return false;
  return optionsHaveChanges(program.getCompilerOptions(), newOptions, sourceFileAffectingCompilerOptions);
}
function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion3) {
  return {
    rootNames,
    options,
    host,
    oldProgram,
    configFileParsingDiagnostics,
    typeScriptVersion: typeScriptVersion3
  };
}
function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
  const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions;
  const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion3 } = createProgramOptions;
  let { oldProgram } = createProgramOptions;
  const reportInvalidIgnoreDeprecations = memoize(() => createOptionValueDiagnostic("ignoreDeprecations", Diagnostics.Invalid_value_for_ignoreDeprecations));
  let processingDefaultLibFiles;
  let processingOtherFiles;
  let files;
  let symlinks;
  let commonSourceDirectory;
  let typeChecker;
  let classifiableNames;
  const ambientModuleNameToUnmodifiedFileName = /* @__PURE__ */ new Map();
  let fileReasons = createMultiMap();
  const cachedBindAndCheckDiagnosticsForFile = {};
  const cachedDeclarationDiagnosticsForFile = {};
  let resolvedTypeReferenceDirectives = createModeAwareCache();
  let fileProcessingDiagnostics;
  let automaticTypeDirectiveNames;
  let automaticTypeDirectiveResolutions;
  let resolvedLibReferences;
  let resolvedLibProcessing;
  let packageMap;
  const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
  let currentNodeModulesDepth = 0;
  const modulesWithElidedImports = /* @__PURE__ */ new Map();
  const sourceFilesFoundSearchingNodeModules = /* @__PURE__ */ new Map();
  (_a = tracing) == null ? void 0 : _a.push(
    tracing.Phase.Program,
    "createProgram",
    { configFilePath: options.configFilePath, rootDir: options.rootDir },
    /*separateBeginAndEnd*/
    true
  );
  mark("beforeProgram");
  const host = createProgramOptions.host || createCompilerHost(options);
  const configParsingHost = parseConfigHostFromCompilerHostLike(host);
  let skipDefaultLib = options.noLib;
  const getDefaultLibraryFileName = memoize(() => host.getDefaultLibFileName(options));
  const defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : getDirectoryPath(getDefaultLibraryFileName());
  const programDiagnostics = createDiagnosticCollection();
  const currentDirectory = host.getCurrentDirectory();
  const supportedExtensions = getSupportedExtensions(options);
  const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
  const hasEmitBlockingDiagnostics = /* @__PURE__ */ new Map();
  let _compilerOptionsObjectLiteralSyntax;
  let moduleResolutionCache;
  let actualResolveModuleNamesWorker;
  const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse;
  if (host.resolveModuleNameLiterals) {
    actualResolveModuleNamesWorker = host.resolveModuleNameLiterals.bind(host);
    moduleResolutionCache = (_b = host.getModuleResolutionCache) == null ? void 0 : _b.call(host);
  } else if (host.resolveModuleNames) {
    actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile, reusedNames) => host.resolveModuleNames(
      moduleNames.map(getModuleResolutionName),
      containingFile,
      reusedNames == null ? void 0 : reusedNames.map(getModuleResolutionName),
      redirectedReference,
      options2,
      containingSourceFile
    ).map(
      (resolved) => resolved ? resolved.extension !== void 0 ? { resolvedModule: resolved } : (
        // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
        { resolvedModule: { ...resolved, extension: extensionFromPath(resolved.resolvedFileName) } }
      ) : emptyResolution
    );
    moduleResolutionCache = (_c = host.getModuleResolutionCache) == null ? void 0 : _c.call(host);
  } else {
    moduleResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options);
    actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(
      moduleNames,
      containingFile,
      redirectedReference,
      options2,
      containingSourceFile,
      host,
      moduleResolutionCache,
      createModuleResolutionLoader
    );
  }
  let actualResolveTypeReferenceDirectiveNamesWorker;
  if (host.resolveTypeReferenceDirectiveReferences) {
    actualResolveTypeReferenceDirectiveNamesWorker = host.resolveTypeReferenceDirectiveReferences.bind(host);
  } else if (host.resolveTypeReferenceDirectives) {
    actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => host.resolveTypeReferenceDirectives(
      typeDirectiveNames.map(getTypeReferenceResolutionName),
      containingFile,
      redirectedReference,
      options2,
      containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat
    ).map((resolvedTypeReferenceDirective) => ({ resolvedTypeReferenceDirective }));
  } else {
    const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(
      currentDirectory,
      getCanonicalFileName,
      /*options*/
      void 0,
      moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()
    );
    actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(
      typeDirectiveNames,
      containingFile,
      redirectedReference,
      options2,
      containingSourceFile,
      host,
      typeReferenceDirectiveResolutionCache,
      createTypeReferenceResolutionLoader
    );
  }
  const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse;
  let actualResolveLibrary;
  if (host.resolveLibrary) {
    actualResolveLibrary = host.resolveLibrary.bind(host);
  } else {
    const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache());
    actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache);
  }
  const packageIdToSourceFile = /* @__PURE__ */ new Map();
  let sourceFileToPackageName = /* @__PURE__ */ new Map();
  let redirectTargetsMap = createMultiMap();
  let usesUriStyleNodeCoreModules = false;
  const filesByName = /* @__PURE__ */ new Map();
  let missingFilePaths;
  const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */ new Map() : void 0;
  let resolvedProjectReferences;
  let projectReferenceRedirects;
  let mapFromFileToProjectReferenceRedirects;
  let mapFromToProjectReferenceRedirectSource;
  const useSourceOfProjectReferenceRedirect = !!((_d = host.useSourceOfProjectReferenceRedirect) == null ? void 0 : _d.call(host)) && !options.disableSourceOfProjectReferenceRedirect;
  const { onProgramCreateComplete, fileExists, directoryExists } = updateHostForUseSourceOfProjectReferenceRedirect({
    compilerHost: host,
    getSymlinkCache,
    useSourceOfProjectReferenceRedirect,
    toPath: toPath3,
    getResolvedProjectReferences,
    getSourceOfProjectReferenceRedirect,
    forEachResolvedProjectReference: forEachResolvedProjectReference2
  });
  const readFile = host.readFile.bind(host);
  (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
  const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
  (_f = tracing) == null ? void 0 : _f.pop();
  let structureIsReused;
  (_g = tracing) == null ? void 0 : _g.push(tracing.Phase.Program, "tryReuseStructureFromOldProgram", {});
  structureIsReused = tryReuseStructureFromOldProgram();
  (_h = tracing) == null ? void 0 : _h.pop();
  if (structureIsReused !== 2 /* Completely */) {
    processingDefaultLibFiles = [];
    processingOtherFiles = [];
    if (projectReferences) {
      if (!resolvedProjectReferences) {
        resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
      }
      if (rootNames.length) {
        resolvedProjectReferences == null ? void 0 : resolvedProjectReferences.forEach((parsedRef, index) => {
          if (!parsedRef)
            return;
          const out = outFile(parsedRef.commandLine.options);
          if (useSourceOfProjectReferenceRedirect) {
            if (out || getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) {
              for (const fileName of parsedRef.commandLine.fileNames) {
                processProjectReferenceFile(fileName, { kind: 1 /* SourceFromProjectReference */, index });
              }
            }
          } else {
            if (out) {
              processProjectReferenceFile(changeExtension(out, ".d.ts"), { kind: 2 /* OutputFromProjectReference */, index });
            } else if (getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) {
              const getCommonSourceDirectory3 = memoize(() => getCommonSourceDirectoryOfConfig(parsedRef.commandLine, !host.useCaseSensitiveFileNames()));
              for (const fileName of parsedRef.commandLine.fileNames) {
                if (!isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */)) {
                  processProjectReferenceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3), { kind: 2 /* OutputFromProjectReference */, index });
                }
              }
            }
          }
        });
      }
    }
    (_i = tracing) == null ? void 0 : _i.push(tracing.Phase.Program, "processRootFiles", { count: rootNames.length });
    forEach(rootNames, (name, index) => processRootFile(
      name,
      /*isDefaultLib*/
      false,
      /*ignoreNoDefaultLib*/
      false,
      { kind: 0 /* RootFile */, index }
    ));
    (_j = tracing) == null ? void 0 : _j.pop();
    automaticTypeDirectiveNames ?? (automaticTypeDirectiveNames = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray);
    automaticTypeDirectiveResolutions = createModeAwareCache();
    if (automaticTypeDirectiveNames.length) {
      (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length });
      const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory;
      const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile);
      const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename);
      for (let i = 0; i < automaticTypeDirectiveNames.length; i++) {
        automaticTypeDirectiveResolutions.set(
          automaticTypeDirectiveNames[i],
          /*mode*/
          void 0,
          resolutions[i]
        );
        processTypeReferenceDirective(
          automaticTypeDirectiveNames[i],
          /*mode*/
          void 0,
          resolutions[i],
          {
            kind: 8 /* AutomaticTypeDirectiveFile */,
            typeReference: automaticTypeDirectiveNames[i],
            packageId: (_m = (_l = resolutions[i]) == null ? void 0 : _l.resolvedTypeReferenceDirective) == null ? void 0 : _m.packageId
          }
        );
      }
      (_n = tracing) == null ? void 0 : _n.pop();
    }
    if (rootNames.length && !skipDefaultLib) {
      const defaultLibraryFileName = getDefaultLibraryFileName();
      if (!options.lib && defaultLibraryFileName) {
        processRootFile(
          defaultLibraryFileName,
          /*isDefaultLib*/
          true,
          /*ignoreNoDefaultLib*/
          false,
          { kind: 6 /* LibFile */ }
        );
      } else {
        forEach(options.lib, (libFileName, index) => {
          processRootFile(
            pathForLibFile(libFileName),
            /*isDefaultLib*/
            true,
            /*ignoreNoDefaultLib*/
            false,
            { kind: 6 /* LibFile */, index }
          );
        });
      }
    }
    missingFilePaths = arrayFrom(mapDefinedIterator(filesByName.entries(), ([path, file]) => file === void 0 ? path : void 0));
    files = stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
    processingDefaultLibFiles = void 0;
    processingOtherFiles = void 0;
  }
  Debug.assert(!!missingFilePaths);
  if (oldProgram && host.onReleaseOldSourceFile) {
    const oldSourceFiles = oldProgram.getSourceFiles();
    for (const oldSourceFile of oldSourceFiles) {
      const newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
      if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is
      oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path) {
        host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
      }
    }
    if (!host.getParsedCommandLine) {
      oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => {
        if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) {
          host.onReleaseOldSourceFile(
            resolvedProjectReference.sourceFile,
            oldProgram.getCompilerOptions(),
            /*hasSourceFileByPath*/
            false
          );
        }
      });
    }
  }
  if (oldProgram && host.onReleaseParsedCommandLine) {
    forEachProjectReference(
      oldProgram.getProjectReferences(),
      oldProgram.getResolvedProjectReferences(),
      (oldResolvedRef, parent2, index) => {
        const oldReference = (parent2 == null ? void 0 : parent2.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index];
        const oldRefPath = resolveProjectReferencePath(oldReference);
        if (!(projectReferenceRedirects == null ? void 0 : projectReferenceRedirects.has(toPath3(oldRefPath)))) {
          host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions());
        }
      }
    );
  }
  oldProgram = void 0;
  resolvedLibProcessing = void 0;
  const program = {
    getRootFileNames: () => rootNames,
    getSourceFile,
    getSourceFileByPath,
    getSourceFiles: () => files,
    getMissingFilePaths: () => missingFilePaths,
    // TODO: GH#18217
    getModuleResolutionCache: () => moduleResolutionCache,
    getFilesByNameMap: () => filesByName,
    getCompilerOptions: () => options,
    getSyntacticDiagnostics,
    getOptionsDiagnostics,
    getGlobalDiagnostics,
    getSemanticDiagnostics,
    getCachedSemanticDiagnostics,
    getSuggestionDiagnostics,
    getDeclarationDiagnostics: getDeclarationDiagnostics2,
    getBindAndCheckDiagnostics,
    getProgramDiagnostics,
    getTypeChecker,
    getClassifiableNames,
    getCommonSourceDirectory: getCommonSourceDirectory2,
    emit,
    getCurrentDirectory: () => currentDirectory,
    getNodeCount: () => getTypeChecker().getNodeCount(),
    getIdentifierCount: () => getTypeChecker().getIdentifierCount(),
    getSymbolCount: () => getTypeChecker().getSymbolCount(),
    getTypeCount: () => getTypeChecker().getTypeCount(),
    getInstantiationCount: () => getTypeChecker().getInstantiationCount(),
    getRelationCacheSizes: () => getTypeChecker().getRelationCacheSizes(),
    getFileProcessingDiagnostics: () => fileProcessingDiagnostics,
    getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives,
    getAutomaticTypeDirectiveNames: () => automaticTypeDirectiveNames,
    getAutomaticTypeDirectiveResolutions: () => automaticTypeDirectiveResolutions,
    isSourceFileFromExternalLibrary,
    isSourceFileDefaultLibrary,
    getSourceFileFromReference,
    getLibFileFromReference,
    sourceFileToPackageName,
    redirectTargetsMap,
    usesUriStyleNodeCoreModules,
    resolvedLibReferences,
    getCurrentPackagesMap: () => packageMap,
    typesPackageExists,
    packageBundlesTypes,
    isEmittedFile,
    getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2,
    getProjectReferences,
    getResolvedProjectReferences,
    getProjectReferenceRedirect,
    getResolvedProjectReferenceToRedirect,
    getResolvedProjectReferenceByPath,
    forEachResolvedProjectReference: forEachResolvedProjectReference2,
    isSourceOfProjectReferenceRedirect,
    emitBuildInfo,
    fileExists,
    readFile,
    directoryExists,
    getSymlinkCache,
    realpath: (_o = host.realpath) == null ? void 0 : _o.bind(host),
    useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
    getCanonicalFileName,
    getFileIncludeReasons: () => fileReasons,
    structureIsReused,
    writeFile: writeFile2
  };
  onProgramCreateComplete();
  fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => {
    switch (diagnostic.kind) {
      case 1 /* FilePreprocessingFileExplainingDiagnostic */:
        return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || emptyArray));
      case 0 /* FilePreprocessingReferencedDiagnostic */:
        const { file, pos, end } = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason);
        return programDiagnostics.add(createFileDiagnostic(file, Debug.checkDefined(pos), Debug.checkDefined(end) - pos, diagnostic.diagnostic, ...diagnostic.args || emptyArray));
      case 2 /* ResolutionDiagnostics */:
        return diagnostic.diagnostics.forEach((d) => programDiagnostics.add(d));
      default:
        Debug.assertNever(diagnostic);
    }
  });
  verifyCompilerOptions();
  mark("afterProgram");
  measure("Program", "beforeProgram", "afterProgram");
  (_p = tracing) == null ? void 0 : _p.pop();
  return program;
  function getPackagesMap() {
    if (packageMap)
      return packageMap;
    packageMap = /* @__PURE__ */ new Map();
    files.forEach((sf) => {
      if (!sf.resolvedModules)
        return;
      sf.resolvedModules.forEach(({ resolvedModule }) => {
        if (resolvedModule == null ? void 0 : resolvedModule.packageId)
          packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name));
      });
    });
    return packageMap;
  }
  function typesPackageExists(packageName) {
    return getPackagesMap().has(getTypesPackageName(packageName));
  }
  function packageBundlesTypes(packageName) {
    return !!getPackagesMap().get(packageName);
  }
  function addResolutionDiagnostics(resolution) {
    var _a2;
    if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length))
      return;
    (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({
      kind: 2 /* ResolutionDiagnostics */,
      diagnostics: resolution.resolutionDiagnostics
    });
  }
  function addResolutionDiagnosticsFromResolutionOrCache(containingFile, name, resolution, mode) {
    if (host.resolveModuleNameLiterals || !host.resolveModuleNames)
      return addResolutionDiagnostics(resolution);
    if (!moduleResolutionCache || isExternalModuleNameRelative(name))
      return;
    const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
    const containingDir = getDirectoryPath(containingFileName);
    const redirectedReference = getRedirectReferenceForResolution(containingFile);
    const fromCache = moduleResolutionCache.getFromNonRelativeNameCache(name, mode, containingDir, redirectedReference);
    if (fromCache)
      addResolutionDiagnostics(fromCache);
  }
  function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) {
    var _a2, _b2;
    if (!moduleNames.length)
      return emptyArray;
    const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
    const redirectedReference = getRedirectReferenceForResolution(containingFile);
    (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName });
    mark("beforeResolveModule");
    const result = actualResolveModuleNamesWorker(moduleNames, containingFileName, redirectedReference, options, containingFile, reusedNames);
    mark("afterResolveModule");
    measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
    (_b2 = tracing) == null ? void 0 : _b2.pop();
    return result;
  }
  function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, reusedNames) {
    var _a2, _b2;
    if (!typeDirectiveNames.length)
      return [];
    const containingSourceFile = !isString(containingFile) ? containingFile : void 0;
    const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
    const redirectedReference = containingSourceFile && getRedirectReferenceForResolution(containingSourceFile);
    (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName });
    mark("beforeResolveTypeReference");
    const result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference, options, containingSourceFile, reusedNames);
    mark("afterResolveTypeReference");
    measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
    (_b2 = tracing) == null ? void 0 : _b2.pop();
    return result;
  }
  function getRedirectReferenceForResolution(file) {
    const redirect = getResolvedProjectReferenceToRedirect(file.originalFileName);
    if (redirect || !isDeclarationFileName(file.originalFileName))
      return redirect;
    const resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.path);
    if (resultFromDts)
      return resultFromDts;
    if (!host.realpath || !options.preserveSymlinks || !stringContains(file.originalFileName, nodeModulesPathPart))
      return void 0;
    const realDeclarationPath = toPath3(host.realpath(file.originalFileName));
    return realDeclarationPath === file.path ? void 0 : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath);
  }
  function getRedirectReferenceForResolutionFromSourceOfProject(filePath) {
    const source = getSourceOfProjectReferenceRedirect(filePath);
    if (isString(source))
      return getResolvedProjectReferenceToRedirect(source);
    if (!source)
      return void 0;
    return forEachResolvedProjectReference2((resolvedRef) => {
      const out = outFile(resolvedRef.commandLine.options);
      if (!out)
        return void 0;
      return toPath3(out) === filePath ? resolvedRef : void 0;
    });
  }
  function compareDefaultLibFiles(a, b) {
    return compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
  }
  function getDefaultLibFilePriority(a) {
    if (containsPath(
      defaultLibraryPath,
      a.fileName,
      /*ignoreCase*/
      false
    )) {
      const basename = getBaseFileName(a.fileName);
      if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
        return 0;
      const name = removeSuffix(removePrefix(basename, "lib."), ".d.ts");
      const index = libs.indexOf(name);
      if (index !== -1)
        return index + 1;
    }
    return libs.length + 2;
  }
  function toPath3(fileName) {
    return toPath(fileName, currentDirectory, getCanonicalFileName);
  }
  function getCommonSourceDirectory2() {
    if (commonSourceDirectory === void 0) {
      const emittedFiles = filter(files, (file) => sourceFileMayBeEmitted(file, program));
      commonSourceDirectory = getCommonSourceDirectory(
        options,
        () => mapDefined(emittedFiles, (file) => file.isDeclarationFile ? void 0 : file.fileName),
        currentDirectory,
        getCanonicalFileName,
        (commonSourceDirectory2) => checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory2)
      );
    }
    return commonSourceDirectory;
  }
  function getClassifiableNames() {
    var _a2;
    if (!classifiableNames) {
      getTypeChecker();
      classifiableNames = /* @__PURE__ */ new Set();
      for (const sourceFile of files) {
        (_a2 = sourceFile.classifiableNames) == null ? void 0 : _a2.forEach((value) => classifiableNames.add(value));
      }
    }
    return classifiableNames;
  }
  function resolveModuleNamesReusingOldState(moduleNames, file) {
    var _a2;
    if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
      return resolveModuleNamesWorker(
        moduleNames,
        file,
        /*reusedNames*/
        void 0
      );
    }
    const oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName);
    if (oldSourceFile !== file && file.resolvedModules) {
      const result2 = [];
      for (const moduleName of moduleNames) {
        const resolvedModule = file.resolvedModules.get(moduleName.text, getModeForUsageLocation(file, moduleName));
        result2.push(resolvedModule);
      }
      return result2;
    }
    let unknownModuleNames;
    let result;
    let reusedNames;
    const predictedToResolveToAmbientModuleMarker = emptyResolution;
    for (let i = 0; i < moduleNames.length; i++) {
      const moduleName = moduleNames[i];
      if (file === oldSourceFile && !hasInvalidatedResolutions(oldSourceFile.path)) {
        const mode = getModeForUsageLocation(file, moduleName);
        const oldResolution = (_a2 = oldSourceFile.resolvedModules) == null ? void 0 : _a2.get(moduleName.text, mode);
        if (oldResolution == null ? void 0 : oldResolution.resolvedModule) {
          if (isTraceEnabled(options, host)) {
            trace(
              host,
              oldResolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2,
              moduleName.text,
              getNormalizedAbsolutePath(file.originalFileName, currentDirectory),
              oldResolution.resolvedModule.resolvedFileName,
              oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId)
            );
          }
          (result ?? (result = new Array(moduleNames.length)))[i] = oldResolution;
          (reusedNames ?? (reusedNames = [])).push(moduleName);
          continue;
        }
      }
      let resolvesToAmbientModuleInNonModifiedFile = false;
      if (contains(file.ambientModuleNames, moduleName.text)) {
        resolvesToAmbientModuleInNonModifiedFile = true;
        if (isTraceEnabled(options, host)) {
          trace(host, Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName.text, getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
        }
      } else {
        resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
      }
      if (resolvesToAmbientModuleInNonModifiedFile) {
        (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
      } else {
        (unknownModuleNames ?? (unknownModuleNames = [])).push(moduleName);
      }
    }
    const resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames) : emptyArray;
    if (!result) {
      Debug.assert(resolutions.length === moduleNames.length);
      return resolutions;
    }
    let j = 0;
    for (let i = 0; i < result.length; i++) {
      if (!result[i]) {
        result[i] = resolutions[j];
        j++;
      }
    }
    Debug.assert(j === resolutions.length);
    return result;
    function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
      const resolutionToFile = getResolvedModule(oldSourceFile, moduleName.text, getModeForUsageLocation(file, moduleName));
      const resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
      if (resolutionToFile && resolvedFile) {
        return false;
      }
      const unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName.text);
      if (!unmodifiedFile) {
        return false;
      }
      if (isTraceEnabled(options, host)) {
        trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName.text, unmodifiedFile);
      }
      return true;
    }
  }
  function resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectiveNames, containingFile) {
    var _a2;
    if (structureIsReused === 0 /* Not */) {
      return resolveTypeReferenceDirectiveNamesWorker(
        typeDirectiveNames,
        containingFile,
        /*reusedNames*/
        void 0
      );
    }
    const oldSourceFile = !isString(containingFile) ? oldProgram && oldProgram.getSourceFile(containingFile.fileName) : void 0;
    if (!isString(containingFile)) {
      if (oldSourceFile !== containingFile && containingFile.resolvedTypeReferenceDirectiveNames) {
        const result2 = [];
        for (const typeDirectiveName of typeDirectiveNames) {
          const resolvedTypeReferenceDirective = containingFile.resolvedTypeReferenceDirectiveNames.get(getTypeReferenceResolutionName(typeDirectiveName), getModeForFileReference(typeDirectiveName, containingFile.impliedNodeFormat));
          result2.push(resolvedTypeReferenceDirective);
        }
        return result2;
      }
    }
    let unknownTypeReferenceDirectiveNames;
    let result;
    let reusedNames;
    const containingSourceFile = !isString(containingFile) ? containingFile : void 0;
    const canReuseResolutions = !isString(containingFile) ? containingFile === oldSourceFile && !hasInvalidatedResolutions(oldSourceFile.path) : !hasInvalidatedResolutions(toPath3(containingFile));
    for (let i = 0; i < typeDirectiveNames.length; i++) {
      const entry = typeDirectiveNames[i];
      if (canReuseResolutions) {
        const typeDirectiveName = getTypeReferenceResolutionName(entry);
        const mode = getModeForFileReference(entry, containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat);
        const oldResolution = (_a2 = !isString(containingFile) ? oldSourceFile == null ? void 0 : oldSourceFile.resolvedTypeReferenceDirectiveNames : oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(typeDirectiveName, mode);
        if (oldResolution == null ? void 0 : oldResolution.resolvedTypeReferenceDirective) {
          if (isTraceEnabled(options, host)) {
            trace(
              host,
              oldResolution.resolvedTypeReferenceDirective.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2,
              typeDirectiveName,
              !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile,
              oldResolution.resolvedTypeReferenceDirective.resolvedFileName,
              oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId)
            );
          }
          (result ?? (result = new Array(typeDirectiveNames.length)))[i] = oldResolution;
          (reusedNames ?? (reusedNames = [])).push(entry);
          continue;
        }
      }
      (unknownTypeReferenceDirectiveNames ?? (unknownTypeReferenceDirectiveNames = [])).push(entry);
    }
    if (!unknownTypeReferenceDirectiveNames)
      return result || emptyArray;
    const resolutions = resolveTypeReferenceDirectiveNamesWorker(
      unknownTypeReferenceDirectiveNames,
      containingFile,
      reusedNames
    );
    if (!result) {
      Debug.assert(resolutions.length === typeDirectiveNames.length);
      return resolutions;
    }
    let j = 0;
    for (let i = 0; i < result.length; i++) {
      if (!result[i]) {
        result[i] = resolutions[j];
        j++;
      }
    }
    Debug.assert(j === resolutions.length);
    return result;
  }
  function canReuseProjectReferences() {
    return !forEachProjectReference(
      oldProgram.getProjectReferences(),
      oldProgram.getResolvedProjectReferences(),
      (oldResolvedRef, parent2, index) => {
        const newRef = (parent2 ? parent2.commandLine.projectReferences : projectReferences)[index];
        const newResolvedRef = parseProjectReferenceConfigFile(newRef);
        if (oldResolvedRef) {
          return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || !arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames);
        } else {
          return newResolvedRef !== void 0;
        }
      },
      (oldProjectReferences, parent2) => {
        const newReferences = parent2 ? getResolvedProjectReferenceByPath(parent2.sourceFile.path).commandLine.projectReferences : projectReferences;
        return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo);
      }
    );
  }
  function tryReuseStructureFromOldProgram() {
    var _a2;
    if (!oldProgram) {
      return 0 /* Not */;
    }
    const oldOptions = oldProgram.getCompilerOptions();
    if (changesAffectModuleResolution(oldOptions, options)) {
      return 0 /* Not */;
    }
    const oldRootNames = oldProgram.getRootFileNames();
    if (!arrayIsEqualTo(oldRootNames, rootNames)) {
      return 0 /* Not */;
    }
    if (!canReuseProjectReferences()) {
      return 0 /* Not */;
    }
    if (projectReferences) {
      resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
    }
    const newSourceFiles = [];
    const modifiedSourceFiles = [];
    structureIsReused = 2 /* Completely */;
    if (oldProgram.getMissingFilePaths().some((missingFilePath) => host.fileExists(missingFilePath))) {
      return 0 /* Not */;
    }
    const oldSourceFiles = oldProgram.getSourceFiles();
    let SeenPackageName;
    ((SeenPackageName2) => {
      SeenPackageName2[SeenPackageName2["Exists"] = 0] = "Exists";
      SeenPackageName2[SeenPackageName2["Modified"] = 1] = "Modified";
    })(SeenPackageName || (SeenPackageName = {}));
    const seenPackageNames = /* @__PURE__ */ new Map();
    for (const oldSourceFile of oldSourceFiles) {
      const sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options);
      let newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(
        oldSourceFile.fileName,
        oldSourceFile.resolvedPath,
        sourceFileOptions,
        /*onError*/
        void 0,
        shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat
      ) : host.getSourceFile(
        oldSourceFile.fileName,
        sourceFileOptions,
        /*onError*/
        void 0,
        shouldCreateNewSourceFile || sourceFileOptions.impliedNodeFormat !== oldSourceFile.impliedNodeFormat
      );
      if (!newSourceFile) {
        return 0 /* Not */;
      }
      newSourceFile.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0;
      newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope;
      Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
      let fileChanged;
      if (oldSourceFile.redirectInfo) {
        if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
          return 0 /* Not */;
        }
        fileChanged = false;
        newSourceFile = oldSourceFile;
      } else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
        if (newSourceFile !== oldSourceFile) {
          return 0 /* Not */;
        }
        fileChanged = false;
      } else {
        fileChanged = newSourceFile !== oldSourceFile;
      }
      newSourceFile.path = oldSourceFile.path;
      newSourceFile.originalFileName = oldSourceFile.originalFileName;
      newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
      newSourceFile.fileName = oldSourceFile.fileName;
      const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
      if (packageName !== void 0) {
        const prevKind = seenPackageNames.get(packageName);
        const newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
        if (prevKind !== void 0 && newKind === 1 /* Modified */ || prevKind === 1 /* Modified */) {
          return 0 /* Not */;
        }
        seenPackageNames.set(packageName, newKind);
      }
      if (fileChanged) {
        if (oldSourceFile.impliedNodeFormat !== newSourceFile.impliedNodeFormat) {
          structureIsReused = 1 /* SafeModules */;
        } else if (!arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
          structureIsReused = 1 /* SafeModules */;
        } else if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
          structureIsReused = 1 /* SafeModules */;
        } else if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
          structureIsReused = 1 /* SafeModules */;
        } else {
          collectExternalModuleReferences(newSourceFile);
          if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
            structureIsReused = 1 /* SafeModules */;
          } else if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
            structureIsReused = 1 /* SafeModules */;
          } else if ((oldSourceFile.flags & 6291456 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 6291456 /* PermanentlySetIncrementalFlags */)) {
            structureIsReused = 1 /* SafeModules */;
          } else if (!arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
            structureIsReused = 1 /* SafeModules */;
          }
        }
        modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
      } else if (hasInvalidatedResolutions(oldSourceFile.path)) {
        structureIsReused = 1 /* SafeModules */;
        modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
      }
      newSourceFiles.push(newSourceFile);
    }
    if (structureIsReused !== 2 /* Completely */) {
      return structureIsReused;
    }
    const modifiedFiles = modifiedSourceFiles.map((f) => f.oldFile);
    for (const oldFile of oldSourceFiles) {
      if (!contains(modifiedFiles, oldFile)) {
        for (const moduleName of oldFile.ambientModuleNames) {
          ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
        }
      }
    }
    for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) {
      const moduleNames = getModuleNames(newSourceFile);
      const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile);
      const resolutionsChanged = hasChangesInResolutions(moduleNames, newSourceFile, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo, moduleResolutionNameAndModeGetter);
      if (resolutionsChanged) {
        structureIsReused = 1 /* SafeModules */;
        newSourceFile.resolvedModules = zipToModeAwareCache(newSourceFile, moduleNames, resolutions, moduleResolutionNameAndModeGetter);
      } else {
        newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
      }
      const typesReferenceDirectives = newSourceFile.typeReferenceDirectives;
      const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typesReferenceDirectives, newSourceFile);
      const typeReferenceResolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, newSourceFile, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo, typeReferenceResolutionNameAndModeGetter);
      if (typeReferenceResolutionsChanged) {
        structureIsReused = 1 /* SafeModules */;
        newSourceFile.resolvedTypeReferenceDirectiveNames = zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions, typeReferenceResolutionNameAndModeGetter);
      } else {
        newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
      }
    }
    if (structureIsReused !== 2 /* Completely */) {
      return structureIsReused;
    }
    if (changesAffectingProgramStructure(oldOptions, options)) {
      return 1 /* SafeModules */;
    }
    if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) {
      return 1 /* SafeModules */;
    }
    if (host.hasChangedAutomaticTypeDirectiveNames) {
      if (host.hasChangedAutomaticTypeDirectiveNames())
        return 1 /* SafeModules */;
    } else {
      automaticTypeDirectiveNames = getAutomaticTypeDirectiveNames(options, host);
      if (!arrayIsEqualTo(oldProgram.getAutomaticTypeDirectiveNames(), automaticTypeDirectiveNames))
        return 1 /* SafeModules */;
    }
    missingFilePaths = oldProgram.getMissingFilePaths();
    Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
    for (const newSourceFile of newSourceFiles) {
      filesByName.set(newSourceFile.path, newSourceFile);
    }
    const oldFilesByNameMap = oldProgram.getFilesByNameMap();
    oldFilesByNameMap.forEach((oldFile, path) => {
      if (!oldFile) {
        filesByName.set(path, oldFile);
        return;
      }
      if (oldFile.path === path) {
        if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
          sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
        }
        return;
      }
      filesByName.set(path, filesByName.get(oldFile.path));
    });
    files = newSourceFiles;
    fileReasons = oldProgram.getFileIncludeReasons();
    fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
    resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
    automaticTypeDirectiveNames = oldProgram.getAutomaticTypeDirectiveNames();
    automaticTypeDirectiveResolutions = oldProgram.getAutomaticTypeDirectiveResolutions();
    sourceFileToPackageName = oldProgram.sourceFileToPackageName;
    redirectTargetsMap = oldProgram.redirectTargetsMap;
    usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules;
    resolvedLibReferences = oldProgram.resolvedLibReferences;
    packageMap = oldProgram.getCurrentPackagesMap();
    return 2 /* Completely */;
  }
  function getEmitHost(writeFileCallback) {
    return {
      getPrependNodes,
      getCanonicalFileName,
      getCommonSourceDirectory: program.getCommonSourceDirectory,
      getCompilerOptions: program.getCompilerOptions,
      getCurrentDirectory: () => currentDirectory,
      getSourceFile: program.getSourceFile,
      getSourceFileByPath: program.getSourceFileByPath,
      getSourceFiles: program.getSourceFiles,
      getLibFileFromReference: program.getLibFileFromReference,
      isSourceFileFromExternalLibrary,
      getResolvedProjectReferenceToRedirect,
      getProjectReferenceRedirect,
      isSourceOfProjectReferenceRedirect,
      getSymlinkCache,
      writeFile: writeFileCallback || writeFile2,
      isEmitBlocked,
      readFile: (f) => host.readFile(f),
      fileExists: (f) => {
        const path = toPath3(f);
        if (getSourceFileByPath(path))
          return true;
        if (contains(missingFilePaths, path))
          return false;
        return host.fileExists(f);
      },
      useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
      getBuildInfo: (bundle) => {
        var _a2;
        return (_a2 = program.getBuildInfo) == null ? void 0 : _a2.call(program, bundle);
      },
      getSourceFileFromReference: (file, ref) => program.getSourceFileFromReference(file, ref),
      redirectTargetsMap,
      getFileIncludeReasons: program.getFileIncludeReasons,
      createHash: maybeBind(host, host.createHash)
    };
  }
  function writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data) {
    host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
  }
  function emitBuildInfo(writeFileCallback) {
    var _a2, _b2;
    Debug.assert(!outFile(options));
    (_a2 = tracing) == null ? void 0 : _a2.push(
      tracing.Phase.Emit,
      "emitBuildInfo",
      {},
      /*separateBeginAndEnd*/
      true
    );
    mark("beforeEmit");
    const emitResult = emitFiles(
      notImplementedResolver,
      getEmitHost(writeFileCallback),
      /*targetSourceFile*/
      void 0,
      /*transformers*/
      noTransformers,
      /*emitOnly*/
      false,
      /*onlyBuildInfo*/
      true
    );
    mark("afterEmit");
    measure("Emit", "beforeEmit", "afterEmit");
    (_b2 = tracing) == null ? void 0 : _b2.pop();
    return emitResult;
  }
  function getResolvedProjectReferences() {
    return resolvedProjectReferences;
  }
  function getProjectReferences() {
    return projectReferences;
  }
  function getPrependNodes() {
    return createPrependNodes(
      projectReferences,
      (_ref, index) => {
        var _a2;
        return (_a2 = resolvedProjectReferences[index]) == null ? void 0 : _a2.commandLine;
      },
      (fileName) => {
        const path = toPath3(fileName);
        const sourceFile = getSourceFileByPath(path);
        return sourceFile ? sourceFile.text : filesByName.has(path) ? void 0 : host.readFile(path);
      },
      host
    );
  }
  function isSourceFileFromExternalLibrary(file) {
    return !!sourceFilesFoundSearchingNodeModules.get(file.path);
  }
  function isSourceFileDefaultLibrary(file) {
    if (!file.isDeclarationFile) {
      return false;
    }
    if (file.hasNoDefaultLib) {
      return true;
    }
    if (!options.noLib) {
      return false;
    }
    const equalityComparer = host.useCaseSensitiveFileNames() ? equateStringsCaseSensitive : equateStringsCaseInsensitive;
    if (!options.lib) {
      return equalityComparer(file.fileName, getDefaultLibraryFileName());
    } else {
      return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual));
    }
  }
  function getTypeChecker() {
    return typeChecker || (typeChecker = createTypeChecker(program));
  }
  function emit(sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit) {
    var _a2, _b2;
    (_a2 = tracing) == null ? void 0 : _a2.push(
      tracing.Phase.Emit,
      "emit",
      { path: sourceFile == null ? void 0 : sourceFile.path },
      /*separateBeginAndEnd*/
      true
    );
    const result = runWithCancellationToken(() => emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit));
    (_b2 = tracing) == null ? void 0 : _b2.pop();
    return result;
  }
  function isEmitBlocked(emitFileName) {
    return hasEmitBlockingDiagnostics.has(toPath3(emitFileName));
  }
  function emitWorker(program2, sourceFile, writeFileCallback, cancellationToken, emitOnly, customTransformers, forceDtsEmit) {
    if (!forceDtsEmit) {
      const result = handleNoEmitOptions(program2, sourceFile, writeFileCallback, cancellationToken);
      if (result)
        return result;
    }
    const emitResolver = getTypeChecker().getEmitResolver(outFile(options) ? void 0 : sourceFile, cancellationToken);
    mark("beforeEmit");
    const emitResult = emitFiles(
      emitResolver,
      getEmitHost(writeFileCallback),
      sourceFile,
      getTransformers(options, customTransformers, emitOnly),
      emitOnly,
      /*onlyBuildInfo*/
      false,
      forceDtsEmit
    );
    mark("afterEmit");
    measure("Emit", "beforeEmit", "afterEmit");
    return emitResult;
  }
  function getSourceFile(fileName) {
    return getSourceFileByPath(toPath3(fileName));
  }
  function getSourceFileByPath(path) {
    return filesByName.get(path) || void 0;
  }
  function getDiagnosticsHelper(sourceFile, getDiagnostics2, cancellationToken) {
    if (sourceFile) {
      return sortAndDeduplicateDiagnostics(getDiagnostics2(sourceFile, cancellationToken));
    }
    return sortAndDeduplicateDiagnostics(flatMap(program.getSourceFiles(), (sourceFile2) => {
      if (cancellationToken) {
        cancellationToken.throwIfCancellationRequested();
      }
      return getDiagnostics2(sourceFile2, cancellationToken);
    }));
  }
  function getSyntacticDiagnostics(sourceFile, cancellationToken) {
    return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
  }
  function getSemanticDiagnostics(sourceFile, cancellationToken) {
    return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
  }
  function getCachedSemanticDiagnostics(sourceFile) {
    var _a2;
    return sourceFile ? (_a2 = cachedBindAndCheckDiagnosticsForFile.perFile) == null ? void 0 : _a2.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
  }
  function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
    return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
  }
  function getProgramDiagnostics(sourceFile) {
    var _a2;
    if (skipTypeChecking(sourceFile, options, program)) {
      return emptyArray;
    }
    const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
    if (!((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) {
      return programDiagnosticsInFile;
    }
    return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics;
  }
  function getDeclarationDiagnostics2(sourceFile, cancellationToken) {
    const options2 = program.getCompilerOptions();
    if (!sourceFile || outFile(options2)) {
      return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
    } else {
      return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
    }
  }
  function getSyntacticDiagnosticsForFile(sourceFile) {
    if (isSourceFileJS(sourceFile)) {
      if (!sourceFile.additionalSyntacticDiagnostics) {
        sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
      }
      return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
    }
    return sourceFile.parseDiagnostics;
  }
  function runWithCancellationToken(func) {
    try {
      return func();
    } catch (e) {
      if (e instanceof OperationCanceledException) {
        typeChecker = void 0;
      }
      throw e;
    }
  }
  function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
    return concatenate(
      filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options),
      getProgramDiagnostics(sourceFile)
    );
  }
  function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
    return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
  }
  function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
    return runWithCancellationToken(() => {
      if (skipTypeChecking(sourceFile, options, program)) {
        return emptyArray;
      }
      const typeChecker2 = getTypeChecker();
      Debug.assert(!!sourceFile.bindDiagnostics);
      const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */;
      const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options);
      const isPlainJs = isPlainJsFile(sourceFile, options.checkJs);
      const isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
      const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */ || isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
      let bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
      let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker2.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
      if (isPlainJs) {
        bindDiagnostics = filter(bindDiagnostics, (d) => plainJSErrors.has(d.code));
        checkDiagnostics = filter(checkDiagnostics, (d) => plainJSErrors.has(d.code));
      }
      return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics && !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : void 0);
    });
  }
  function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, ...allDiagnostics) {
    var _a2;
    const flatDiagnostics = flatten(allDiagnostics);
    if (!includeBindAndCheckDiagnostics || !((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) {
      return flatDiagnostics;
    }
    const { diagnostics, directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics);
    for (const errorExpectation of directives.getUnusedExpectations()) {
      diagnostics.push(createDiagnosticForRange(sourceFile, errorExpectation.range, Diagnostics.Unused_ts_expect_error_directive));
    }
    return diagnostics;
  }
  function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
    const directives = createCommentDirectivesMap(sourceFile, commentDirectives);
    const diagnostics = flatDiagnostics.filter((diagnostic) => markPrecedingCommentDirectiveLine(diagnostic, directives) === -1);
    return { diagnostics, directives };
  }
  function getSuggestionDiagnostics(sourceFile, cancellationToken) {
    return runWithCancellationToken(() => {
      return getTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
    });
  }
  function markPrecedingCommentDirectiveLine(diagnostic, directives) {
    const { file, start: start2 } = diagnostic;
    if (!file) {
      return -1;
    }
    const lineStarts = getLineStarts(file);
    let line = computeLineAndCharacterOfPosition(lineStarts, start2).line - 1;
    while (line >= 0) {
      if (directives.markUsed(line)) {
        return line;
      }
      const lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
      if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
        return -1;
      }
      line--;
    }
    return -1;
  }
  function getJSSyntacticDiagnosticsForFile(sourceFile) {
    return runWithCancellationToken(() => {
      const diagnostics = [];
      walk(sourceFile, sourceFile);
      forEachChildRecursively(sourceFile, walk, walkArray);
      return diagnostics;
      function walk(node, parent2) {
        switch (parent2.kind) {
          case 168 /* Parameter */:
          case 171 /* PropertyDeclaration */:
          case 173 /* MethodDeclaration */:
            if (parent2.questionToken === node) {
              diagnostics.push(createDiagnosticForNode2(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
              return "skip";
            }
          case 172 /* MethodSignature */:
          case 175 /* Constructor */:
          case 176 /* GetAccessor */:
          case 177 /* SetAccessor */:
          case 217 /* FunctionExpression */:
          case 261 /* FunctionDeclaration */:
          case 218 /* ArrowFunction */:
          case 259 /* VariableDeclaration */:
            if (parent2.type === node) {
              diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
              return "skip";
            }
        }
        switch (node.kind) {
          case 272 /* ImportClause */:
            if (node.isTypeOnly) {
              diagnostics.push(createDiagnosticForNode2(parent2, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
              return "skip";
            }
            break;
          case 277 /* ExportDeclaration */:
            if (node.isTypeOnly) {
              diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
              return "skip";
            }
            break;
          case 275 /* ImportSpecifier */:
          case 280 /* ExportSpecifier */:
            if (node.isTypeOnly) {
              diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, isImportSpecifier(node) ? "import...type" : "export...type"));
              return "skip";
            }
            break;
          case 270 /* ImportEqualsDeclaration */:
            diagnostics.push(createDiagnosticForNode2(node, Diagnostics.import_can_only_be_used_in_TypeScript_files));
            return "skip";
          case 276 /* ExportAssignment */:
            if (node.isExportEquals) {
              diagnostics.push(createDiagnosticForNode2(node, Diagnostics.export_can_only_be_used_in_TypeScript_files));
              return "skip";
            }
            break;
          case 297 /* HeritageClause */:
            const heritageClause = node;
            if (heritageClause.token === 119 /* ImplementsKeyword */) {
              diagnostics.push(createDiagnosticForNode2(node, Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
              return "skip";
            }
            break;
          case 263 /* InterfaceDeclaration */:
            const interfaceKeyword = tokenToString(120 /* InterfaceKeyword */);
            Debug.assertIsDefined(interfaceKeyword);
            diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
            return "skip";
          case 266 /* ModuleDeclaration */:
            const moduleKeyword = node.flags & 16 /* Namespace */ ? tokenToString(145 /* NamespaceKeyword */) : tokenToString(144 /* ModuleKeyword */);
            Debug.assertIsDefined(moduleKeyword);
            diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
            return "skip";
          case 264 /* TypeAliasDeclaration */:
            diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
            return "skip";
          case 265 /* EnumDeclaration */:
            const enumKeyword = Debug.checkDefined(tokenToString(94 /* EnumKeyword */));
            diagnostics.push(createDiagnosticForNode2(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
            return "skip";
          case 234 /* NonNullExpression */:
            diagnostics.push(createDiagnosticForNode2(node, Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
            return "skip";
          case 233 /* AsExpression */:
            diagnostics.push(createDiagnosticForNode2(node.type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
            return "skip";
          case 237 /* SatisfiesExpression */:
            diagnostics.push(createDiagnosticForNode2(node.type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files));
            return "skip";
          case 215 /* TypeAssertionExpression */:
            Debug.fail();
        }
      }
      function walkArray(nodes, parent2) {
        if (canHaveIllegalDecorators(parent2)) {
          const decorator = find(parent2.modifiers, isDecorator);
          if (decorator) {
            diagnostics.push(createDiagnosticForNode2(decorator, Diagnostics.Decorators_are_not_valid_here));
          }
        } else if (canHaveDecorators(parent2) && parent2.modifiers) {
          const decoratorIndex = findIndex(parent2.modifiers, isDecorator);
          if (decoratorIndex >= 0) {
            if (isParameter(parent2) && !options.experimentalDecorators) {
              diagnostics.push(createDiagnosticForNode2(parent2.modifiers[decoratorIndex], Diagnostics.Decorators_are_not_valid_here));
            } else if (isClassDeclaration(parent2)) {
              const exportIndex = findIndex(parent2.modifiers, isExportModifier);
              if (exportIndex >= 0) {
                const defaultIndex = findIndex(parent2.modifiers, isDefaultModifier);
                if (decoratorIndex > exportIndex && defaultIndex >= 0 && decoratorIndex < defaultIndex) {
                  diagnostics.push(createDiagnosticForNode2(parent2.modifiers[decoratorIndex], Diagnostics.Decorators_are_not_valid_here));
                } else if (exportIndex >= 0 && decoratorIndex < exportIndex) {
                  const trailingDecoratorIndex = findIndex(parent2.modifiers, isDecorator, exportIndex);
                  if (trailingDecoratorIndex >= 0) {
                    diagnostics.push(addRelatedInfo(
                      createDiagnosticForNode2(parent2.modifiers[trailingDecoratorIndex], Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export),
                      createDiagnosticForNode2(parent2.modifiers[decoratorIndex], Diagnostics.Decorator_used_before_export_here)
                    ));
                  }
                }
              }
            }
          }
        }
        switch (parent2.kind) {
          case 262 /* ClassDeclaration */:
          case 230 /* ClassExpression */:
          case 173 /* MethodDeclaration */:
          case 175 /* Constructor */:
          case 176 /* GetAccessor */:
          case 177 /* SetAccessor */:
          case 217 /* FunctionExpression */:
          case 261 /* FunctionDeclaration */:
          case 218 /* ArrowFunction */:
            if (nodes === parent2.typeParameters) {
              diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
              return "skip";
            }
          case 242 /* VariableStatement */:
            if (nodes === parent2.modifiers) {
              checkModifiers(parent2.modifiers, parent2.kind === 242 /* VariableStatement */);
              return "skip";
            }
            break;
          case 171 /* PropertyDeclaration */:
            if (nodes === parent2.modifiers) {
              for (const modifier of nodes) {
                if (isModifier(modifier) && modifier.kind !== 126 /* StaticKeyword */ && modifier.kind !== 129 /* AccessorKeyword */) {
                  diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind)));
                }
              }
              return "skip";
            }
            break;
          case 168 /* Parameter */:
            if (nodes === parent2.modifiers && some(nodes, isModifier)) {
              diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
              return "skip";
            }
            break;
          case 212 /* CallExpression */:
          case 213 /* NewExpression */:
          case 232 /* ExpressionWithTypeArguments */:
          case 284 /* JsxSelfClosingElement */:
          case 285 /* JsxOpeningElement */:
          case 214 /* TaggedTemplateExpression */:
            if (nodes === parent2.typeArguments) {
              diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
              return "skip";
            }
            break;
        }
      }
      function checkModifiers(modifiers, isConstValid) {
        for (const modifier of modifiers) {
          switch (modifier.kind) {
            case 87 /* ConstKeyword */:
              if (isConstValid) {
                continue;
              }
            case 125 /* PublicKeyword */:
            case 123 /* PrivateKeyword */:
            case 124 /* ProtectedKeyword */:
            case 148 /* ReadonlyKeyword */:
            case 138 /* DeclareKeyword */:
            case 128 /* AbstractKeyword */:
            case 163 /* OverrideKeyword */:
            case 103 /* InKeyword */:
            case 147 /* OutKeyword */:
              diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind)));
              break;
            case 126 /* StaticKeyword */:
            case 95 /* ExportKeyword */:
            case 90 /* DefaultKeyword */:
            case 129 /* AccessorKeyword */:
          }
        }
      }
      function createDiagnosticForNodeArray2(nodes, message, ...args) {
        const start2 = nodes.pos;
        return createFileDiagnostic(sourceFile, start2, nodes.end - start2, message, ...args);
      }
      function createDiagnosticForNode2(node, message, ...args) {
        return createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args);
      }
    });
  }
  function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
    return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
  }
  function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
    return runWithCancellationToken(() => {
      const resolver = getTypeChecker().getEmitResolver(sourceFile, cancellationToken);
      return getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray;
    });
  }
  function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics2) {
    var _a2;
    const cachedResult = sourceFile ? (_a2 = cache.perFile) == null ? void 0 : _a2.get(sourceFile.path) : cache.allDiagnostics;
    if (cachedResult) {
      return cachedResult;
    }
    const result = getDiagnostics2(sourceFile, cancellationToken);
    if (sourceFile) {
      (cache.perFile || (cache.perFile = /* @__PURE__ */ new Map())).set(sourceFile.path, result);
    } else {
      cache.allDiagnostics = result;
    }
    return result;
  }
  function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
    return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
  }
  function getOptionsDiagnostics() {
    return sortAndDeduplicateDiagnostics(concatenate(
      programDiagnostics.getGlobalDiagnostics(),
      getOptionsDiagnosticsOfConfigFile()
    ));
  }
  function getOptionsDiagnosticsOfConfigFile() {
    if (!options.configFile)
      return emptyArray;
    let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
    forEachResolvedProjectReference2((resolvedRef) => {
      diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
    });
    return diagnostics;
  }
  function getGlobalDiagnostics() {
    return rootNames.length ? sortAndDeduplicateDiagnostics(getTypeChecker().getGlobalDiagnostics().slice()) : emptyArray;
  }
  function getConfigFileParsingDiagnostics2() {
    return configFileParsingDiagnostics || emptyArray;
  }
  function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason) {
    processSourceFile(
      normalizePath(fileName),
      isDefaultLib,
      ignoreNoDefaultLib,
      /*packageId*/
      void 0,
      reason
    );
  }
  function fileReferenceIsEqualTo(a, b) {
    return a.fileName === b.fileName;
  }
  function moduleNameIsEqualTo(a, b) {
    return a.kind === 80 /* Identifier */ ? b.kind === 80 /* Identifier */ && a.escapedText === b.escapedText : b.kind === 11 /* StringLiteral */ && a.text === b.text;
  }
  function createSyntheticImport(text, file) {
    const externalHelpersModuleReference = factory.createStringLiteral(text);
    const importDecl = factory.createImportDeclaration(
      /*modifiers*/
      void 0,
      /*importClause*/
      void 0,
      externalHelpersModuleReference,
      /*assertClause*/
      void 0
    );
    addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */);
    setParent(externalHelpersModuleReference, importDecl);
    setParent(importDecl, file);
    externalHelpersModuleReference.flags &= ~8 /* Synthesized */;
    importDecl.flags &= ~8 /* Synthesized */;
    return externalHelpersModuleReference;
  }
  function collectExternalModuleReferences(file) {
    if (file.imports) {
      return;
    }
    const isJavaScriptFile = isSourceFileJS(file);
    const isExternalModuleFile = isExternalModule(file);
    let imports;
    let moduleAugmentations;
    let ambientModules;
    if ((getIsolatedModules(options) || isExternalModuleFile) && !file.isDeclarationFile) {
      if (options.importHelpers) {
        imports = [createSyntheticImport(externalHelpersModuleNameText, file)];
      }
      const jsxImport = getJSXRuntimeImport(getJSXImplicitImportBase(options, file), options);
      if (jsxImport) {
        (imports || (imports = [])).push(createSyntheticImport(jsxImport, file));
      }
    }
    for (const node of file.statements) {
      collectModuleReferences(
        node,
        /*inAmbientModule*/
        false
      );
    }
    const shouldProcessRequires = isJavaScriptFile && shouldResolveJsRequire(options);
    if (file.flags & 2097152 /* PossiblyContainsDynamicImport */ || shouldProcessRequires) {
      collectDynamicImportOrRequireCalls(file);
    }
    file.imports = imports || emptyArray;
    file.moduleAugmentations = moduleAugmentations || emptyArray;
    file.ambientModuleNames = ambientModules || emptyArray;
    return;
    function collectModuleReferences(node, inAmbientModule) {
      if (isAnyImportOrReExport(node)) {
        const moduleNameExpr = getExternalModuleName(node);
        if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !isExternalModuleNameRelative(moduleNameExpr.text))) {
          setParentRecursive(
            node,
            /*incremental*/
            false
          );
          imports = append(imports, moduleNameExpr);
          if (!usesUriStyleNodeCoreModules && currentNodeModulesDepth === 0 && !file.isDeclarationFile) {
            usesUriStyleNodeCoreModules = startsWith(moduleNameExpr.text, "node:");
          }
        }
      } else if (isModuleDeclaration(node)) {
        if (isAmbientModule(node) && (inAmbientModule || hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
          node.name.parent = node;
          const nameText = getTextOfIdentifierOrLiteral(node.name);
          if (isExternalModuleFile || inAmbientModule && !isExternalModuleNameRelative(nameText)) {
            (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
          } else if (!inAmbientModule) {
            if (file.isDeclarationFile) {
              (ambientModules || (ambientModules = [])).push(nameText);
            }
            const body = node.body;
            if (body) {
              for (const statement of body.statements) {
                collectModuleReferences(
                  statement,
                  /*inAmbientModule*/
                  true
                );
              }
            }
          }
        }
      }
    }
    function collectDynamicImportOrRequireCalls(file2) {
      const r = /import|require/g;
      while (r.exec(file2.text) !== null) {
        const node = getNodeAtPosition(file2, r.lastIndex);
        if (shouldProcessRequires && isRequireCall(
          node,
          /*requireStringLiteralLikeArgument*/
          true
        )) {
          setParentRecursive(
            node,
            /*incremental*/
            false
          );
          imports = append(imports, node.arguments[0]);
        } else if (isImportCall(node) && node.arguments.length >= 1 && isStringLiteralLike(node.arguments[0])) {
          setParentRecursive(
            node,
            /*incremental*/
            false
          );
          imports = append(imports, node.arguments[0]);
        } else if (isLiteralImportTypeNode(node)) {
          setParentRecursive(
            node,
            /*incremental*/
            false
          );
          imports = append(imports, node.argument.literal);
        }
      }
    }
    function getNodeAtPosition(sourceFile, position) {
      let current = sourceFile;
      const getContainingChild = (child) => {
        if (child.pos <= position && (position < child.end || position === child.end && child.kind === 1 /* EndOfFileToken */)) {
          return child;
        }
      };
      while (true) {
        const child = isJavaScriptFile && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild);
        if (!child) {
          return current;
        }
        current = child;
      }
    }
  }
  function getLibFileFromReference(ref) {
    var _a2;
    const { libFileName } = getLibFileNameFromLibReference(ref);
    const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual);
    return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0;
  }
  function getSourceFileFromReference(referencingFile, ref) {
    return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile);
  }
  function getSourceFileFromReferenceWorker(fileName, getSourceFile2, fail, reason) {
    if (hasExtension(fileName)) {
      const canonicalFileName = host.getCanonicalFileName(fileName);
      if (!options.allowNonTsExtensions && !forEach(flatten(supportedExtensionsWithJsonIfResolveJsonModule), (extension) => fileExtensionIs(canonicalFileName, extension))) {
        if (fail) {
          if (hasJSFileExtension(canonicalFileName)) {
            fail(Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
          } else {
            fail(Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'");
          }
        }
        return void 0;
      }
      const sourceFile = getSourceFile2(fileName);
      if (fail) {
        if (!sourceFile) {
          const redirect = getProjectReferenceRedirect(fileName);
          if (redirect) {
            fail(Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
          } else {
            fail(Diagnostics.File_0_not_found, fileName);
          }
        } else if (isReferencedFile(reason) && canonicalFileName === host.getCanonicalFileName(getSourceFileByPath(reason.file).fileName)) {
          fail(Diagnostics.A_file_cannot_have_a_reference_to_itself);
        }
      }
      return sourceFile;
    } else {
      const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile2(fileName);
      if (sourceFileNoExtension)
        return sourceFileNoExtension;
      if (fail && options.allowNonTsExtensions) {
        fail(Diagnostics.File_0_not_found, fileName);
        return void 0;
      }
      const sourceFileWithAddedExtension = forEach(supportedExtensions[0], (extension) => getSourceFile2(fileName + extension));
      if (fail && !sourceFileWithAddedExtension)
        fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'");
      return sourceFileWithAddedExtension;
    }
  }
  function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, reason) {
    getSourceFileFromReferenceWorker(
      fileName,
      (fileName2) => findSourceFile(fileName2, isDefaultLib, ignoreNoDefaultLib, reason, packageId),
      // TODO: GH#18217
      (diagnostic, ...args) => addFilePreprocessingFileExplainingDiagnostic(
        /*file*/
        void 0,
        reason,
        diagnostic,
        args
      ),
      reason
    );
  }
  function processProjectReferenceFile(fileName, reason) {
    return processSourceFile(
      fileName,
      /*isDefaultLib*/
      false,
      /*ignoreNoDefaultLib*/
      false,
      /*packageId*/
      void 0,
      reason
    );
  }
  function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason) {
    const hasExistingReasonToReportErrorOn = !isReferencedFile(reason) && some(fileReasons.get(existingFile.path), isReferencedFile);
    if (hasExistingReasonToReportErrorOn) {
      addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, [existingFile.fileName, fileName]);
    } else {
      addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]);
    }
  }
  function createRedirectedSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) {
    var _a2;
    const redirect = parseNodeFactory.createRedirectedSourceFile({ redirectTarget, unredirected });
    redirect.fileName = fileName;
    redirect.path = path;
    redirect.resolvedPath = resolvedPath;
    redirect.originalFileName = originalFileName;
    redirect.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0;
    redirect.packageJsonScope = sourceFileOptions.packageJsonScope;
    sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
    return redirect;
  }
  function findSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
    var _a2, _b2;
    (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "findSourceFile", {
      fileName,
      isDefaultLib: isDefaultLib || void 0,
      fileIncludeKind: FileIncludeKind[reason.kind]
    });
    const result = findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId);
    (_b2 = tracing) == null ? void 0 : _b2.pop();
    return result;
  }
  function getCreateSourceFileOptions(fileName, moduleResolutionCache2, host2, options2) {
    const result = getImpliedNodeFormatForFileWorker(getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache2 == null ? void 0 : moduleResolutionCache2.getPackageJsonInfoCache(), host2, options2);
    const languageVersion = getEmitScriptTarget(options2);
    const setExternalModuleIndicator2 = getSetExternalModuleIndicator(options2);
    return typeof result === "object" ? { ...result, languageVersion, setExternalModuleIndicator: setExternalModuleIndicator2 } : { languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator2 };
  }
  function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
    var _a2, _b2;
    const path = toPath3(fileName);
    if (useSourceOfProjectReferenceRedirect) {
      let source = getSourceOfProjectReferenceRedirect(path);
      if (!source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && stringContains(fileName, nodeModulesPathPart)) {
        const realPath2 = toPath3(host.realpath(fileName));
        if (realPath2 !== path)
          source = getSourceOfProjectReferenceRedirect(realPath2);
      }
      if (source) {
        const file2 = isString(source) ? findSourceFile(source, isDefaultLib, ignoreNoDefaultLib, reason, packageId) : void 0;
        if (file2)
          addFileToFilesByName(
            file2,
            path,
            /*redirectedPath*/
            void 0
          );
        return file2;
      }
    }
    const originalFileName = fileName;
    if (filesByName.has(path)) {
      const file2 = filesByName.get(path);
      addFileIncludeReason(file2 || void 0, reason);
      if (file2 && !(options.forceConsistentCasingInFileNames === false)) {
        const checkedName = file2.fileName;
        const isRedirect = toPath3(checkedName) !== toPath3(fileName);
        if (isRedirect) {
          fileName = getProjectReferenceRedirect(fileName) || fileName;
        }
        const checkedAbsolutePath = getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
        const inputAbsolutePath = getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
        if (checkedAbsolutePath !== inputAbsolutePath) {
          reportFileNamesDifferOnlyInCasingError(fileName, file2, reason);
        }
      }
      if (file2 && sourceFilesFoundSearchingNodeModules.get(file2.path) && currentNodeModulesDepth === 0) {
        sourceFilesFoundSearchingNodeModules.set(file2.path, false);
        if (!options.noResolve) {
          processReferencedFiles(file2, isDefaultLib);
          processTypeReferenceDirectives(file2);
        }
        if (!options.noLib) {
          processLibReferenceDirectives(file2);
        }
        modulesWithElidedImports.set(file2.path, false);
        processImportedModules(file2);
      } else if (file2 && modulesWithElidedImports.get(file2.path)) {
        if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
          modulesWithElidedImports.set(file2.path, false);
          processImportedModules(file2);
        }
      }
      return file2 || void 0;
    }
    let redirectedPath;
    if (isReferencedFile(reason) && !useSourceOfProjectReferenceRedirect) {
      const redirectProject = getProjectReferenceRedirectProject(fileName);
      if (redirectProject) {
        if (outFile(redirectProject.commandLine.options)) {
          return void 0;
        }
        const redirect = getProjectReferenceOutputName(redirectProject, fileName);
        fileName = redirect;
        redirectedPath = toPath3(redirect);
      }
    }
    const sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options);
    const file = host.getSourceFile(
      fileName,
      sourceFileOptions,
      (hostErrorMessage) => addFilePreprocessingFileExplainingDiagnostic(
        /*file*/
        void 0,
        reason,
        Diagnostics.Cannot_read_file_0_Colon_1,
        [fileName, hostErrorMessage]
      ),
      shouldCreateNewSourceFile || ((_a2 = oldProgram == null ? void 0 : oldProgram.getSourceFileByPath(toPath3(fileName))) == null ? void 0 : _a2.impliedNodeFormat) !== sourceFileOptions.impliedNodeFormat
    );
    if (packageId) {
      const packageIdKey = packageIdToString(packageId);
      const fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
      if (fileFromPackageId) {
        const dupFile = createRedirectedSourceFile(fileFromPackageId, file, fileName, path, toPath3(fileName), originalFileName, sourceFileOptions);
        redirectTargetsMap.add(fileFromPackageId.path, fileName);
        addFileToFilesByName(dupFile, path, redirectedPath);
        addFileIncludeReason(dupFile, reason);
        sourceFileToPackageName.set(path, packageIdToPackageName(packageId));
        processingOtherFiles.push(dupFile);
        return dupFile;
      } else if (file) {
        packageIdToSourceFile.set(packageIdKey, file);
        sourceFileToPackageName.set(path, packageIdToPackageName(packageId));
      }
    }
    addFileToFilesByName(file, path, redirectedPath);
    if (file) {
      sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
      file.fileName = fileName;
      file.path = path;
      file.resolvedPath = toPath3(fileName);
      file.originalFileName = originalFileName;
      file.packageJsonLocations = ((_b2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _b2.length) ? sourceFileOptions.packageJsonLocations : void 0;
      file.packageJsonScope = sourceFileOptions.packageJsonScope;
      addFileIncludeReason(file, reason);
      if (host.useCaseSensitiveFileNames()) {
        const pathLowerCase = toFileNameLowerCase(path);
        const existingFile = filesByNameIgnoreCase.get(pathLowerCase);
        if (existingFile) {
          reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason);
        } else {
          filesByNameIgnoreCase.set(pathLowerCase, file);
        }
      }
      skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib && !ignoreNoDefaultLib;
      if (!options.noResolve) {
        processReferencedFiles(file, isDefaultLib);
        processTypeReferenceDirectives(file);
      }
      if (!options.noLib) {
        processLibReferenceDirectives(file);
      }
      processImportedModules(file);
      if (isDefaultLib) {
        processingDefaultLibFiles.push(file);
      } else {
        processingOtherFiles.push(file);
      }
    }
    return file;
  }
  function addFileIncludeReason(file, reason) {
    if (file)
      fileReasons.add(file.path, reason);
  }
  function addFileToFilesByName(file, path, redirectedPath) {
    if (redirectedPath) {
      filesByName.set(redirectedPath, file);
      filesByName.set(path, file || false);
    } else {
      filesByName.set(path, file);
    }
  }
  function getProjectReferenceRedirect(fileName) {
    const referencedProject = getProjectReferenceRedirectProject(fileName);
    return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
  }
  function getProjectReferenceRedirectProject(fileName) {
    if (!resolvedProjectReferences || !resolvedProjectReferences.length || isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".json" /* Json */)) {
      return void 0;
    }
    return getResolvedProjectReferenceToRedirect(fileName);
  }
  function getProjectReferenceOutputName(referencedProject, fileName) {
    const out = outFile(referencedProject.commandLine.options);
    return out ? changeExtension(out, ".d.ts" /* Dts */) : getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
  }
  function getResolvedProjectReferenceToRedirect(fileName) {
    if (mapFromFileToProjectReferenceRedirects === void 0) {
      mapFromFileToProjectReferenceRedirects = /* @__PURE__ */ new Map();
      forEachResolvedProjectReference2((referencedProject) => {
        if (toPath3(options.configFilePath) !== referencedProject.sourceFile.path) {
          referencedProject.commandLine.fileNames.forEach((f) => mapFromFileToProjectReferenceRedirects.set(toPath3(f), referencedProject.sourceFile.path));
        }
      });
    }
    const referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath3(fileName));
    return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
  }
  function forEachResolvedProjectReference2(cb) {
    return forEachResolvedProjectReference(resolvedProjectReferences, cb);
  }
  function getSourceOfProjectReferenceRedirect(path) {
    if (!isDeclarationFileName(path))
      return void 0;
    if (mapFromToProjectReferenceRedirectSource === void 0) {
      mapFromToProjectReferenceRedirectSource = /* @__PURE__ */ new Map();
      forEachResolvedProjectReference2((resolvedRef) => {
        const out = outFile(resolvedRef.commandLine.options);
        if (out) {
          const outputDts = changeExtension(out, ".d.ts" /* Dts */);
          mapFromToProjectReferenceRedirectSource.set(toPath3(outputDts), true);
        } else {
          const getCommonSourceDirectory3 = memoize(() => getCommonSourceDirectoryOfConfig(resolvedRef.commandLine, !host.useCaseSensitiveFileNames()));
          forEach(resolvedRef.commandLine.fileNames, (fileName) => {
            if (!isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */)) {
              const outputDts = getOutputDeclarationFileName(fileName, resolvedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3);
              mapFromToProjectReferenceRedirectSource.set(toPath3(outputDts), fileName);
            }
          });
        }
      });
    }
    return mapFromToProjectReferenceRedirectSource.get(path);
  }
  function isSourceOfProjectReferenceRedirect(fileName) {
    return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
  }
  function getResolvedProjectReferenceByPath(projectReferencePath) {
    if (!projectReferenceRedirects) {
      return void 0;
    }
    return projectReferenceRedirects.get(projectReferencePath) || void 0;
  }
  function processReferencedFiles(file, isDefaultLib) {
    forEach(file.referencedFiles, (ref, index) => {
      processSourceFile(
        resolveTripleslashReference(ref.fileName, file.fileName),
        isDefaultLib,
        /*ignoreNoDefaultLib*/
        false,
        /*packageId*/
        void 0,
        { kind: 4 /* ReferenceFile */, file: file.path, index }
      );
    });
  }
  function processTypeReferenceDirectives(file) {
    const typeDirectives = file.typeReferenceDirectives;
    if (!typeDirectives.length) {
      file.resolvedTypeReferenceDirectiveNames = void 0;
      return;
    }
    const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectives, file);
    for (let index = 0; index < typeDirectives.length; index++) {
      const ref = file.typeReferenceDirectives[index];
      const resolvedTypeReferenceDirective = resolutions[index];
      const fileName = toFileNameLowerCase(ref.fileName);
      setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective, getModeForFileReference(ref, file.impliedNodeFormat));
      const mode = ref.resolutionMode || file.impliedNodeFormat;
      if (mode && getEmitModuleResolutionKind(options) !== 3 /* Node16 */ && getEmitModuleResolutionKind(options) !== 99 /* NodeNext */) {
        (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({
          kind: 2 /* ResolutionDiagnostics */,
          diagnostics: [
            createDiagnosticForRange(file, ref, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext)
          ]
        });
      }
      processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index });
    }
  }
  function processTypeReferenceDirective(typeReferenceDirective, mode, resolution, reason) {
    var _a2, _b2;
    (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolution.resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : void 0 });
    processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason);
    (_b2 = tracing) == null ? void 0 : _b2.pop();
  }
  function processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason) {
    var _a2;
    addResolutionDiagnostics(resolution);
    const previousResolution = (_a2 = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode)) == null ? void 0 : _a2.resolvedTypeReferenceDirective;
    if (previousResolution && previousResolution.primary) {
      return;
    }
    let saveResolution = true;
    const { resolvedTypeReferenceDirective } = resolution;
    if (resolvedTypeReferenceDirective) {
      if (resolvedTypeReferenceDirective.isExternalLibraryImport)
        currentNodeModulesDepth++;
      if (resolvedTypeReferenceDirective.primary) {
        processSourceFile(
          resolvedTypeReferenceDirective.resolvedFileName,
          /*isDefaultLib*/
          false,
          /*ignoreNoDefaultLib*/
          false,
          resolvedTypeReferenceDirective.packageId,
          reason
        );
      } else {
        if (previousResolution) {
          if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
            const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
            const existingFile = getSourceFile(previousResolution.resolvedFileName);
            if (otherFileText !== existingFile.text) {
              addFilePreprocessingFileExplainingDiagnostic(
                existingFile,
                reason,
                Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict,
                [typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName]
              );
            }
          }
          saveResolution = false;
        } else {
          processSourceFile(
            resolvedTypeReferenceDirective.resolvedFileName,
            /*isDefaultLib*/
            false,
            /*ignoreNoDefaultLib*/
            false,
            resolvedTypeReferenceDirective.packageId,
            reason
          );
        }
      }
      if (resolvedTypeReferenceDirective.isExternalLibraryImport)
        currentNodeModulesDepth--;
    } else {
      addFilePreprocessingFileExplainingDiagnostic(
        /*file*/
        void 0,
        reason,
        Diagnostics.Cannot_find_type_definition_file_for_0,
        [typeReferenceDirective]
      );
    }
    if (saveResolution) {
      resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolution);
    }
  }
  function pathForLibFile(libFileName) {
    const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName);
    if (existing)
      return existing.actual;
    const result = pathForLibFileWorker(libFileName);
    (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result);
    return result.actual;
  }
  function pathForLibFileWorker(libFileName) {
    var _a2, _b2, _c2, _d2, _e2;
    const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName);
    if (existing)
      return existing;
    if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) {
      const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName);
      if (oldResolution) {
        if (oldResolution.resolution && isTraceEnabled(options, host)) {
          const libraryName2 = getLibraryNameFromLibFileName(libFileName);
          const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName);
          trace(
            host,
            oldResolution.resolution.resolvedModule ? oldResolution.resolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved,
            libraryName2,
            getNormalizedAbsolutePath(resolveFrom2, currentDirectory),
            (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName,
            ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId)
          );
        }
        (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution);
        return oldResolution;
      }
    }
    const libraryName = getLibraryNameFromLibFileName(libFileName);
    const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName);
    (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom });
    mark("beforeResolveLibrary");
    const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName);
    mark("afterResolveLibrary");
    measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary");
    (_e2 = tracing) == null ? void 0 : _e2.pop();
    const result = {
      resolution,
      actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName)
    };
    (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result);
    return result;
  }
  function processLibReferenceDirectives(file) {
    forEach(file.libReferenceDirectives, (libReference, index) => {
      const { libName, libFileName } = getLibFileNameFromLibReference(libReference);
      if (libFileName) {
        processRootFile(
          pathForLibFile(libFileName),
          /*isDefaultLib*/
          true,
          /*ignoreNoDefaultLib*/
          true,
          { kind: 7 /* LibReferenceDirective */, file: file.path, index }
        );
      } else {
        const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts");
        const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity);
        const diagnostic = suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0;
        const args = suggestion ? [libName, suggestion] : [libName];
        (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
          kind: 0 /* FilePreprocessingReferencedDiagnostic */,
          reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index },
          diagnostic,
          args
        });
      }
    });
  }
  function getCanonicalFileName(fileName) {
    return host.getCanonicalFileName(fileName);
  }
  function processImportedModules(file) {
    var _a2;
    collectExternalModuleReferences(file);
    if (file.imports.length || file.moduleAugmentations.length) {
      const moduleNames = getModuleNames(file);
      const resolutions = resolveModuleNamesReusingOldState(moduleNames, file);
      Debug.assert(resolutions.length === moduleNames.length);
      const optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options : void 0) || options;
      for (let index = 0; index < moduleNames.length; index++) {
        const resolution = resolutions[index].resolvedModule;
        const moduleName = moduleNames[index].text;
        const mode = getModeForUsageLocation(file, moduleNames[index]);
        setResolvedModule(file, moduleName, resolutions[index], mode);
        addResolutionDiagnosticsFromResolutionOrCache(file, moduleName, resolutions[index], mode);
        if (!resolution) {
          continue;
        }
        const isFromNodeModulesSearch = resolution.isExternalLibraryImport;
        const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension);
        const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
        const resolvedFileName = resolution.resolvedFileName;
        if (isFromNodeModulesSearch) {
          currentNodeModulesDepth++;
        }
        const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
        const shouldAddFile = resolvedFileName && !getResolutionDiagnostic(optionsForFile, resolution, file) && !optionsForFile.noResolve && index < file.imports.length && !elideImport && !(isJsFile && !getAllowJSCompilerOption(optionsForFile)) && (isInJSFile(file.imports[index]) || !(file.imports[index].flags & 8388608 /* JSDoc */));
        if (elideImport) {
          modulesWithElidedImports.set(file.path, true);
        } else if (shouldAddFile) {
          findSourceFile(
            resolvedFileName,
            /*isDefaultLib*/
            false,
            /*ignoreNoDefaultLib*/
            false,
            { kind: 3 /* Import */, file: file.path, index },
            resolution.packageId
          );
        }
        if (isFromNodeModulesSearch) {
          currentNodeModulesDepth--;
        }
      }
    } else {
      file.resolvedModules = void 0;
    }
  }
  function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
    let allFilesBelongToPath = true;
    const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory));
    for (const sourceFile of sourceFiles) {
      if (!sourceFile.isDeclarationFile) {
        const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
        if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
          addProgramDiagnosticExplainingFile(
            sourceFile,
            Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files,
            [sourceFile.fileName, rootDirectory]
          );
          allFilesBelongToPath = false;
        }
      }
    }
    return allFilesBelongToPath;
  }
  function parseProjectReferenceConfigFile(ref) {
    if (!projectReferenceRedirects) {
      projectReferenceRedirects = /* @__PURE__ */ new Map();
    }
    const refPath = resolveProjectReferencePath(ref);
    const sourceFilePath = toPath3(refPath);
    const fromCache = projectReferenceRedirects.get(sourceFilePath);
    if (fromCache !== void 0) {
      return fromCache || void 0;
    }
    let commandLine;
    let sourceFile;
    if (host.getParsedCommandLine) {
      commandLine = host.getParsedCommandLine(refPath);
      if (!commandLine) {
        addFileToFilesByName(
          /*file*/
          void 0,
          sourceFilePath,
          /*redirectedPath*/
          void 0
        );
        projectReferenceRedirects.set(sourceFilePath, false);
        return void 0;
      }
      sourceFile = Debug.checkDefined(commandLine.options.configFile);
      Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
      addFileToFilesByName(
        sourceFile,
        sourceFilePath,
        /*redirectedPath*/
        void 0
      );
    } else {
      const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory);
      sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
      addFileToFilesByName(
        sourceFile,
        sourceFilePath,
        /*redirectedPath*/
        void 0
      );
      if (sourceFile === void 0) {
        projectReferenceRedirects.set(sourceFilePath, false);
        return void 0;
      }
      commandLine = parseJsonSourceFileConfigFileContent(
        sourceFile,
        configParsingHost,
        basePath,
        /*existingOptions*/
        void 0,
        refPath
      );
    }
    sourceFile.fileName = refPath;
    sourceFile.path = sourceFilePath;
    sourceFile.resolvedPath = sourceFilePath;
    sourceFile.originalFileName = refPath;
    const resolvedRef = { commandLine, sourceFile };
    projectReferenceRedirects.set(sourceFilePath, resolvedRef);
    if (commandLine.projectReferences) {
      resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
    }
    return resolvedRef;
  }
  function verifyCompilerOptions() {
    if (options.strictPropertyInitialization && !getStrictOptionValue(options, "strictNullChecks")) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
    }
    if (options.exactOptionalPropertyTypes && !getStrictOptionValue(options, "strictNullChecks")) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "exactOptionalPropertyTypes", "strictNullChecks");
    }
    if (options.isolatedModules || options.verbatimModuleSyntax) {
      if (options.out) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules");
      }
      if (options.outFile) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules");
      }
    }
    if (options.inlineSourceMap) {
      if (options.sourceMap) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
      }
      if (options.mapRoot) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
      }
    }
    if (options.composite) {
      if (options.declaration === false) {
        createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
      }
      if (options.incremental === false) {
        createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
      }
    }
    const outputFile = outFile(options);
    if (options.tsBuildInfoFile) {
      if (!isIncrementalCompilation(options)) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
      }
    } else if (options.incremental && !outputFile && !options.configFilePath) {
      programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
    }
    verifyDeprecatedCompilerOptions();
    verifyProjectReferences();
    if (options.composite) {
      const rootPaths = new Set(rootNames.map(toPath3));
      for (const file of files) {
        if (sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
          addProgramDiagnosticExplainingFile(
            file,
            Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern,
            [file.fileName, options.configFilePath || ""]
          );
        }
      }
    }
    if (options.paths) {
      for (const key in options.paths) {
        if (!hasProperty(options.paths, key)) {
          continue;
        }
        if (!hasZeroOrOneAsteriskCharacter(key)) {
          createDiagnosticForOptionPaths(
            /*onKey*/
            true,
            key,
            Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character,
            key
          );
        }
        if (isArray(options.paths[key])) {
          const len = options.paths[key].length;
          if (len === 0) {
            createDiagnosticForOptionPaths(
              /*onKey*/
              false,
              key,
              Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array,
              key
            );
          }
          for (let i = 0; i < len; i++) {
            const subst = options.paths[key][i];
            const typeOfSubst = typeof subst;
            if (typeOfSubst === "string") {
              if (!hasZeroOrOneAsteriskCharacter(subst)) {
                createDiagnosticForOptionPathKeyValue(key, i, Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
              }
              if (!options.baseUrl && !pathIsRelative(subst) && !pathIsAbsolute(subst)) {
                createDiagnosticForOptionPathKeyValue(key, i, Diagnostics.Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash);
              }
            } else {
              createDiagnosticForOptionPathKeyValue(key, i, Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
            }
          }
        } else {
          createDiagnosticForOptionPaths(
            /*onKey*/
            false,
            key,
            Diagnostics.Substitutions_for_pattern_0_should_be_an_array,
            key
          );
        }
      }
    }
    if (!options.sourceMap && !options.inlineSourceMap) {
      if (options.inlineSources) {
        createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
      }
      if (options.sourceRoot) {
        createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
      }
    }
    if (options.out && options.outFile) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
    }
    if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
    }
    if (options.declarationDir) {
      if (!getEmitDeclarations(options)) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
      }
      if (outputFile) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
      }
    }
    if (options.declarationMap && !getEmitDeclarations(options)) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
    }
    if (options.lib && options.noLib) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
    }
    if (options.noImplicitUseStrict && getStrictOptionValue(options, "alwaysStrict")) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
    }
    const languageVersion = getEmitScriptTarget(options);
    const firstNonAmbientExternalModuleSourceFile = find(files, (f) => isExternalModule(f) && !f.isDeclarationFile);
    if (options.isolatedModules || options.verbatimModuleSyntax) {
      if (options.module === 0 /* None */ && languageVersion < 2 /* ES2015 */ && options.isolatedModules) {
        createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
      }
      if (options.preserveConstEnums === false) {
        createDiagnosticForOptionName(Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_0_is_enabled, options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules", "preserveConstEnums");
      }
    } else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === 0 /* None */) {
      const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, typeof firstNonAmbientExternalModuleSourceFile.externalModuleIndicator === "boolean" ? firstNonAmbientExternalModuleSourceFile : firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
      programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
    }
    if (outputFile && !options.emitDeclarationOnly) {
      if (options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) {
        createDiagnosticForOptionName(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
      } else if (options.module === void 0 && firstNonAmbientExternalModuleSourceFile) {
        const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, typeof firstNonAmbientExternalModuleSourceFile.externalModuleIndicator === "boolean" ? firstNonAmbientExternalModuleSourceFile : firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
        programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
      }
    }
    if (getResolveJsonModule(options)) {
      if (getEmitModuleResolutionKind(options) === 1 /* Classic */) {
        createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_when_moduleResolution_is_set_to_classic, "resolveJsonModule");
      } else if (!hasJsonModuleEmitEnabled(options)) {
        createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
      }
    }
    if (options.outDir || // there is --outDir specified
    options.rootDir || // there is --rootDir specified
    options.sourceRoot || // there is --sourceRoot specified
    options.mapRoot) {
      const dir = getCommonSourceDirectory2();
      if (options.outDir && dir === "" && files.some((file) => getRootLength(file.fileName) > 1)) {
        createDiagnosticForOptionName(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
      }
    }
    if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
    }
    if (options.checkJs && !getAllowJSCompilerOption(options)) {
      programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
    }
    if (options.emitDeclarationOnly) {
      if (!getEmitDeclarations(options)) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
      }
      if (options.noEmit) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
      }
    }
    if (options.emitDecoratorMetadata && !options.experimentalDecorators) {
      createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
    }
    if (options.jsxFactory) {
      if (options.reactNamespace) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
      }
      if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", inverseJsxOptionMap.get("" + options.jsx));
      }
      if (!parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
        createOptionValueDiagnostic("jsxFactory", Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
      }
    } else if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) {
      createOptionValueDiagnostic("reactNamespace", Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
    }
    if (options.jsxFragmentFactory) {
      if (!options.jsxFactory) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory");
      }
      if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", inverseJsxOptionMap.get("" + options.jsx));
      }
      if (!parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) {
        createOptionValueDiagnostic("jsxFragmentFactory", Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory);
      }
    }
    if (options.reactNamespace) {
      if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", inverseJsxOptionMap.get("" + options.jsx));
      }
    }
    if (options.jsxImportSource) {
      if (options.jsx === 2 /* React */) {
        createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", inverseJsxOptionMap.get("" + options.jsx));
      }
    }
    if (options.preserveValueImports && getEmitModuleKind(options) < 5 /* ES2015 */) {
      createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_es2015_or_later, "preserveValueImports");
    }
    const moduleKind = getEmitModuleKind(options);
    if (options.verbatimModuleSyntax) {
      if (moduleKind === 2 /* AMD */ || moduleKind === 3 /* UMD */ || moduleKind === 4 /* System */) {
        createDiagnosticForOptionName(Diagnostics.Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System, "verbatimModuleSyntax");
      }
      if (options.preserveValueImports) {
        createRedundantOptionDiagnostic("preserveValueImports", "verbatimModuleSyntax");
      }
      if (options.importsNotUsedAsValues) {
        createRedundantOptionDiagnostic("importsNotUsedAsValues", "verbatimModuleSyntax");
      }
    }
    if (options.allowImportingTsExtensions && !(options.noEmit || options.emitDeclarationOnly)) {
      createOptionValueDiagnostic("allowImportingTsExtensions", Diagnostics.Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set);
    }
    const moduleResolution = getEmitModuleResolutionKind(options);
    if (options.resolvePackageJsonExports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
      createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonExports");
    }
    if (options.resolvePackageJsonImports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
      createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonImports");
    }
    if (options.customConditions && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
      createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "customConditions");
    }
    if (moduleResolution === 100 /* Bundler */ && !emitModuleKindIsNonNodeESM(moduleKind)) {
      createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_es2015_or_later, "bundler");
    }
    if (!options.noEmit && !options.suppressOutputPathCheck) {
      const emitHost = getEmitHost();
      const emitFilesSeen = /* @__PURE__ */ new Set();
      forEachEmittedFile(emitHost, (emitFileNames) => {
        if (!options.emitDeclarationOnly) {
          verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen);
        }
        verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen);
      });
    }
    function verifyEmitFilePath(emitFileName, emitFilesSeen) {
      if (emitFileName) {
        const emitFilePath = toPath3(emitFileName);
        if (filesByName.has(emitFilePath)) {
          let chain;
          if (!options.configFilePath) {
            chain = chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig
            );
          }
          chain = chainDiagnosticMessages(chain, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
          blockEmittingOfFile(emitFileName, createCompilerDiagnosticFromMessageChain(chain));
        }
        const emitFileKey = !host.useCaseSensitiveFileNames() ? toFileNameLowerCase(emitFilePath) : emitFilePath;
        if (emitFilesSeen.has(emitFileKey)) {
          blockEmittingOfFile(emitFileName, createCompilerDiagnostic(Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
        } else {
          emitFilesSeen.add(emitFileKey);
        }
      }
    }
  }
  function getIgnoreDeprecationsVersion() {
    const ignoreDeprecations = options.ignoreDeprecations;
    if (ignoreDeprecations) {
      if (ignoreDeprecations === "5.0") {
        return new Version(ignoreDeprecations);
      }
      reportInvalidIgnoreDeprecations();
    }
    return Version.zero;
  }
  function checkDeprecations(deprecatedIn, removedIn, createDiagnostic, fn) {
    const deprecatedInVersion = new Version(deprecatedIn);
    const removedInVersion = new Version(removedIn);
    const typescriptVersion = new Version(typeScriptVersion3 || versionMajorMinor);
    const ignoreDeprecationsVersion = getIgnoreDeprecationsVersion();
    const mustBeRemoved = !(removedInVersion.compareTo(typescriptVersion) === 1 /* GreaterThan */);
    const canBeSilenced = !mustBeRemoved && ignoreDeprecationsVersion.compareTo(deprecatedInVersion) === -1 /* LessThan */;
    if (mustBeRemoved || canBeSilenced) {
      fn((name, value, useInstead) => {
        if (mustBeRemoved) {
          if (value === void 0) {
            createDiagnostic(name, value, useInstead, Diagnostics.Option_0_has_been_removed_Please_remove_it_from_your_configuration, name);
          } else {
            createDiagnostic(name, value, useInstead, Diagnostics.Option_0_1_has_been_removed_Please_remove_it_from_your_configuration, name, value);
          }
        } else {
          if (value === void 0) {
            createDiagnostic(name, value, useInstead, Diagnostics.Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprecations_Colon_2_to_silence_this_error, name, removedIn, deprecatedIn);
          } else {
            createDiagnostic(name, value, useInstead, Diagnostics.Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDeprecations_Colon_3_to_silence_this_error, name, value, removedIn, deprecatedIn);
          }
        }
      });
    }
  }
  function verifyDeprecatedCompilerOptions() {
    function createDiagnostic(name, value, useInstead, message, ...args) {
      if (useInstead) {
        const details = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Use_0_instead,
          useInstead
        );
        const chain = chainDiagnosticMessages(details, message, ...args);
        createDiagnosticForOption(
          /*onKey*/
          !value,
          name,
          /*option2*/
          void 0,
          chain
        );
      } else {
        createDiagnosticForOption(
          /*onKey*/
          !value,
          name,
          /*option2*/
          void 0,
          message,
          ...args
        );
      }
    }
    checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => {
      if (options.target === 0 /* ES3 */) {
        createDeprecatedDiagnostic("target", "ES3");
      }
      if (options.noImplicitUseStrict) {
        createDeprecatedDiagnostic("noImplicitUseStrict");
      }
      if (options.keyofStringsOnly) {
        createDeprecatedDiagnostic("keyofStringsOnly");
      }
      if (options.suppressExcessPropertyErrors) {
        createDeprecatedDiagnostic("suppressExcessPropertyErrors");
      }
      if (options.suppressImplicitAnyIndexErrors) {
        createDeprecatedDiagnostic("suppressImplicitAnyIndexErrors");
      }
      if (options.noStrictGenericChecks) {
        createDeprecatedDiagnostic("noStrictGenericChecks");
      }
      if (options.charset) {
        createDeprecatedDiagnostic("charset");
      }
      if (options.out) {
        createDeprecatedDiagnostic(
          "out",
          /*value*/
          void 0,
          "outFile"
        );
      }
      if (options.importsNotUsedAsValues) {
        createDeprecatedDiagnostic(
          "importsNotUsedAsValues",
          /*value*/
          void 0,
          "verbatimModuleSyntax"
        );
      }
      if (options.preserveValueImports) {
        createDeprecatedDiagnostic(
          "preserveValueImports",
          /*value*/
          void 0,
          "verbatimModuleSyntax"
        );
      }
    });
  }
  function verifyDeprecatedProjectReference(ref, parentFile, index) {
    function createDiagnostic(_name, _value, _useInstead, message, ...args) {
      createDiagnosticForReference(parentFile, index, message, ...args);
    }
    checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => {
      if (ref.prepend) {
        createDeprecatedDiagnostic("prepend");
      }
    });
  }
  function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) {
    var _a2;
    let fileIncludeReasons;
    let relatedInfo;
    let locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : void 0;
    if (file)
      (_a2 = fileReasons.get(file.path)) == null ? void 0 : _a2.forEach(processReason);
    if (fileProcessingReason)
      processReason(fileProcessingReason);
    if (locationReason && (fileIncludeReasons == null ? void 0 : fileIncludeReasons.length) === 1)
      fileIncludeReasons = void 0;
    const location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason);
    const fileIncludeReasonDetails = fileIncludeReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon);
    const redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file);
    const chain = chainDiagnosticMessages(redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, diagnostic, ...args || emptyArray);
    return location && isReferenceFileLocation(location) ? createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : createCompilerDiagnosticFromMessageChain(chain, relatedInfo);
    function processReason(reason) {
      (fileIncludeReasons || (fileIncludeReasons = [])).push(fileIncludeReasonToDiagnostics(program, reason));
      if (!locationReason && isReferencedFile(reason)) {
        locationReason = reason;
      } else if (locationReason !== reason) {
        relatedInfo = append(relatedInfo, fileIncludeReasonToRelatedInformation(reason));
      }
      if (reason === fileProcessingReason)
        fileProcessingReason = void 0;
    }
  }
  function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) {
    (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
      kind: 1 /* FilePreprocessingFileExplainingDiagnostic */,
      file: file && file.path,
      fileProcessingReason,
      diagnostic,
      args
    });
  }
  function addProgramDiagnosticExplainingFile(file, diagnostic, args) {
    programDiagnostics.add(createDiagnosticExplainingFile(
      file,
      /*fileProcessingReason*/
      void 0,
      diagnostic,
      args
    ));
  }
  function fileIncludeReasonToRelatedInformation(reason) {
    if (isReferencedFile(reason)) {
      const referenceLocation = getReferencedFileLocation(getSourceFileByPath, reason);
      let message2;
      switch (reason.kind) {
        case 3 /* Import */:
          message2 = Diagnostics.File_is_included_via_import_here;
          break;
        case 4 /* ReferenceFile */:
          message2 = Diagnostics.File_is_included_via_reference_here;
          break;
        case 5 /* TypeReferenceDirective */:
          message2 = Diagnostics.File_is_included_via_type_library_reference_here;
          break;
        case 7 /* LibReferenceDirective */:
          message2 = Diagnostics.File_is_included_via_library_reference_here;
          break;
        default:
          Debug.assertNever(reason);
      }
      return isReferenceFileLocation(referenceLocation) ? createFileDiagnostic(
        referenceLocation.file,
        referenceLocation.pos,
        referenceLocation.end - referenceLocation.pos,
        message2
      ) : void 0;
    }
    if (!options.configFile)
      return void 0;
    let configFileNode;
    let message;
    switch (reason.kind) {
      case 0 /* RootFile */:
        if (!options.configFile.configFileSpecs)
          return void 0;
        const fileName = getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory);
        const matchedByFiles = getMatchedFileSpec(program, fileName);
        if (matchedByFiles) {
          configFileNode = getTsConfigPropArrayElementValue(options.configFile, "files", matchedByFiles);
          message = Diagnostics.File_is_matched_by_files_list_specified_here;
          break;
        }
        const matchedByInclude = getMatchedIncludeSpec(program, fileName);
        if (!matchedByInclude || !isString(matchedByInclude))
          return void 0;
        configFileNode = getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude);
        message = Diagnostics.File_is_matched_by_include_pattern_specified_here;
        break;
      case 1 /* SourceFromProjectReference */:
      case 2 /* OutputFromProjectReference */:
        const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences == null ? void 0 : resolvedProjectReferences[reason.index]);
        const referenceInfo = forEachProjectReference(
          projectReferences,
          resolvedProjectReferences,
          (resolvedRef, parent2, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent2 == null ? void 0 : parent2.sourceFile) || options.configFile, index: index2 } : void 0
        );
        if (!referenceInfo)
          return void 0;
        const { sourceFile, index } = referenceInfo;
        const referencesSyntax = forEachTsConfigPropArray(
          sourceFile,
          "references",
          (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0
        );
        return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile(
          sourceFile,
          referencesSyntax.elements[index],
          reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here
        ) : void 0;
      case 8 /* AutomaticTypeDirectiveFile */:
        if (!options.types)
          return void 0;
        configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference);
        message = Diagnostics.File_is_entry_point_of_type_library_specified_here;
        break;
      case 6 /* LibFile */:
        if (reason.index !== void 0) {
          configFileNode = getOptionsSyntaxByArrayElementValue("lib", options.lib[reason.index]);
          message = Diagnostics.File_is_library_specified_here;
          break;
        }
        const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === getEmitScriptTarget(options) ? key : void 0);
        configFileNode = target ? getOptionsSyntaxByValue("target", target) : void 0;
        message = Diagnostics.File_is_default_library_for_target_specified_here;
        break;
      default:
        Debug.assertNever(reason);
    }
    return configFileNode && createDiagnosticForNodeInSourceFile(
      options.configFile,
      configFileNode,
      message
    );
  }
  function verifyProjectReferences() {
    const buildInfoPath = !options.suppressOutputPathCheck ? getTsBuildInfoEmitOutputFilePath(options) : void 0;
    forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent2, index) => {
      const ref = (parent2 ? parent2.commandLine.projectReferences : projectReferences)[index];
      const parentFile = parent2 && parent2.sourceFile;
      verifyDeprecatedProjectReference(ref, parentFile, index);
      if (!resolvedRef) {
        createDiagnosticForReference(parentFile, index, Diagnostics.File_0_not_found, ref.path);
        return;
      }
      const options2 = resolvedRef.commandLine.options;
      if (!options2.composite || options2.noEmit) {
        const inputs = parent2 ? parent2.commandLine.fileNames : rootNames;
        if (inputs.length) {
          if (!options2.composite)
            createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
          if (options2.noEmit)
            createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path);
        }
      }
      if (ref.prepend) {
        const out = outFile(options2);
        if (out) {
          if (!host.fileExists(out)) {
            createDiagnosticForReference(parentFile, index, Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
          }
        } else {
          createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
        }
      }
      if (!parent2 && buildInfoPath && buildInfoPath === getTsBuildInfoEmitOutputFilePath(options2)) {
        createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
        hasEmitBlockingDiagnostics.set(toPath3(buildInfoPath), true);
      }
    });
  }
  function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, ...args) {
    let needCompilerDiagnostic = true;
    forEachOptionPathsSyntax((pathProp) => {
      if (isObjectLiteralExpression(pathProp.initializer)) {
        forEachPropertyAssignment(pathProp.initializer, key, (keyProps) => {
          const initializer = keyProps.initializer;
          if (isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
            programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, ...args));
            needCompilerDiagnostic = false;
          }
        });
      }
    });
    if (needCompilerDiagnostic) {
      programDiagnostics.add(createCompilerDiagnostic(message, ...args));
    }
  }
  function createDiagnosticForOptionPaths(onKey, key, message, ...args) {
    let needCompilerDiagnostic = true;
    forEachOptionPathsSyntax((pathProp) => {
      if (isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax(
        pathProp.initializer,
        onKey,
        key,
        /*key2*/
        void 0,
        message,
        ...args
      )) {
        needCompilerDiagnostic = false;
      }
    });
    if (needCompilerDiagnostic) {
      programDiagnostics.add(createCompilerDiagnostic(message, ...args));
    }
  }
  function forEachOptionsSyntaxByName(name, callback) {
    return forEachPropertyAssignment(getCompilerOptionsObjectLiteralSyntax(), name, callback);
  }
  function forEachOptionPathsSyntax(callback) {
    return forEachOptionsSyntaxByName("paths", callback);
  }
  function getOptionsSyntaxByValue(name, value) {
    return forEachOptionsSyntaxByName(name, (property) => isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : void 0);
  }
  function getOptionsSyntaxByArrayElementValue(name, value) {
    const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
    return compilerOptionsObjectLiteralSyntax && getPropertyArrayElementValue(compilerOptionsObjectLiteralSyntax, name, value);
  }
  function createDiagnosticForOptionName(message, option1, option2, option3) {
    createDiagnosticForOption(
      /*onKey*/
      true,
      option1,
      option2,
      message,
      option1,
      option2,
      option3
    );
  }
  function createOptionValueDiagnostic(option1, message, ...args) {
    createDiagnosticForOption(
      /*onKey*/
      false,
      option1,
      /*option2*/
      void 0,
      message,
      ...args
    );
  }
  function createDiagnosticForReference(sourceFile, index, message, ...args) {
    const referencesSyntax = forEachTsConfigPropArray(
      sourceFile || options.configFile,
      "references",
      (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0
    );
    if (referencesSyntax && referencesSyntax.elements.length > index) {
      programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, ...args));
    } else {
      programDiagnostics.add(createCompilerDiagnostic(message, ...args));
    }
  }
  function createDiagnosticForOption(onKey, option1, option2, message, ...args) {
    const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
    const needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, ...args);
    if (needCompilerDiagnostic) {
      if ("messageText" in message) {
        programDiagnostics.add(createCompilerDiagnosticFromMessageChain(message));
      } else {
        programDiagnostics.add(createCompilerDiagnostic(message, ...args));
      }
    }
  }
  function getCompilerOptionsObjectLiteralSyntax() {
    if (_compilerOptionsObjectLiteralSyntax === void 0) {
      _compilerOptionsObjectLiteralSyntax = forEachPropertyAssignment(
        getTsConfigObjectLiteralExpression(options.configFile),
        "compilerOptions",
        (prop) => isObjectLiteralExpression(prop.initializer) ? prop.initializer : void 0
      ) || false;
    }
    return _compilerOptionsObjectLiteralSyntax || void 0;
  }
  function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, ...args) {
    let needsCompilerDiagnostic = false;
    forEachPropertyAssignment(objectLiteral, key1, (prop) => {
      if ("messageText" in message) {
        programDiagnostics.add(createDiagnosticForNodeFromMessageChain(options.configFile, onKey ? prop.name : prop.initializer, message));
      } else {
        programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, ...args));
      }
      needsCompilerDiagnostic = true;
    }, key2);
    return needsCompilerDiagnostic;
  }
  function createRedundantOptionDiagnostic(errorOnOption, redundantWithOption) {
    const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
    if (compilerOptionsObjectLiteralSyntax) {
      createOptionDiagnosticInObjectLiteralSyntax(
        compilerOptionsObjectLiteralSyntax,
        /*onKey*/
        true,
        errorOnOption,
        /*key2*/
        void 0,
        Diagnostics.Option_0_is_redundant_and_cannot_be_specified_with_option_1,
        errorOnOption,
        redundantWithOption
      );
    } else {
      createDiagnosticForOptionName(Diagnostics.Option_0_is_redundant_and_cannot_be_specified_with_option_1, errorOnOption, redundantWithOption);
    }
  }
  function blockEmittingOfFile(emitFileName, diag2) {
    hasEmitBlockingDiagnostics.set(toPath3(emitFileName), true);
    programDiagnostics.add(diag2);
  }
  function isEmittedFile(file) {
    if (options.noEmit) {
      return false;
    }
    const filePath = toPath3(file);
    if (getSourceFileByPath(filePath)) {
      return false;
    }
    const out = outFile(options);
    if (out) {
      return isSameFile(filePath, out) || isSameFile(filePath, removeFileExtension(out) + ".d.ts" /* Dts */);
    }
    if (options.declarationDir && containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
      return true;
    }
    if (options.outDir) {
      return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
    }
    if (fileExtensionIsOneOf(filePath, supportedJSExtensionsFlat) || isDeclarationFileName(filePath)) {
      const filePathWithoutExtension = removeFileExtension(filePath);
      return !!getSourceFileByPath(filePathWithoutExtension + ".ts" /* Ts */) || !!getSourceFileByPath(filePathWithoutExtension + ".tsx" /* Tsx */);
    }
    return false;
  }
  function isSameFile(file1, file2) {
    return comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
  }
  function getSymlinkCache() {
    if (host.getSymlinkCache) {
      return host.getSymlinkCache();
    }
    if (!symlinks) {
      symlinks = createSymlinkCache(currentDirectory, getCanonicalFileName);
    }
    if (files && automaticTypeDirectiveResolutions && !symlinks.hasProcessedResolutions()) {
      symlinks.setSymlinksFromResolutions(files, automaticTypeDirectiveResolutions);
    }
    return symlinks;
  }
}
function updateHostForUseSourceOfProjectReferenceRedirect(host) {
  let setOfDeclarationDirectories;
  const originalFileExists = host.compilerHost.fileExists;
  const originalDirectoryExists = host.compilerHost.directoryExists;
  const originalGetDirectories = host.compilerHost.getDirectories;
  const originalRealpath = host.compilerHost.realpath;
  if (!host.useSourceOfProjectReferenceRedirect)
    return { onProgramCreateComplete: noop, fileExists };
  host.compilerHost.fileExists = fileExists;
  let directoryExists;
  if (originalDirectoryExists) {
    directoryExists = host.compilerHost.directoryExists = (path) => {
      if (originalDirectoryExists.call(host.compilerHost, path)) {
        handleDirectoryCouldBeSymlink(path);
        return true;
      }
      if (!host.getResolvedProjectReferences())
        return false;
      if (!setOfDeclarationDirectories) {
        setOfDeclarationDirectories = /* @__PURE__ */ new Set();
        host.forEachResolvedProjectReference((ref) => {
          const out = outFile(ref.commandLine.options);
          if (out) {
            setOfDeclarationDirectories.add(getDirectoryPath(host.toPath(out)));
          } else {
            const declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
            if (declarationDir) {
              setOfDeclarationDirectories.add(host.toPath(declarationDir));
            }
          }
        });
      }
      return fileOrDirectoryExistsUsingSource(
        path,
        /*isFile*/
        false
      );
    };
  }
  if (originalGetDirectories) {
    host.compilerHost.getDirectories = (path) => !host.getResolvedProjectReferences() || originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path) ? originalGetDirectories.call(host.compilerHost, path) : [];
  }
  if (originalRealpath) {
    host.compilerHost.realpath = (s) => {
      var _a;
      return ((_a = host.getSymlinkCache().getSymlinkedFiles()) == null ? void 0 : _a.get(host.toPath(s))) || originalRealpath.call(host.compilerHost, s);
    };
  }
  return { onProgramCreateComplete, fileExists, directoryExists };
  function onProgramCreateComplete() {
    host.compilerHost.fileExists = originalFileExists;
    host.compilerHost.directoryExists = originalDirectoryExists;
    host.compilerHost.getDirectories = originalGetDirectories;
  }
  function fileExists(file) {
    if (originalFileExists.call(host.compilerHost, file))
      return true;
    if (!host.getResolvedProjectReferences())
      return false;
    if (!isDeclarationFileName(file))
      return false;
    return fileOrDirectoryExistsUsingSource(
      file,
      /*isFile*/
      true
    );
  }
  function fileExistsIfProjectReferenceDts(file) {
    const source = host.getSourceOfProjectReferenceRedirect(host.toPath(file));
    return source !== void 0 ? isString(source) ? originalFileExists.call(host.compilerHost, source) : true : void 0;
  }
  function directoryExistsIfProjectReferenceDeclDir(dir) {
    const dirPath = host.toPath(dir);
    const dirPathWithTrailingDirectorySeparator = `${dirPath}${directorySeparator}`;
    return forEachKey(
      setOfDeclarationDirectories,
      (declDirPath) => dirPath === declDirPath || // Any parent directory of declaration dir
      startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || // Any directory inside declaration dir
      startsWith(dirPath, `${declDirPath}/`)
    );
  }
  function handleDirectoryCouldBeSymlink(directory) {
    var _a;
    if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory))
      return;
    if (!originalRealpath || !stringContains(directory, nodeModulesPathPart))
      return;
    const symlinkCache = host.getSymlinkCache();
    const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory));
    if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath))
      return;
    const real = normalizePath(originalRealpath.call(host.compilerHost, directory));
    let realPath2;
    if (real === directory || (realPath2 = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
      symlinkCache.setSymlinkedDirectory(directoryPath, false);
      return;
    }
    symlinkCache.setSymlinkedDirectory(directory, {
      real: ensureTrailingDirectorySeparator(real),
      realPath: realPath2
    });
  }
  function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
    var _a;
    const fileOrDirectoryExistsUsingSource2 = isFile ? (file) => fileExistsIfProjectReferenceDts(file) : (dir) => directoryExistsIfProjectReferenceDeclDir(dir);
    const result = fileOrDirectoryExistsUsingSource2(fileOrDirectory);
    if (result !== void 0)
      return result;
    const symlinkCache = host.getSymlinkCache();
    const symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
    if (!symlinkedDirectories)
      return false;
    const fileOrDirectoryPath = host.toPath(fileOrDirectory);
    if (!stringContains(fileOrDirectoryPath, nodeModulesPathPart))
      return false;
    if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath)))
      return true;
    return firstDefinedIterator(
      symlinkedDirectories.entries(),
      ([directoryPath, symlinkedDirectory]) => {
        if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath))
          return void 0;
        const result2 = fileOrDirectoryExistsUsingSource2(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
        if (isFile && result2) {
          const absolutePath = getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
          symlinkCache.setSymlinkedFile(
            fileOrDirectoryPath,
            `${symlinkedDirectory.real}${absolutePath.replace(new RegExp(directoryPath, "i"), "")}`
          );
        }
        return result2;
      }
    ) || false;
  }
}
var emitSkippedWithNoDiagnostics = { diagnostics: emptyArray, sourceMaps: void 0, emittedFiles: void 0, emitSkipped: true };
function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) {
  const options = program.getCompilerOptions();
  if (options.noEmit) {
    program.getSemanticDiagnostics(sourceFile, cancellationToken);
    return sourceFile || outFile(options) ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken);
  }
  if (!options.noEmitOnError)
    return void 0;
  let diagnostics = [
    ...program.getOptionsDiagnostics(cancellationToken),
    ...program.getSyntacticDiagnostics(sourceFile, cancellationToken),
    ...program.getGlobalDiagnostics(cancellationToken),
    ...program.getSemanticDiagnostics(sourceFile, cancellationToken)
  ];
  if (diagnostics.length === 0 && getEmitDeclarations(program.getCompilerOptions())) {
    diagnostics = program.getDeclarationDiagnostics(
      /*sourceFile*/
      void 0,
      cancellationToken
    );
  }
  if (!diagnostics.length)
    return void 0;
  let emittedFiles;
  if (!sourceFile && !outFile(options)) {
    const emitResult = program.emitBuildInfo(writeFile2, cancellationToken);
    if (emitResult.diagnostics)
      diagnostics = [...diagnostics, ...emitResult.diagnostics];
    emittedFiles = emitResult.emittedFiles;
  }
  return { diagnostics, sourceMaps: void 0, emittedFiles, emitSkipped: true };
}
function filterSemanticDiagnostics(diagnostic, option) {
  return filter(diagnostic, (d) => !d.skippedOn || !option[d.skippedOn]);
}
function parseConfigHostFromCompilerHostLike(host, directoryStructureHost = host) {
  return {
    fileExists: (f) => directoryStructureHost.fileExists(f),
    readDirectory(root, extensions, excludes, includes, depth) {
      Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
      return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
    },
    readFile: (f) => directoryStructureHost.readFile(f),
    useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
    getCurrentDirectory: () => host.getCurrentDirectory(),
    onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined,
    trace: host.trace ? (s) => host.trace(s) : void 0
  };
}
function createPrependNodes(projectReferences, getCommandLine, readFile, host) {
  if (!projectReferences)
    return emptyArray;
  let nodes;
  for (let i = 0; i < projectReferences.length; i++) {
    const ref = projectReferences[i];
    const resolvedRefOpts = getCommandLine(ref, i);
    if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
      const out = outFile(resolvedRefOpts.options);
      if (!out)
        continue;
      const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(
        resolvedRefOpts.options,
        /*forceDtsPaths*/
        true
      );
      const node = createInputFilesWithFilePaths(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath, host, resolvedRefOpts.options);
      (nodes || (nodes = [])).push(node);
    }
  }
  return nodes || emptyArray;
}
function resolveProjectReferencePath(ref) {
  return resolveConfigFileProjectName(ref.path);
}
function getResolutionDiagnostic(options, { extension }, { isDeclarationFile }) {
  switch (extension) {
    case ".ts" /* Ts */:
    case ".d.ts" /* Dts */:
    case ".mts" /* Mts */:
    case ".d.mts" /* Dmts */:
    case ".cts" /* Cts */:
    case ".d.cts" /* Dcts */:
      return void 0;
    case ".tsx" /* Tsx */:
      return needJsx();
    case ".jsx" /* Jsx */:
      return needJsx() || needAllowJs();
    case ".js" /* Js */:
    case ".mjs" /* Mjs */:
    case ".cjs" /* Cjs */:
      return needAllowJs();
    case ".json" /* Json */:
      return needResolveJsonModule();
    default:
      return needAllowArbitraryExtensions();
  }
  function needJsx() {
    return options.jsx ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
  }
  function needAllowJs() {
    return getAllowJSCompilerOption(options) || !getStrictOptionValue(options, "noImplicitAny") ? void 0 : Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
  }
  function needResolveJsonModule() {
    return getResolveJsonModule(options) ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
  }
  function needAllowArbitraryExtensions() {
    return isDeclarationFile || options.allowArbitraryExtensions ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set;
  }
}
function getModuleNames({ imports, moduleAugmentations }) {
  const res = imports.map((i) => i);
  for (const aug of moduleAugmentations) {
    if (aug.kind === 11 /* StringLiteral */) {
      res.push(aug);
    }
  }
  return res;
}
function getModuleNameStringLiteralAt({ imports, moduleAugmentations }, index) {
  if (index < imports.length)
    return imports[index];
  let augIndex = imports.length;
  for (const aug of moduleAugmentations) {
    if (aug.kind === 11 /* StringLiteral */) {
      if (index === augIndex)
        return aug;
      augIndex++;
    }
  }
  Debug.fail("should never ask for module name at index higher than possible module name");
}

// src/compiler/builderState.ts
function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
  const outputFiles = [];
  const { emitSkipped, diagnostics } = program.emit(sourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit);
  return { outputFiles, emitSkipped, diagnostics };
  function writeFile2(fileName, text, writeByteOrderMark) {
    outputFiles.push({ name: fileName, writeByteOrderMark, text });
  }
}
var BuilderState;
((BuilderState2) => {
  function createManyToManyPathMap() {
    function create2(forward, reverse, deleted) {
      const map2 = {
        getKeys: (v) => reverse.get(v),
        getValues: (k) => forward.get(k),
        keys: () => forward.keys(),
        deleteKey: (k) => {
          (deleted || (deleted = /* @__PURE__ */ new Set())).add(k);
          const set = forward.get(k);
          if (!set) {
            return false;
          }
          set.forEach((v) => deleteFromMultimap(reverse, v, k));
          forward.delete(k);
          return true;
        },
        set: (k, vSet) => {
          deleted == null ? void 0 : deleted.delete(k);
          const existingVSet = forward.get(k);
          forward.set(k, vSet);
          existingVSet == null ? void 0 : existingVSet.forEach((v) => {
            if (!vSet.has(v)) {
              deleteFromMultimap(reverse, v, k);
            }
          });
          vSet.forEach((v) => {
            if (!(existingVSet == null ? void 0 : existingVSet.has(v))) {
              addToMultimap(reverse, v, k);
            }
          });
          return map2;
        }
      };
      return map2;
    }
    return create2(
      /* @__PURE__ */ new Map(),
      /* @__PURE__ */ new Map(),
      /*deleted*/
      void 0
    );
  }
  BuilderState2.createManyToManyPathMap = createManyToManyPathMap;
  function addToMultimap(map2, k, v) {
    let set = map2.get(k);
    if (!set) {
      set = /* @__PURE__ */ new Set();
      map2.set(k, set);
    }
    set.add(v);
  }
  function deleteFromMultimap(map2, k, v) {
    const set = map2.get(k);
    if (set == null ? void 0 : set.delete(v)) {
      if (!set.size) {
        map2.delete(k);
      }
      return true;
    }
    return false;
  }
  function getReferencedFilesFromImportedModuleSymbol(symbol) {
    return mapDefined(symbol.declarations, (declaration) => {
      var _a;
      return (_a = getSourceFileOfNode(declaration)) == null ? void 0 : _a.resolvedPath;
    });
  }
  function getReferencedFilesFromImportLiteral(checker, importName) {
    const symbol = checker.getSymbolAtLocation(importName);
    return symbol && getReferencedFilesFromImportedModuleSymbol(symbol);
  }
  function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
    return toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
  }
  function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
    let referencedFiles;
    if (sourceFile.imports && sourceFile.imports.length > 0) {
      const checker = program.getTypeChecker();
      for (const importName of sourceFile.imports) {
        const declarationSourceFilePaths = getReferencedFilesFromImportLiteral(checker, importName);
        declarationSourceFilePaths == null ? void 0 : declarationSourceFilePaths.forEach(addReferencedFile);
      }
    }
    const sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath);
    if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
      for (const referencedFile of sourceFile.referencedFiles) {
        const referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
        addReferencedFile(referencedPath);
      }
    }
    if (sourceFile.resolvedTypeReferenceDirectiveNames) {
      sourceFile.resolvedTypeReferenceDirectiveNames.forEach(({ resolvedTypeReferenceDirective }) => {
        if (!resolvedTypeReferenceDirective) {
          return;
        }
        const fileName = resolvedTypeReferenceDirective.resolvedFileName;
        const typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
        addReferencedFile(typeFilePath);
      });
    }
    if (sourceFile.moduleAugmentations.length) {
      const checker = program.getTypeChecker();
      for (const moduleName of sourceFile.moduleAugmentations) {
        if (!isStringLiteral(moduleName))
          continue;
        const symbol = checker.getSymbolAtLocation(moduleName);
        if (!symbol)
          continue;
        addReferenceFromAmbientModule(symbol);
      }
    }
    for (const ambientModule of program.getTypeChecker().getAmbientModules()) {
      if (ambientModule.declarations && ambientModule.declarations.length > 1) {
        addReferenceFromAmbientModule(ambientModule);
      }
    }
    return referencedFiles;
    function addReferenceFromAmbientModule(symbol) {
      if (!symbol.declarations) {
        return;
      }
      for (const declaration of symbol.declarations) {
        const declarationSourceFile = getSourceFileOfNode(declaration);
        if (declarationSourceFile && declarationSourceFile !== sourceFile) {
          addReferencedFile(declarationSourceFile.resolvedPath);
        }
      }
    }
    function addReferencedFile(referencedPath) {
      (referencedFiles || (referencedFiles = /* @__PURE__ */ new Set())).add(referencedPath);
    }
  }
  function canReuseOldState(newReferencedMap, oldState) {
    return oldState && !oldState.referencedMap === !newReferencedMap;
  }
  BuilderState2.canReuseOldState = canReuseOldState;
  function create(newProgram, oldState, disableUseFileVersionAsSignature) {
    var _a, _b, _c;
    const fileInfos = /* @__PURE__ */ new Map();
    const options = newProgram.getCompilerOptions();
    const isOutFile = outFile(options);
    const referencedMap = options.module !== 0 /* None */ && !isOutFile ? createManyToManyPathMap() : void 0;
    const exportedModulesMap = referencedMap ? createManyToManyPathMap() : void 0;
    const useOldState = canReuseOldState(referencedMap, oldState);
    newProgram.getTypeChecker();
    for (const sourceFile of newProgram.getSourceFiles()) {
      const version2 = Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
      const oldUncommittedSignature = useOldState ? (_a = oldState.oldSignatures) == null ? void 0 : _a.get(sourceFile.resolvedPath) : void 0;
      const signature = oldUncommittedSignature === void 0 ? useOldState ? (_b = oldState.fileInfos.get(sourceFile.resolvedPath)) == null ? void 0 : _b.signature : void 0 : oldUncommittedSignature || void 0;
      if (referencedMap) {
        const newReferences = getReferencedFiles(newProgram, sourceFile, newProgram.getCanonicalFileName);
        if (newReferences) {
          referencedMap.set(sourceFile.resolvedPath, newReferences);
        }
        if (useOldState) {
          const oldUncommittedExportedModules = (_c = oldState.oldExportedModulesMap) == null ? void 0 : _c.get(sourceFile.resolvedPath);
          const exportedModules = oldUncommittedExportedModules === void 0 ? oldState.exportedModulesMap.getValues(sourceFile.resolvedPath) : oldUncommittedExportedModules || void 0;
          if (exportedModules) {
            exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
          }
        }
      }
      fileInfos.set(sourceFile.resolvedPath, {
        version: version2,
        signature,
        // No need to calculate affectsGlobalScope with --out since its not used at all
        affectsGlobalScope: !isOutFile ? isFileAffectingGlobalScope(sourceFile) || void 0 : void 0,
        impliedFormat: sourceFile.impliedNodeFormat
      });
    }
    return {
      fileInfos,
      referencedMap,
      exportedModulesMap,
      useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState
    };
  }
  BuilderState2.create = create;
  function releaseCache2(state) {
    state.allFilesExcludingDefaultLibraryFile = void 0;
    state.allFileNames = void 0;
  }
  BuilderState2.releaseCache = releaseCache2;
  function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, host) {
    var _a, _b;
    const result = getFilesAffectedByWithOldState(
      state,
      programOfThisState,
      path,
      cancellationToken,
      host
    );
    (_a = state.oldSignatures) == null ? void 0 : _a.clear();
    (_b = state.oldExportedModulesMap) == null ? void 0 : _b.clear();
    return result;
  }
  BuilderState2.getFilesAffectedBy = getFilesAffectedBy;
  function getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, host) {
    const sourceFile = programOfThisState.getSourceFileByPath(path);
    if (!sourceFile) {
      return emptyArray;
    }
    if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host)) {
      return [sourceFile];
    }
    return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, host);
  }
  BuilderState2.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState;
  function updateSignatureOfFile(state, signature, path) {
    state.fileInfos.get(path).signature = signature;
    (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(path);
  }
  BuilderState2.updateSignatureOfFile = updateSignatureOfFile;
  function computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, onNewSignature) {
    programOfThisState.emit(
      sourceFile,
      (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => {
        Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`);
        onNewSignature(computeSignatureWithDiagnostics(
          programOfThisState,
          sourceFile,
          text,
          host,
          data
        ), sourceFiles);
      },
      cancellationToken,
      /*emitOnly*/
      true,
      /*customTransformers*/
      void 0,
      /*forceDtsEmit*/
      true
    );
  }
  BuilderState2.computeDtsSignature = computeDtsSignature;
  function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host, useFileVersionAsSignature = state.useFileVersionAsSignature) {
    var _a;
    if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath))
      return false;
    const info = state.fileInfos.get(sourceFile.resolvedPath);
    const prevSignature = info.signature;
    let latestSignature;
    if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) {
      computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, (signature, sourceFiles) => {
        latestSignature = signature;
        if (latestSignature !== prevSignature) {
          updateExportedModules(state, sourceFile, sourceFiles[0].exportedModulesFromDeclarationEmit);
        }
      });
    }
    if (latestSignature === void 0) {
      latestSignature = sourceFile.version;
      if (state.exportedModulesMap && latestSignature !== prevSignature) {
        (state.oldExportedModulesMap || (state.oldExportedModulesMap = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false);
        const references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : void 0;
        if (references) {
          state.exportedModulesMap.set(sourceFile.resolvedPath, references);
        } else {
          state.exportedModulesMap.deleteKey(sourceFile.resolvedPath);
        }
      }
    }
    (state.oldSignatures || (state.oldSignatures = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, prevSignature || false);
    (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(sourceFile.resolvedPath);
    info.signature = latestSignature;
    return latestSignature !== prevSignature;
  }
  BuilderState2.updateShapeSignature = updateShapeSignature;
  function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) {
    if (!state.exportedModulesMap)
      return;
    (state.oldExportedModulesMap || (state.oldExportedModulesMap = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false);
    const exportedModules = getExportedModules(exportedModulesFromDeclarationEmit);
    if (exportedModules) {
      state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
    } else {
      state.exportedModulesMap.deleteKey(sourceFile.resolvedPath);
    }
  }
  BuilderState2.updateExportedModules = updateExportedModules;
  function getExportedModules(exportedModulesFromDeclarationEmit) {
    let exportedModules;
    exportedModulesFromDeclarationEmit == null ? void 0 : exportedModulesFromDeclarationEmit.forEach(
      (symbol) => getReferencedFilesFromImportedModuleSymbol(symbol).forEach(
        (path) => (exportedModules ?? (exportedModules = /* @__PURE__ */ new Set())).add(path)
      )
    );
    return exportedModules;
  }
  BuilderState2.getExportedModules = getExportedModules;
  function getAllDependencies(state, programOfThisState, sourceFile) {
    const compilerOptions = programOfThisState.getCompilerOptions();
    if (outFile(compilerOptions)) {
      return getAllFileNames(state, programOfThisState);
    }
    if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
      return getAllFileNames(state, programOfThisState);
    }
    const seenMap = /* @__PURE__ */ new Set();
    const queue = [sourceFile.resolvedPath];
    while (queue.length) {
      const path = queue.pop();
      if (!seenMap.has(path)) {
        seenMap.add(path);
        const references = state.referencedMap.getValues(path);
        if (references) {
          for (const key of references.keys()) {
            queue.push(key);
          }
        }
      }
    }
    return arrayFrom(mapDefinedIterator(seenMap.keys(), (path) => {
      var _a;
      return ((_a = programOfThisState.getSourceFileByPath(path)) == null ? void 0 : _a.fileName) ?? path;
    }));
  }
  BuilderState2.getAllDependencies = getAllDependencies;
  function getAllFileNames(state, programOfThisState) {
    if (!state.allFileNames) {
      const sourceFiles = programOfThisState.getSourceFiles();
      state.allFileNames = sourceFiles === emptyArray ? emptyArray : sourceFiles.map((file) => file.fileName);
    }
    return state.allFileNames;
  }
  function getReferencedByPaths(state, referencedFilePath) {
    const keys = state.referencedMap.getKeys(referencedFilePath);
    return keys ? arrayFrom(keys.keys()) : [];
  }
  BuilderState2.getReferencedByPaths = getReferencedByPaths;
  function containsOnlyAmbientModules(sourceFile) {
    for (const statement of sourceFile.statements) {
      if (!isModuleWithStringLiteralName(statement)) {
        return false;
      }
    }
    return true;
  }
  function containsGlobalScopeAugmentation(sourceFile) {
    return some(sourceFile.moduleAugmentations, (augmentation) => isGlobalScopeAugmentation(augmentation.parent));
  }
  function isFileAffectingGlobalScope(sourceFile) {
    return containsGlobalScopeAugmentation(sourceFile) || !isExternalOrCommonJsModule(sourceFile) && !isJsonSourceFile(sourceFile) && !containsOnlyAmbientModules(sourceFile);
  }
  function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
    if (state.allFilesExcludingDefaultLibraryFile) {
      return state.allFilesExcludingDefaultLibraryFile;
    }
    let result;
    if (firstSourceFile)
      addSourceFile(firstSourceFile);
    for (const sourceFile of programOfThisState.getSourceFiles()) {
      if (sourceFile !== firstSourceFile) {
        addSourceFile(sourceFile);
      }
    }
    state.allFilesExcludingDefaultLibraryFile = result || emptyArray;
    return state.allFilesExcludingDefaultLibraryFile;
    function addSourceFile(sourceFile) {
      if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
        (result || (result = [])).push(sourceFile);
      }
    }
  }
  BuilderState2.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
  function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
    const compilerOptions = programOfThisState.getCompilerOptions();
    if (compilerOptions && outFile(compilerOptions)) {
      return [sourceFileWithUpdatedShape];
    }
    return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
  }
  function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cancellationToken, host) {
    if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
      return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
    }
    const compilerOptions = programOfThisState.getCompilerOptions();
    if (compilerOptions && (getIsolatedModules(compilerOptions) || outFile(compilerOptions))) {
      return [sourceFileWithUpdatedShape];
    }
    const seenFileNamesMap = /* @__PURE__ */ new Map();
    seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
    const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
    while (queue.length > 0) {
      const currentPath = queue.pop();
      if (!seenFileNamesMap.has(currentPath)) {
        const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
        seenFileNamesMap.set(currentPath, currentSourceFile);
        if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, host)) {
          queue.push(...getReferencedByPaths(state, currentSourceFile.resolvedPath));
        }
      }
    }
    return arrayFrom(mapDefinedIterator(seenFileNamesMap.values(), (value) => value));
  }
})(BuilderState || (BuilderState = {}));

// src/compiler/builder.ts
var BuilderFileEmit = /* @__PURE__ */ ((BuilderFileEmit2) => {
  BuilderFileEmit2[BuilderFileEmit2["None"] = 0] = "None";
  BuilderFileEmit2[BuilderFileEmit2["Js"] = 1] = "Js";
  BuilderFileEmit2[BuilderFileEmit2["JsMap"] = 2] = "JsMap";
  BuilderFileEmit2[BuilderFileEmit2["JsInlineMap"] = 4] = "JsInlineMap";
  BuilderFileEmit2[BuilderFileEmit2["Dts"] = 8] = "Dts";
  BuilderFileEmit2[BuilderFileEmit2["DtsMap"] = 16] = "DtsMap";
  BuilderFileEmit2[BuilderFileEmit2["AllJs"] = 7] = "AllJs";
  BuilderFileEmit2[BuilderFileEmit2["AllDts"] = 24] = "AllDts";
  BuilderFileEmit2[BuilderFileEmit2["All"] = 31] = "All";
  return BuilderFileEmit2;
})(BuilderFileEmit || {});
function getBuilderFileEmit(options) {
  let result = 1 /* Js */;
  if (options.sourceMap)
    result = result | 2 /* JsMap */;
  if (options.inlineSourceMap)
    result = result | 4 /* JsInlineMap */;
  if (getEmitDeclarations(options))
    result = result | 8 /* Dts */;
  if (options.declarationMap)
    result = result | 16 /* DtsMap */;
  if (options.emitDeclarationOnly)
    result = result & 24 /* AllDts */;
  return result;
}
function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) {
  const oldEmitKind = oldOptionsOrEmitKind && (isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind));
  const emitKind = isNumber(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind);
  if (oldEmitKind === emitKind)
    return 0 /* None */;
  if (!oldEmitKind || !emitKind)
    return emitKind;
  const diff = oldEmitKind ^ emitKind;
  let result = 0 /* None */;
  if (diff & 7 /* AllJs */)
    result = emitKind & 7 /* AllJs */;
  if (diff & 24 /* AllDts */)
    result = result | emitKind & 24 /* AllDts */;
  return result;
}
function hasSameKeys(map1, map2) {
  return map1 === map2 || map1 !== void 0 && map2 !== void 0 && map1.size === map2.size && !forEachKey(map1, (key) => !map2.has(key));
}
function createBuilderProgramState(newProgram, oldState) {
  var _a, _b;
  const state = BuilderState.create(
    newProgram,
    oldState,
    /*disableUseFileVersionAsSignature*/
    false
  );
  state.program = newProgram;
  const compilerOptions = newProgram.getCompilerOptions();
  state.compilerOptions = compilerOptions;
  const outFilePath = outFile(compilerOptions);
  if (!outFilePath) {
    state.semanticDiagnosticsPerFile = /* @__PURE__ */ new Map();
  } else if (compilerOptions.composite && (oldState == null ? void 0 : oldState.outSignature) && outFilePath === outFile(oldState == null ? void 0 : oldState.compilerOptions)) {
    state.outSignature = oldState.outSignature && getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldState.outSignature);
  }
  state.changedFilesSet = /* @__PURE__ */ new Set();
  state.latestChangedDtsFile = compilerOptions.composite ? oldState == null ? void 0 : oldState.latestChangedDtsFile : void 0;
  const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState);
  const oldCompilerOptions = useOldState ? oldState.compilerOptions : void 0;
  const canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
  const canCopyEmitSignatures = compilerOptions.composite && (oldState == null ? void 0 : oldState.emitSignatures) && !outFilePath && !compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions);
  if (useOldState) {
    (_a = oldState.changedFilesSet) == null ? void 0 : _a.forEach((value) => state.changedFilesSet.add(value));
    if (!outFilePath && ((_b = oldState.affectedFilesPendingEmit) == null ? void 0 : _b.size)) {
      state.affectedFilesPendingEmit = new Map(oldState.affectedFilesPendingEmit);
      state.seenAffectedFiles = /* @__PURE__ */ new Set();
    }
    state.programEmitPending = oldState.programEmitPending;
  } else {
    state.buildInfoEmitPending = true;
  }
  const referencedMap = state.referencedMap;
  const oldReferencedMap = useOldState ? oldState.referencedMap : void 0;
  const copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
  const copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
  state.fileInfos.forEach((info, sourceFilePath) => {
    let oldInfo;
    let newReferences;
    if (!useOldState || // File wasn't present in old state
    !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match
    oldInfo.version !== info.version || // Implied formats dont match
    oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed
    !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program
    newReferences && forEachKey(newReferences, (path) => !state.fileInfos.has(path) && oldState.fileInfos.has(path))) {
      addFileToChangeSet(state, sourceFilePath);
    } else if (canCopySemanticDiagnostics) {
      const sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
      if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics)
        return;
      if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics)
        return;
      const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
      if (diagnostics) {
        state.semanticDiagnosticsPerFile.set(
          sourceFilePath,
          oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram)
        );
        if (!state.semanticDiagnosticsFromOldState) {
          state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set();
        }
        state.semanticDiagnosticsFromOldState.add(sourceFilePath);
      }
    }
    if (canCopyEmitSignatures) {
      const oldEmitSignature = oldState.emitSignatures.get(sourceFilePath);
      if (oldEmitSignature) {
        (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature));
      }
    }
  });
  if (useOldState && forEachEntry(oldState.fileInfos, (info, sourceFilePath) => {
    if (state.fileInfos.has(sourceFilePath))
      return false;
    if (outFilePath || info.affectsGlobalScope)
      return true;
    state.buildInfoEmitPending = true;
    return false;
  })) {
    BuilderState.getAllFilesExcludingDefaultLibraryFile(
      state,
      newProgram,
      /*firstSourceFile*/
      void 0
    ).forEach((file) => addFileToChangeSet(state, file.resolvedPath));
  } else if (oldCompilerOptions) {
    const pendingEmitKind = compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions) ? getBuilderFileEmit(compilerOptions) : getPendingEmitKind(compilerOptions, oldCompilerOptions);
    if (pendingEmitKind !== 0 /* None */) {
      if (!outFilePath) {
        newProgram.getSourceFiles().forEach((f) => {
          if (!state.changedFilesSet.has(f.resolvedPath)) {
            addToAffectedFilesPendingEmit(
              state,
              f.resolvedPath,
              pendingEmitKind
            );
          }
        });
        Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
        state.seenAffectedFiles = state.seenAffectedFiles || /* @__PURE__ */ new Set();
        state.buildInfoEmitPending = true;
      } else {
        state.programEmitPending = state.programEmitPending ? state.programEmitPending | pendingEmitKind : pendingEmitKind;
      }
    }
  }
  if (outFilePath && !state.changedFilesSet.size) {
    if (useOldState)
      state.bundle = oldState.bundle;
    if (some(newProgram.getProjectReferences(), (ref) => !!ref.prepend))
      state.programEmitPending = getBuilderFileEmit(compilerOptions);
  }
  return state;
}
function addFileToChangeSet(state, path) {
  state.changedFilesSet.add(path);
  state.buildInfoEmitPending = true;
  state.programEmitPending = void 0;
}
function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) {
  return !!options.declarationMap === !!oldOptions.declarationMap ? (
    // Use same format of signature
    oldEmitSignature
  ) : (
    // Convert to different format
    isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0]
  );
}
function repopulateDiagnostics(diagnostics, newProgram) {
  if (!diagnostics.length)
    return diagnostics;
  return sameMap(diagnostics, (diag2) => {
    if (isString(diag2.messageText))
      return diag2;
    const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => {
      var _a;
      return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain);
    });
    return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain };
  });
}
function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) {
  const info = repopulateInfo(chain);
  if (info) {
    return {
      ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference),
      next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo)
    };
  }
  const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo);
  return next === chain.next ? chain : { ...chain, next };
}
function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) {
  return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo));
}
function convertToDiagnostics(diagnostics, newProgram) {
  if (!diagnostics.length)
    return emptyArray;
  let buildInfoDirectory;
  return diagnostics.map((diagnostic) => {
    const result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPathInBuildInfoDirectory);
    result.reportsUnnecessary = diagnostic.reportsUnnecessary;
    result.reportsDeprecated = diagnostic.reportDeprecated;
    result.source = diagnostic.source;
    result.skippedOn = diagnostic.skippedOn;
    const { relatedInformation } = diagnostic;
    result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) : [] : void 0;
    return result;
  });
  function toPathInBuildInfoDirectory(path) {
    buildInfoDirectory ?? (buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory())));
    return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName);
  }
}
function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) {
  const { file } = diagnostic;
  const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0;
  return {
    ...diagnostic,
    file: sourceFile,
    messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info)
  };
}
function releaseCache(state) {
  BuilderState.releaseCache(state);
  state.program = void 0;
}
function backupBuilderProgramEmitState(state) {
  const outFilePath = outFile(state.compilerOptions);
  Debug.assert(!state.changedFilesSet.size || outFilePath);
  return {
    affectedFilesPendingEmit: state.affectedFilesPendingEmit && new Map(state.affectedFilesPendingEmit),
    seenEmittedFiles: state.seenEmittedFiles && new Map(state.seenEmittedFiles),
    programEmitPending: state.programEmitPending,
    emitSignatures: state.emitSignatures && new Map(state.emitSignatures),
    outSignature: state.outSignature,
    latestChangedDtsFile: state.latestChangedDtsFile,
    hasChangedEmitSignature: state.hasChangedEmitSignature,
    changedFilesSet: outFilePath ? new Set(state.changedFilesSet) : void 0
  };
}
function restoreBuilderProgramEmitState(state, savedEmitState) {
  state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit;
  state.seenEmittedFiles = savedEmitState.seenEmittedFiles;
  state.programEmitPending = savedEmitState.programEmitPending;
  state.emitSignatures = savedEmitState.emitSignatures;
  state.outSignature = savedEmitState.outSignature;
  state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile;
  state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature;
  if (savedEmitState.changedFilesSet)
    state.changedFilesSet = savedEmitState.changedFilesSet;
}
function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
  Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
}
function getNextAffectedFile(state, cancellationToken, host) {
  var _a, _b;
  while (true) {
    const { affectedFiles } = state;
    if (affectedFiles) {
      const seenAffectedFiles = state.seenAffectedFiles;
      let affectedFilesIndex = state.affectedFilesIndex;
      while (affectedFilesIndex < affectedFiles.length) {
        const affectedFile = affectedFiles[affectedFilesIndex];
        if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
          state.affectedFilesIndex = affectedFilesIndex;
          addToAffectedFilesPendingEmit(state, affectedFile.resolvedPath, getBuilderFileEmit(state.compilerOptions));
          handleDtsMayChangeOfAffectedFile(
            state,
            affectedFile,
            cancellationToken,
            host
          );
          return affectedFile;
        }
        affectedFilesIndex++;
      }
      state.changedFilesSet.delete(state.currentChangedFilePath);
      state.currentChangedFilePath = void 0;
      (_a = state.oldSignatures) == null ? void 0 : _a.clear();
      (_b = state.oldExportedModulesMap) == null ? void 0 : _b.clear();
      state.affectedFiles = void 0;
    }
    const nextKey = state.changedFilesSet.keys().next();
    if (nextKey.done) {
      return void 0;
    }
    const program = Debug.checkDefined(state.program);
    const compilerOptions = program.getCompilerOptions();
    if (outFile(compilerOptions)) {
      Debug.assert(!state.semanticDiagnosticsPerFile);
      return program;
    }
    state.affectedFiles = BuilderState.getFilesAffectedByWithOldState(
      state,
      program,
      nextKey.value,
      cancellationToken,
      host
    );
    state.currentChangedFilePath = nextKey.value;
    state.affectedFilesIndex = 0;
    if (!state.seenAffectedFiles)
      state.seenAffectedFiles = /* @__PURE__ */ new Set();
  }
}
function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles) {
  var _a;
  if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size))
    return;
  if (!emitOnlyDtsFiles)
    return state.affectedFilesPendingEmit = void 0;
  state.affectedFilesPendingEmit.forEach((emitKind, path) => {
    const pending = emitKind & 7 /* AllJs */;
    if (!pending)
      state.affectedFilesPendingEmit.delete(path);
    else
      state.affectedFilesPendingEmit.set(path, pending);
  });
}
function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) {
  var _a;
  if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size))
    return void 0;
  return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path) => {
    var _a2;
    const affectedFile = state.program.getSourceFileByPath(path);
    if (!affectedFile || !sourceFileMayBeEmitted(affectedFile, state.program)) {
      state.affectedFilesPendingEmit.delete(path);
      return void 0;
    }
    const seenKind = (_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath);
    let pendingKind = getPendingEmitKind(emitKind, seenKind);
    if (emitOnlyDtsFiles)
      pendingKind = pendingKind & 24 /* AllDts */;
    if (pendingKind)
      return { affectedFile, emitKind: pendingKind };
  });
}
function removeDiagnosticsOfLibraryFiles(state) {
  if (!state.cleanedDiagnosticsOfLibFiles) {
    state.cleanedDiagnosticsOfLibFiles = true;
    const program = Debug.checkDefined(state.program);
    const options = program.getCompilerOptions();
    forEach(
      program.getSourceFiles(),
      (f) => program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)
    );
  }
}
function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, host) {
  removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
  if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
    removeDiagnosticsOfLibraryFiles(state);
    BuilderState.updateShapeSignature(
      state,
      Debug.checkDefined(state.program),
      affectedFile,
      cancellationToken,
      host
    );
    return;
  }
  if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies)
    return;
  handleDtsMayChangeOfReferencingExportOfAffectedFile(
    state,
    affectedFile,
    cancellationToken,
    host
  );
}
function handleDtsMayChangeOf(state, path, cancellationToken, host) {
  removeSemanticDiagnosticsOf(state, path);
  if (!state.changedFilesSet.has(path)) {
    const program = Debug.checkDefined(state.program);
    const sourceFile = program.getSourceFileByPath(path);
    if (sourceFile) {
      BuilderState.updateShapeSignature(
        state,
        program,
        sourceFile,
        cancellationToken,
        host,
        /*useFileVersionAsSignature*/
        true
      );
      if (getEmitDeclarations(state.compilerOptions)) {
        addToAffectedFilesPendingEmit(state, path, state.compilerOptions.declarationMap ? 24 /* AllDts */ : 8 /* Dts */);
      }
    }
  }
}
function removeSemanticDiagnosticsOf(state, path) {
  if (!state.semanticDiagnosticsFromOldState) {
    return true;
  }
  state.semanticDiagnosticsFromOldState.delete(path);
  state.semanticDiagnosticsPerFile.delete(path);
  return !state.semanticDiagnosticsFromOldState.size;
}
function isChangedSignature(state, path) {
  const oldSignature = Debug.checkDefined(state.oldSignatures).get(path) || void 0;
  const newSignature = Debug.checkDefined(state.fileInfos.get(path)).signature;
  return newSignature !== oldSignature;
}
function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host) {
  var _a;
  if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope))
    return false;
  BuilderState.getAllFilesExcludingDefaultLibraryFile(
    state,
    state.program,
    /*firstSourceFile*/
    void 0
  ).forEach((file) => handleDtsMayChangeOf(
    state,
    file.resolvedPath,
    cancellationToken,
    host
  ));
  removeDiagnosticsOfLibraryFiles(state);
  return true;
}
function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host) {
  var _a;
  if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath))
    return;
  if (!isChangedSignature(state, affectedFile.resolvedPath))
    return;
  if (getIsolatedModules(state.compilerOptions)) {
    const seenFileNamesMap = /* @__PURE__ */ new Map();
    seenFileNamesMap.set(affectedFile.resolvedPath, true);
    const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
    while (queue.length > 0) {
      const currentPath = queue.pop();
      if (!seenFileNamesMap.has(currentPath)) {
        seenFileNamesMap.set(currentPath, true);
        if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, host))
          return;
        handleDtsMayChangeOf(state, currentPath, cancellationToken, host);
        if (isChangedSignature(state, currentPath)) {
          const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
          queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
        }
      }
    }
  }
  const seenFileAndExportsOfFile = /* @__PURE__ */ new Set();
  (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _a.forEach((exportedFromPath) => {
    if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host))
      return true;
    const references = state.referencedMap.getKeys(exportedFromPath);
    return references && forEachKey(
      references,
      (filePath) => handleDtsMayChangeOfFileAndExportsOfFile(
        state,
        filePath,
        seenFileAndExportsOfFile,
        cancellationToken,
        host
      )
    );
  });
}
function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host) {
  var _a, _b;
  if (!tryAddToSet(seenFileAndExportsOfFile, filePath))
    return void 0;
  if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host))
    return true;
  handleDtsMayChangeOf(state, filePath, cancellationToken, host);
  (_a = state.exportedModulesMap.getKeys(filePath)) == null ? void 0 : _a.forEach(
    (exportedFromPath) => handleDtsMayChangeOfFileAndExportsOfFile(
      state,
      exportedFromPath,
      seenFileAndExportsOfFile,
      cancellationToken,
      host
    )
  );
  (_b = state.referencedMap.getKeys(filePath)) == null ? void 0 : _b.forEach(
    (referencingFilePath) => !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
    handleDtsMayChangeOf(
      // Dont add to seen since this is not yet done with the export removal
      state,
      referencingFilePath,
      cancellationToken,
      host
    )
  );
  return void 0;
}
function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
  return concatenate(
    getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken),
    Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile)
  );
}
function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
  const path = sourceFile.resolvedPath;
  if (state.semanticDiagnosticsPerFile) {
    const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
    if (cachedDiagnostics) {
      return filterSemanticDiagnostics(cachedDiagnostics, state.compilerOptions);
    }
  }
  const diagnostics = Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
  if (state.semanticDiagnosticsPerFile) {
    state.semanticDiagnosticsPerFile.set(path, diagnostics);
  }
  return filterSemanticDiagnostics(diagnostics, state.compilerOptions);
}
function isProgramBundleEmitBuildInfo(info) {
  return !!outFile(info.options || {});
}
function getBuildInfo2(state, bundle) {
  var _a, _b, _c;
  const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory();
  const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
  const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : void 0;
  const fileNames = [];
  const fileNameToFileId = /* @__PURE__ */ new Map();
  const root = [];
  if (outFile(state.compilerOptions)) {
    const fileInfos2 = arrayFrom(state.fileInfos.entries(), ([key, value]) => {
      const fileId = toFileId(key);
      tryAddRoot(key, fileId);
      return value.impliedFormat ? { version: value.version, impliedFormat: value.impliedFormat, signature: void 0, affectsGlobalScope: void 0 } : value.version;
    });
    const program2 = {
      fileNames,
      fileInfos: fileInfos2,
      root,
      options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions),
      outSignature: state.outSignature,
      latestChangedDtsFile,
      pendingEmit: !state.programEmitPending ? void 0 : (
        // Pending is undefined or None is encoded as undefined
        state.programEmitPending === getBuilderFileEmit(state.compilerOptions) ? false : (
          // Pending emit is same as deteremined by compilerOptions
          state.programEmitPending
        )
      )
      // Actual value
    };
    const { js, dts, commonSourceDirectory, sourceFiles } = bundle;
    state.bundle = bundle = {
      commonSourceDirectory,
      sourceFiles,
      js: js || (!state.compilerOptions.emitDeclarationOnly ? (_a = state.bundle) == null ? void 0 : _a.js : void 0),
      dts: dts || (getEmitDeclarations(state.compilerOptions) ? (_b = state.bundle) == null ? void 0 : _b.dts : void 0)
    };
    return createBuildInfo(program2, bundle);
  }
  let fileIdsList;
  let fileNamesToFileIdListId;
  let emitSignatures;
  const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]) => {
    var _a2, _b2;
    const fileId = toFileId(key);
    tryAddRoot(key, fileId);
    Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key));
    const oldSignature = (_a2 = state.oldSignatures) == null ? void 0 : _a2.get(key);
    const actualSignature = oldSignature !== void 0 ? oldSignature || void 0 : value.signature;
    if (state.compilerOptions.composite) {
      const file = state.program.getSourceFileByPath(key);
      if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program)) {
        const emitSignature = (_b2 = state.emitSignatures) == null ? void 0 : _b2.get(key);
        if (emitSignature !== actualSignature) {
          (emitSignatures || (emitSignatures = [])).push(emitSignature === void 0 ? fileId : (
            // There is no emit, encode as false
            // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature
            [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray : emitSignature]
          ));
        }
      }
    }
    return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? (
      // If file version is same as signature, dont serialize signature
      { version: value.version, signature: void 0, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }
    ) : (
      // If file info only contains version and signature and both are same we can just write string
      value.version
    ) : actualSignature !== void 0 ? (
      // If signature is not same as version, encode signature in the fileInfo
      oldSignature === void 0 ? (
        // If we havent computed signature, use fileInfo as is
        value
      ) : (
        // Serialize fileInfo with new updated signature
        { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }
      )
    ) : (
      // Signature of the FileInfo is undefined, serialize it as false
      { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }
    );
  });
  let referencedMap;
  if (state.referencedMap) {
    referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map((key) => [
      toFileId(key),
      toFileIdListId(state.referencedMap.getValues(key))
    ]);
  }
  let exportedModulesMap;
  if (state.exportedModulesMap) {
    exportedModulesMap = mapDefined(arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive), (key) => {
      var _a2;
      const oldValue = (_a2 = state.oldExportedModulesMap) == null ? void 0 : _a2.get(key);
      if (oldValue === void 0)
        return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))];
      if (oldValue)
        return [toFileId(key), toFileIdListId(oldValue)];
      return void 0;
    });
  }
  let semanticDiagnosticsPerFile;
  if (state.semanticDiagnosticsPerFile) {
    for (const key of arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) {
      const value = state.semanticDiagnosticsPerFile.get(key);
      (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(
        value.length ? [
          toFileId(key),
          convertToReusableDiagnostics(value, relativeToBuildInfo)
        ] : toFileId(key)
      );
    }
  }
  let affectedFilesPendingEmit;
  if ((_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.size) {
    const fullEmitForOptions = getBuilderFileEmit(state.compilerOptions);
    const seenFiles = /* @__PURE__ */ new Set();
    for (const path of arrayFrom(state.affectedFilesPendingEmit.keys()).sort(compareStringsCaseSensitive)) {
      if (tryAddToSet(seenFiles, path)) {
        const file = state.program.getSourceFileByPath(path);
        if (!file || !sourceFileMayBeEmitted(file, state.program))
          continue;
        const fileId = toFileId(path), pendingEmit = state.affectedFilesPendingEmit.get(path);
        (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(
          pendingEmit === fullEmitForOptions ? fileId : (
            // Pending full emit per options
            pendingEmit === 8 /* Dts */ ? [fileId] : (
              // Pending on Dts only
              [fileId, pendingEmit]
            )
          )
          // Anything else
        );
      }
    }
  }
  let changeFileSet;
  if (state.changedFilesSet.size) {
    for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) {
      (changeFileSet || (changeFileSet = [])).push(toFileId(path));
    }
  }
  const program = {
    fileNames,
    fileInfos,
    root,
    options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions),
    fileIdsList,
    referencedMap,
    exportedModulesMap,
    semanticDiagnosticsPerFile,
    affectedFilesPendingEmit,
    changeFileSet,
    emitSignatures,
    latestChangedDtsFile
  };
  return createBuildInfo(program, bundle);
  function relativeToBuildInfoEnsuringAbsolutePath(path) {
    return relativeToBuildInfo(getNormalizedAbsolutePath(path, currentDirectory));
  }
  function relativeToBuildInfo(path) {
    return ensurePathIsNonModuleName(getRelativePathFromDirectory(buildInfoDirectory, path, state.program.getCanonicalFileName));
  }
  function toFileId(path) {
    let fileId = fileNameToFileId.get(path);
    if (fileId === void 0) {
      fileNames.push(relativeToBuildInfo(path));
      fileNameToFileId.set(path, fileId = fileNames.length);
    }
    return fileId;
  }
  function toFileIdListId(set) {
    const fileIds = arrayFrom(set.keys(), toFileId).sort(compareValues);
    const key = fileIds.join();
    let fileIdListId = fileNamesToFileIdListId == null ? void 0 : fileNamesToFileIdListId.get(key);
    if (fileIdListId === void 0) {
      (fileIdsList || (fileIdsList = [])).push(fileIds);
      (fileNamesToFileIdListId || (fileNamesToFileIdListId = /* @__PURE__ */ new Map())).set(key, fileIdListId = fileIdsList.length);
    }
    return fileIdListId;
  }
  function tryAddRoot(path, fileId) {
    const file = state.program.getSourceFile(path);
    if (!state.program.getFileIncludeReasons().get(file.path).some((r) => r.kind === 0 /* RootFile */))
      return;
    if (!root.length)
      return root.push(fileId);
    const last2 = root[root.length - 1];
    const isLastStartEnd = isArray(last2);
    if (isLastStartEnd && last2[1] === fileId - 1)
      return last2[1] = fileId;
    if (isLastStartEnd || root.length === 1 || last2 !== fileId - 1)
      return root.push(fileId);
    const lastButOne = root[root.length - 2];
    if (!isNumber(lastButOne) || lastButOne !== last2 - 1)
      return root.push(fileId);
    root[root.length - 2] = [lastButOne, fileId];
    return root.length = root.length - 1;
  }
  function convertToProgramBuildInfoCompilerOptions(options) {
    let result;
    const { optionsNameMap } = getOptionsNameMap();
    for (const name of getOwnKeys(options).sort(compareStringsCaseSensitive)) {
      const optionInfo = optionsNameMap.get(name.toLowerCase());
      if (optionInfo == null ? void 0 : optionInfo.affectsBuildInfo) {
        (result || (result = {}))[name] = convertToReusableCompilerOptionValue(
          optionInfo,
          options[name],
          relativeToBuildInfoEnsuringAbsolutePath
        );
      }
    }
    return result;
  }
}
function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
  if (option) {
    Debug.assert(option.type !== "listOrElement");
    if (option.type === "list") {
      const values = value;
      if (option.element.isFilePath && values.length) {
        return values.map(relativeToBuildInfo);
      }
    } else if (option.isFilePath) {
      return relativeToBuildInfo(value);
    }
  }
  return value;
}
function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
  Debug.assert(!!diagnostics.length);
  return diagnostics.map((diagnostic) => {
    const result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
    result.reportsUnnecessary = diagnostic.reportsUnnecessary;
    result.reportDeprecated = diagnostic.reportsDeprecated;
    result.source = diagnostic.source;
    result.skippedOn = diagnostic.skippedOn;
    const { relatedInformation } = diagnostic;
    result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo)) : [] : void 0;
    return result;
  });
}
function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
  const { file } = diagnostic;
  return {
    ...diagnostic,
    file: file ? relativeToBuildInfo(file.resolvedPath) : void 0,
    messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText)
  };
}
function convertToReusableDiagnosticMessageChain(chain) {
  if (chain.repopulateInfo) {
    return {
      info: chain.repopulateInfo(),
      next: convertToReusableDiagnosticMessageChainArray(chain.next)
    };
  }
  const next = convertToReusableDiagnosticMessageChainArray(chain.next);
  return next === chain.next ? chain : { ...chain, next };
}
function convertToReusableDiagnosticMessageChainArray(array) {
  if (!array)
    return array;
  return forEach(array, (chain, index) => {
    const reusable = convertToReusableDiagnosticMessageChain(chain);
    if (chain === reusable)
      return void 0;
    const result = index > 0 ? array.slice(0, index - 1) : [];
    result.push(reusable);
    for (let i = index + 1; i < array.length; i++) {
      result.push(convertToReusableDiagnosticMessageChain(array[i]));
    }
    return result;
  }) || array;
}
var BuilderProgramKind = /* @__PURE__ */ ((BuilderProgramKind2) => {
  BuilderProgramKind2[BuilderProgramKind2["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
  BuilderProgramKind2[BuilderProgramKind2["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
  return BuilderProgramKind2;
})(BuilderProgramKind || {});
function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  let host;
  let newProgram;
  let oldProgram;
  if (newProgramOrRootNames === void 0) {
    Debug.assert(hostOrOptions === void 0);
    host = oldProgramOrHost;
    oldProgram = configFileParsingDiagnosticsOrOldProgram;
    Debug.assert(!!oldProgram);
    newProgram = oldProgram.getProgram();
  } else if (isArray(newProgramOrRootNames)) {
    oldProgram = configFileParsingDiagnosticsOrOldProgram;
    newProgram = createProgram({
      rootNames: newProgramOrRootNames,
      options: hostOrOptions,
      host: oldProgramOrHost,
      oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
      configFileParsingDiagnostics,
      projectReferences
    });
    host = oldProgramOrHost;
  } else {
    newProgram = newProgramOrRootNames;
    host = hostOrOptions;
    oldProgram = oldProgramOrHost;
    configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
  }
  return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray };
}
function getTextHandlingSourceMapForSignature(text, data) {
  return (data == null ? void 0 : data.sourceMapUrlPos) !== void 0 ? text.substring(0, data.sourceMapUrlPos) : text;
}
function computeSignatureWithDiagnostics(program, sourceFile, text, host, data) {
  var _a;
  text = getTextHandlingSourceMapForSignature(text, data);
  let sourceFileDirectory;
  if ((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length) {
    text += data.diagnostics.map(
      (diagnostic) => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`
    ).join("\n");
  }
  return (host.createHash ?? generateDjb2Hash)(text);
  function flattenDiagnosticMessageText2(diagnostic) {
    return isString(diagnostic) ? diagnostic : diagnostic === void 0 ? "" : !diagnostic.next ? diagnostic.messageText : diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText2).join("\n");
  }
  function locationInfo(diagnostic) {
    if (diagnostic.file.resolvedPath === sourceFile.resolvedPath)
      return `(${diagnostic.start},${diagnostic.length})`;
    if (sourceFileDirectory === void 0)
      sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath);
    return `${ensurePathIsNonModuleName(getRelativePathFromDirectory(
      sourceFileDirectory,
      diagnostic.file.resolvedPath,
      program.getCanonicalFileName
    ))}(${diagnostic.start},${diagnostic.length})`;
  }
}
function computeSignature(text, host, data) {
  return (host.createHash ?? generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data));
}
function createBuilderProgram(kind, { newProgram, host, oldProgram, configFileParsingDiagnostics }) {
  let oldState = oldProgram && oldProgram.getState();
  if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
    newProgram = void 0;
    oldState = void 0;
    return oldProgram;
  }
  const state = createBuilderProgramState(newProgram, oldState);
  newProgram.getBuildInfo = (bundle) => getBuildInfo2(state, bundle);
  newProgram = void 0;
  oldProgram = void 0;
  oldState = void 0;
  const getState = () => state;
  const builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics);
  builderProgram.getState = getState;
  builderProgram.saveEmitState = () => backupBuilderProgramEmitState(state);
  builderProgram.restoreEmitState = (saved) => restoreBuilderProgramEmitState(state, saved);
  builderProgram.hasChangedEmitSignature = () => !!state.hasChangedEmitSignature;
  builderProgram.getAllDependencies = (sourceFile) => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile);
  builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
  builderProgram.emit = emit;
  builderProgram.releaseProgram = () => releaseCache(state);
  if (kind === 0 /* SemanticDiagnosticsBuilderProgram */) {
    builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
  } else if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) {
    builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
    builderProgram.emitNextAffectedFile = emitNextAffectedFile;
    builderProgram.emitBuildInfo = emitBuildInfo;
  } else {
    notImplemented();
  }
  return builderProgram;
  function emitBuildInfo(writeFile2, cancellationToken) {
    if (state.buildInfoEmitPending) {
      const result = Debug.checkDefined(state.program).emitBuildInfo(writeFile2 || maybeBind(host, host.writeFile), cancellationToken);
      state.buildInfoEmitPending = false;
      return result;
    }
    return emitSkippedWithNoDiagnostics;
  }
  function emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) {
    var _a, _b, _c;
    let affected = getNextAffectedFile(state, cancellationToken, host);
    const programEmitKind = getBuilderFileEmit(state.compilerOptions);
    let emitKind = emitOnlyDtsFiles ? programEmitKind & 24 /* AllDts */ : programEmitKind;
    if (!affected) {
      if (!outFile(state.compilerOptions)) {
        const pendingAffectedFile = getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles);
        if (!pendingAffectedFile) {
          if (!state.buildInfoEmitPending)
            return void 0;
          const affected2 = state.program;
          const result2 = affected2.emitBuildInfo(writeFile2 || maybeBind(host, host.writeFile), cancellationToken);
          state.buildInfoEmitPending = false;
          return { result: result2, affected: affected2 };
        }
        ({ affectedFile: affected, emitKind } = pendingAffectedFile);
      } else {
        if (!state.programEmitPending)
          return void 0;
        emitKind = state.programEmitPending;
        if (emitOnlyDtsFiles)
          emitKind = emitKind & 24 /* AllDts */;
        if (!emitKind)
          return void 0;
        affected = state.program;
      }
    }
    let emitOnly;
    if (emitKind & 7 /* AllJs */)
      emitOnly = 0 /* Js */;
    if (emitKind & 24 /* AllDts */)
      emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0;
    if (affected === state.program) {
      state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? getPendingEmitKind(state.programEmitPending, emitKind) : void 0;
    }
    const result = state.program.emit(
      affected === state.program ? void 0 : affected,
      getWriteFileCallback(writeFile2, customTransformers),
      cancellationToken,
      emitOnly,
      customTransformers
    );
    if (affected !== state.program) {
      const affectedSourceFile = affected;
      state.seenAffectedFiles.add(affectedSourceFile.resolvedPath);
      if (state.affectedFilesIndex !== void 0)
        state.affectedFilesIndex++;
      state.buildInfoEmitPending = true;
      const existing = ((_a = state.seenEmittedFiles) == null ? void 0 : _a.get(affectedSourceFile.resolvedPath)) || 0 /* None */;
      (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, emitKind | existing);
      const existingPending = ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || programEmitKind;
      const pendingKind = getPendingEmitKind(existingPending, emitKind | existing);
      if (pendingKind)
        (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind);
      else
        (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath);
    } else {
      state.changedFilesSet.clear();
    }
    return { result, affected };
  }
  function getWriteFileCallback(writeFile2, customTransformers) {
    if (!getEmitDeclarations(state.compilerOptions))
      return writeFile2 || maybeBind(host, host.writeFile);
    return (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => {
      var _a, _b, _c, _d;
      if (isDeclarationFileName(fileName)) {
        if (!outFile(state.compilerOptions)) {
          Debug.assert((sourceFiles == null ? void 0 : sourceFiles.length) === 1);
          let emitSignature;
          if (!customTransformers) {
            const file = sourceFiles[0];
            const info = state.fileInfos.get(file.resolvedPath);
            if (info.signature === file.version) {
              const signature = computeSignatureWithDiagnostics(
                state.program,
                file,
                text,
                host,
                data
              );
              if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length))
                emitSignature = signature;
              if (signature !== file.version) {
                if (host.storeFilesChangingSignatureDuringEmit)
                  (state.filesChangingSignature ?? (state.filesChangingSignature = /* @__PURE__ */ new Set())).add(file.resolvedPath);
                if (state.exportedModulesMap)
                  BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit);
                if (state.affectedFiles) {
                  const existing = (_b = state.oldSignatures) == null ? void 0 : _b.get(file.resolvedPath);
                  if (existing === void 0)
                    (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false);
                  info.signature = signature;
                } else {
                  info.signature = signature;
                  (_c = state.oldExportedModulesMap) == null ? void 0 : _c.clear();
                }
              }
            }
          }
          if (state.compilerOptions.composite) {
            const filePath = sourceFiles[0].resolvedPath;
            emitSignature = handleNewSignature((_d = state.emitSignatures) == null ? void 0 : _d.get(filePath), emitSignature);
            if (!emitSignature)
              return;
            (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature);
          }
        } else if (state.compilerOptions.composite) {
          const newSignature = handleNewSignature(
            state.outSignature,
            /*newSignature*/
            void 0
          );
          if (!newSignature)
            return;
          state.outSignature = newSignature;
        }
      }
      if (writeFile2)
        writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
      else if (host.writeFile)
        host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
      else
        state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
      function handleNewSignature(oldSignatureFormat, newSignature) {
        const oldSignature = !oldSignatureFormat || isString(oldSignatureFormat) ? oldSignatureFormat : oldSignatureFormat[0];
        newSignature ?? (newSignature = computeSignature(text, host, data));
        if (newSignature === oldSignature) {
          if (oldSignatureFormat === oldSignature)
            return void 0;
          else if (data)
            data.differsOnlyInMap = true;
          else
            data = { differsOnlyInMap: true };
        } else {
          state.hasChangedEmitSignature = true;
          state.latestChangedDtsFile = fileName;
        }
        return newSignature;
      }
    };
  }
  function emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) {
    if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) {
      assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
    }
    const result = handleNoEmitOptions(builderProgram, targetSourceFile, writeFile2, cancellationToken);
    if (result)
      return result;
    if (!targetSourceFile) {
      if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) {
        let sourceMaps = [];
        let emitSkipped = false;
        let diagnostics;
        let emittedFiles = [];
        let affectedEmitResult;
        while (affectedEmitResult = emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
          emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
          diagnostics = addRange(diagnostics, affectedEmitResult.result.diagnostics);
          emittedFiles = addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
          sourceMaps = addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
        }
        return {
          emitSkipped,
          diagnostics: diagnostics || emptyArray,
          emittedFiles,
          sourceMaps
        };
      } else {
        clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles);
      }
    }
    return Debug.checkDefined(state.program).emit(
      targetSourceFile,
      getWriteFileCallback(writeFile2, customTransformers),
      cancellationToken,
      emitOnlyDtsFiles,
      customTransformers
    );
  }
  function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
    while (true) {
      const affected = getNextAffectedFile(state, cancellationToken, host);
      let result;
      if (!affected)
        return void 0;
      else if (affected !== state.program) {
        const affectedSourceFile = affected;
        if (!ignoreSourceFile || !ignoreSourceFile(affectedSourceFile)) {
          result = getSemanticDiagnosticsOfFile(state, affectedSourceFile, cancellationToken);
        }
        state.seenAffectedFiles.add(affectedSourceFile.resolvedPath);
        state.affectedFilesIndex++;
        state.buildInfoEmitPending = true;
        if (!result)
          continue;
      } else {
        result = state.program.getSemanticDiagnostics(
          /*sourceFile*/
          void 0,
          cancellationToken
        );
        state.changedFilesSet.clear();
        state.programEmitPending = getBuilderFileEmit(state.compilerOptions);
      }
      return { result, affected };
    }
  }
  function getSemanticDiagnostics(sourceFile, cancellationToken) {
    assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
    const compilerOptions = Debug.checkDefined(state.program).getCompilerOptions();
    if (outFile(compilerOptions)) {
      Debug.assert(!state.semanticDiagnosticsPerFile);
      return Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
    }
    if (sourceFile) {
      return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
    }
    while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
    }
    let diagnostics;
    for (const sourceFile2 of Debug.checkDefined(state.program).getSourceFiles()) {
      diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile2, cancellationToken));
    }
    return diagnostics || emptyArray;
  }
}
function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
  var _a;
  const existingKind = ((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.get(affectedFilePendingEmit)) || 0 /* None */;
  (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedFilePendingEmit, existingKind | kind);
}
function toBuilderStateFileInfoForMultiEmit(fileInfo) {
  return isString(fileInfo) ? { version: fileInfo, signature: fileInfo, affectsGlobalScope: void 0, impliedFormat: void 0 } : isString(fileInfo.signature) ? fileInfo : { version: fileInfo.version, signature: fileInfo.signature === false ? void 0 : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat };
}
function toBuilderFileEmit(value, fullEmitForOptions) {
  return isNumber(value) ? fullEmitForOptions : value[1] || 8 /* Dts */;
}
function toProgramEmitPending(value, options) {
  return !value ? getBuilderFileEmit(options || {}) : value;
}
function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host) {
  var _a, _b, _c, _d;
  const program = buildInfo.program;
  const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  let state;
  const filePaths = (_a = program.fileNames) == null ? void 0 : _a.map(toPathInBuildInfoDirectory);
  let filePathsSetList;
  const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : void 0;
  if (isProgramBundleEmitBuildInfo(program)) {
    const fileInfos = /* @__PURE__ */ new Map();
    program.fileInfos.forEach((fileInfo, index) => {
      const path = toFilePath(index + 1);
      fileInfos.set(path, isString(fileInfo) ? { version: fileInfo, signature: void 0, affectsGlobalScope: void 0, impliedFormat: void 0 } : fileInfo);
    });
    state = {
      fileInfos,
      compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {},
      latestChangedDtsFile,
      outSignature: program.outSignature,
      programEmitPending: program.pendingEmit === void 0 ? void 0 : toProgramEmitPending(program.pendingEmit, program.options),
      bundle: buildInfo.bundle
    };
  } else {
    filePathsSetList = (_b = program.fileIdsList) == null ? void 0 : _b.map((fileIds) => new Set(fileIds.map(toFilePath)));
    const fileInfos = /* @__PURE__ */ new Map();
    const emitSignatures = ((_c = program.options) == null ? void 0 : _c.composite) && !outFile(program.options) ? /* @__PURE__ */ new Map() : void 0;
    program.fileInfos.forEach((fileInfo, index) => {
      const path = toFilePath(index + 1);
      const stateFileInfo = toBuilderStateFileInfoForMultiEmit(fileInfo);
      fileInfos.set(path, stateFileInfo);
      if (emitSignatures && stateFileInfo.signature)
        emitSignatures.set(path, stateFileInfo.signature);
    });
    (_d = program.emitSignatures) == null ? void 0 : _d.forEach((value) => {
      if (isNumber(value))
        emitSignatures.delete(toFilePath(value));
      else {
        const key = toFilePath(value[0]);
        emitSignatures.set(
          key,
          !isString(value[1]) && !value[1].length ? (
            // File signature is emit signature but differs in map
            [emitSignatures.get(key)]
          ) : value[1]
        );
      }
    });
    const fullEmitForOptions = program.affectedFilesPendingEmit ? getBuilderFileEmit(program.options || {}) : void 0;
    state = {
      fileInfos,
      compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {},
      referencedMap: toManyToManyPathMap(program.referencedMap),
      exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap),
      semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => isNumber(value) ? emptyArray : value[1]),
      hasReusableDiagnostic: true,
      affectedFilesPendingEmit: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)),
      changedFilesSet: new Set(map(program.changeFileSet, toFilePath)),
      latestChangedDtsFile,
      emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0
    };
  }
  return {
    getState: () => state,
    saveEmitState: noop,
    restoreEmitState: noop,
    getProgram: notImplemented,
    getProgramOrUndefined: returnUndefined,
    releaseProgram: noop,
    getCompilerOptions: () => state.compilerOptions,
    getSourceFile: notImplemented,
    getSourceFiles: notImplemented,
    getOptionsDiagnostics: notImplemented,
    getGlobalDiagnostics: notImplemented,
    getConfigFileParsingDiagnostics: notImplemented,
    getSyntacticDiagnostics: notImplemented,
    getDeclarationDiagnostics: notImplemented,
    getSemanticDiagnostics: notImplemented,
    emit: notImplemented,
    getAllDependencies: notImplemented,
    getCurrentDirectory: notImplemented,
    emitNextAffectedFile: notImplemented,
    getSemanticDiagnosticsOfNextAffectedFile: notImplemented,
    emitBuildInfo: notImplemented,
    close: noop,
    hasChangedEmitSignature: returnFalse
  };
  function toPathInBuildInfoDirectory(path) {
    return toPath(path, buildInfoDirectory, getCanonicalFileName);
  }
  function toAbsolutePath(path) {
    return getNormalizedAbsolutePath(path, buildInfoDirectory);
  }
  function toFilePath(fileId) {
    return filePaths[fileId - 1];
  }
  function toFilePathsSet(fileIdsListId) {
    return filePathsSetList[fileIdsListId - 1];
  }
  function toManyToManyPathMap(referenceMap) {
    if (!referenceMap) {
      return void 0;
    }
    const map2 = BuilderState.createManyToManyPathMap();
    referenceMap.forEach(
      ([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId))
    );
    return map2;
  }
}
function getBuildInfoFileVersionMap(program, buildInfoPath, host) {
  const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  const fileInfos = /* @__PURE__ */ new Map();
  let rootIndex = 0;
  const roots = [];
  program.fileInfos.forEach((fileInfo, index) => {
    const path = toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName);
    const version2 = isString(fileInfo) ? fileInfo : fileInfo.version;
    fileInfos.set(path, version2);
    if (rootIndex < program.root.length) {
      const current = program.root[rootIndex];
      const fileId = index + 1;
      if (isArray(current)) {
        if (current[0] <= fileId && fileId <= current[1]) {
          roots.push(path);
          if (current[1] === fileId)
            rootIndex++;
        }
      } else if (current === fileId) {
        roots.push(path);
        rootIndex++;
      }
    }
  });
  return { fileInfos, roots };
}
function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) {
  return {
    getState: notImplemented,
    saveEmitState: noop,
    restoreEmitState: noop,
    getProgram,
    getProgramOrUndefined: () => getState().program,
    releaseProgram: () => getState().program = void 0,
    getCompilerOptions: () => getState().compilerOptions,
    getSourceFile: (fileName) => getProgram().getSourceFile(fileName),
    getSourceFiles: () => getProgram().getSourceFiles(),
    getOptionsDiagnostics: (cancellationToken) => getProgram().getOptionsDiagnostics(cancellationToken),
    getGlobalDiagnostics: (cancellationToken) => getProgram().getGlobalDiagnostics(cancellationToken),
    getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics,
    getSyntacticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken),
    getDeclarationDiagnostics: (sourceFile, cancellationToken) => getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken),
    getSemanticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSemanticDiagnostics(sourceFile, cancellationToken),
    emit: (sourceFile, writeFile2, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile2, cancellationToken, emitOnlyDts, customTransformers),
    emitBuildInfo: (writeFile2, cancellationToken) => getProgram().emitBuildInfo(writeFile2, cancellationToken),
    getAllDependencies: notImplemented,
    getCurrentDirectory: () => getProgram().getCurrentDirectory(),
    close: noop
  };
  function getProgram() {
    return Debug.checkDefined(getState().program);
  }
}

// src/compiler/builderPublic.ts
function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  return createBuilderProgram(0 /* SemanticDiagnosticsBuilderProgram */, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
}
function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  return createBuilderProgram(1 /* EmitAndSemanticDiagnosticsBuilderProgram */, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
}
function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
  const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences);
  return createRedirectedBuilderProgram(() => ({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }), newConfigFileParsingDiagnostics);
}

// src/compiler/resolutionCache.ts
function removeIgnoredPath(path) {
  if (endsWith(path, "/node_modules/.staging")) {
    return removeSuffix(path, "/.staging");
  }
  return some(ignoredPaths, (searchPath) => stringContains(path, searchPath)) ? void 0 : path;
}
function perceivedOsRootLengthForWatching(pathComponents2, length2) {
  if (length2 <= 1)
    return 1;
  let userCheckIndex = 1;
  let isDosStyle = pathComponents2[0].search(/[a-zA-Z]:/) === 0;
  if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths
  pathComponents2[1].search(/[a-zA-Z]\$$/) === 0) {
    if (length2 === 2)
      return 2;
    userCheckIndex = 2;
    isDosStyle = true;
  }
  if (isDosStyle && !pathComponents2[userCheckIndex].match(/^users$/i)) {
    return userCheckIndex;
  }
  return userCheckIndex + 2;
}
function canWatchDirectoryOrFile(pathComponents2, length2) {
  if (length2 === void 0)
    length2 = pathComponents2.length;
  if (length2 <= 2)
    return false;
  const perceivedOsRootLength = perceivedOsRootLengthForWatching(pathComponents2, length2);
  return length2 > perceivedOsRootLength + 1;
}
function canWatchAtTypes(atTypes) {
  return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes));
}
function isInDirectoryPath(dirComponents, fileOrDirComponents) {
  if (fileOrDirComponents.length < fileOrDirComponents.length)
    return false;
  for (let i = 0; i < dirComponents.length; i++) {
    if (fileOrDirComponents[i] !== dirComponents[i])
      return false;
  }
  return true;
}
function canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(fileOrDirPath) {
  return canWatchDirectoryOrFile(getPathComponents(fileOrDirPath));
}
function canWatchAffectingLocation(filePath) {
  return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(filePath);
}
function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory) {
  const failedLookupPathComponents = getPathComponents(failedLookupLocationPath);
  failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
  const failedLookupComponents = getPathComponents(failedLookupLocation);
  const perceivedOsRootLength = perceivedOsRootLengthForWatching(failedLookupPathComponents, failedLookupPathComponents.length);
  if (failedLookupPathComponents.length <= perceivedOsRootLength + 1)
    return void 0;
  const nodeModulesIndex = failedLookupPathComponents.indexOf("node_modules");
  if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1)
    return void 0;
  if (isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) {
    if (failedLookupPathComponents.length > rootPathComponents.length + 1) {
      return getDirectoryOfFailedLookupWatch(failedLookupComponents, failedLookupPathComponents, Math.max(rootPathComponents.length + 1, perceivedOsRootLength + 1));
    } else {
      return {
        dir: rootDir,
        dirPath: rootPath,
        nonRecursive: true
      };
    }
  }
  return getDirectoryToWatchFromFailedLookupLocationDirectory(
    failedLookupComponents,
    failedLookupPathComponents,
    failedLookupPathComponents.length - 1,
    perceivedOsRootLength,
    nodeModulesIndex,
    rootPathComponents
  );
}
function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dirPathComponents, dirPathComponentsLength, perceivedOsRootLength, nodeModulesIndex, rootPathComponents) {
  if (nodeModulesIndex !== -1) {
    return getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, nodeModulesIndex + 1);
  }
  let nonRecursive = true;
  let length2 = dirPathComponentsLength;
  for (let i = 0; i < dirPathComponentsLength; i++) {
    if (dirPathComponents[i] !== rootPathComponents[i]) {
      nonRecursive = false;
      length2 = Math.max(i + 1, perceivedOsRootLength + 1);
      break;
    }
  }
  return getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, length2, nonRecursive);
}
function getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, length2, nonRecursive) {
  return {
    dir: getPathFromPathComponents(dirComponents, length2),
    dirPath: getPathFromPathComponents(dirPathComponents, length2),
    nonRecursive
  };
}
function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, filterCustomPath) {
  const typeRootPathComponents = getPathComponents(typeRootPath);
  if (isInDirectoryPath(rootPathComponents, typeRootPathComponents)) {
    return rootPath;
  }
  typeRoot = isRootedDiskPath(typeRoot) ? normalizePath(typeRoot) : getNormalizedAbsolutePath(typeRoot, getCurrentDirectory());
  const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(
    getPathComponents(typeRoot),
    typeRootPathComponents,
    typeRootPathComponents.length,
    perceivedOsRootLengthForWatching(typeRootPathComponents, typeRootPathComponents.length),
    typeRootPathComponents.indexOf("node_modules"),
    rootPathComponents
  );
  return toWatch && filterCustomPath(toWatch.dirPath) ? toWatch.dirPath : void 0;
}
function getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory) {
  const normalized = getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory());
  return !isDiskPathRoot(normalized) ? removeTrailingDirectorySeparator(normalized) : normalized;
}
function getRootPathSplitLength(rootPath) {
  return rootPath.split(directorySeparator).length - (hasTrailingDirectorySeparator(rootPath) ? 1 : 0);
}
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
  let filesWithChangedSetOfUnresolvedImports;
  let filesWithInvalidatedResolutions;
  let filesWithInvalidatedNonRelativeUnresolvedImports;
  const nonRelativeExternalModuleResolutions = createMultiMap();
  const resolutionsWithFailedLookups = /* @__PURE__ */ new Set();
  const resolutionsWithOnlyAffectingLocations = /* @__PURE__ */ new Set();
  const resolvedFileToResolution = /* @__PURE__ */ new Map();
  const impliedFormatPackageJsons = /* @__PURE__ */ new Map();
  let hasChangedAutomaticTypeDirectiveNames = false;
  let affectingPathChecksForFile;
  let affectingPathChecks;
  let failedLookupChecks;
  let startsWithPathChecks;
  let isInDirectoryChecks;
  let allModuleAndTypeResolutionsAreInvalidated = false;
  const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory());
  const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
  const resolvedModuleNames = /* @__PURE__ */ new Map();
  const moduleResolutionCache = createModuleResolutionCache(
    getCurrentDirectory(),
    resolutionHost.getCanonicalFileName,
    resolutionHost.getCompilationSettings()
  );
  const resolvedTypeReferenceDirectives = /* @__PURE__ */ new Map();
  const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(
    getCurrentDirectory(),
    resolutionHost.getCanonicalFileName,
    resolutionHost.getCompilationSettings(),
    moduleResolutionCache.getPackageJsonInfoCache()
  );
  const resolvedLibraries = /* @__PURE__ */ new Map();
  const libraryResolutionCache = createModuleResolutionCache(
    getCurrentDirectory(),
    resolutionHost.getCanonicalFileName,
    getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()),
    moduleResolutionCache.getPackageJsonInfoCache()
  );
  const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map();
  const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map();
  const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory);
  const rootPath = resolutionHost.toPath(rootDir);
  const rootPathComponents = getPathComponents(rootPath);
  const typeRootsWatches = /* @__PURE__ */ new Map();
  return {
    getModuleResolutionCache: () => moduleResolutionCache,
    startRecordingFilesWithChangedResolutions,
    finishRecordingFilesWithChangedResolutions,
    // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
    // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
    startCachingPerDirectoryResolution,
    finishCachingPerDirectoryResolution,
    resolveModuleNameLiterals,
    resolveTypeReferenceDirectiveReferences,
    resolveLibrary: resolveLibrary2,
    resolveSingleModuleNameWithoutWatching,
    removeResolutionsFromProjectReferenceRedirects,
    removeResolutionsOfFile,
    hasChangedAutomaticTypeDirectiveNames: () => hasChangedAutomaticTypeDirectiveNames,
    invalidateResolutionOfFile,
    invalidateResolutionsOfFailedLookupLocations,
    setFilesWithInvalidatedNonRelativeUnresolvedImports,
    createHasInvalidatedResolutions,
    isFileWithInvalidatedNonRelativeUnresolvedImports,
    updateTypeRootsWatch,
    closeTypeRootsWatch,
    clear: clear2,
    onChangesAffectModuleResolution
  };
  function getResolvedModule2(resolution) {
    return resolution.resolvedModule;
  }
  function getResolvedTypeReferenceDirective2(resolution) {
    return resolution.resolvedTypeReferenceDirective;
  }
  function clear2() {
    clearMap(directoryWatchesOfFailedLookups, closeFileWatcherOf);
    clearMap(fileWatchesOfAffectingLocations, closeFileWatcherOf);
    nonRelativeExternalModuleResolutions.clear();
    closeTypeRootsWatch();
    resolvedModuleNames.clear();
    resolvedTypeReferenceDirectives.clear();
    resolvedFileToResolution.clear();
    resolutionsWithFailedLookups.clear();
    resolutionsWithOnlyAffectingLocations.clear();
    failedLookupChecks = void 0;
    startsWithPathChecks = void 0;
    isInDirectoryChecks = void 0;
    affectingPathChecks = void 0;
    affectingPathChecksForFile = void 0;
    allModuleAndTypeResolutionsAreInvalidated = false;
    moduleResolutionCache.clear();
    typeReferenceDirectiveResolutionCache.clear();
    moduleResolutionCache.update(resolutionHost.getCompilationSettings());
    typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings());
    libraryResolutionCache.clear();
    impliedFormatPackageJsons.clear();
    resolvedLibraries.clear();
    hasChangedAutomaticTypeDirectiveNames = false;
  }
  function onChangesAffectModuleResolution() {
    allModuleAndTypeResolutionsAreInvalidated = true;
    moduleResolutionCache.clearAllExceptPackageJsonInfoCache();
    typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache();
    moduleResolutionCache.update(resolutionHost.getCompilationSettings());
    typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings());
  }
  function startRecordingFilesWithChangedResolutions() {
    filesWithChangedSetOfUnresolvedImports = [];
  }
  function finishRecordingFilesWithChangedResolutions() {
    const collected = filesWithChangedSetOfUnresolvedImports;
    filesWithChangedSetOfUnresolvedImports = void 0;
    return collected;
  }
  function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
    if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
      return false;
    }
    const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
    return !!value && !!value.length;
  }
  function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) {
    invalidateResolutionsOfFailedLookupLocations();
    const collected = filesWithInvalidatedResolutions;
    filesWithInvalidatedResolutions = void 0;
    return {
      hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path),
      hasInvalidatedLibResolutions: (libFileName) => {
        var _a;
        return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated);
      }
    };
  }
  function startCachingPerDirectoryResolution() {
    moduleResolutionCache.clearAllExceptPackageJsonInfoCache();
    typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache();
    libraryResolutionCache.clearAllExceptPackageJsonInfoCache();
    nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
    nonRelativeExternalModuleResolutions.clear();
  }
  function cleanupLibResolutionWatching(newProgram) {
    resolvedLibraries.forEach((resolution, libFileName) => {
      var _a;
      if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) {
        stopWatchFailedLookupLocationOfResolution(
          resolution,
          resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)),
          getResolvedModule2
        );
        resolvedLibraries.delete(libFileName);
      }
    });
  }
  function finishCachingPerDirectoryResolution(newProgram, oldProgram) {
    filesWithInvalidatedNonRelativeUnresolvedImports = void 0;
    allModuleAndTypeResolutionsAreInvalidated = false;
    nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
    nonRelativeExternalModuleResolutions.clear();
    if (newProgram !== oldProgram) {
      cleanupLibResolutionWatching(newProgram);
      newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => {
        var _a;
        const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0;
        const existing = impliedFormatPackageJsons.get(newFile.path) ?? emptyArray;
        for (let i = existing.length; i < expected; i++) {
          createFileWatcherOfAffectingLocation(
            newFile.packageJsonLocations[i],
            /*forResolution*/
            false
          );
        }
        if (existing.length > expected) {
          for (let i = expected; i < existing.length; i++) {
            fileWatchesOfAffectingLocations.get(existing[i]).files--;
          }
        }
        if (expected)
          impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations);
        else
          impliedFormatPackageJsons.delete(newFile.path);
      });
      impliedFormatPackageJsons.forEach((existing, path) => {
        if (!(newProgram == null ? void 0 : newProgram.getSourceFileByPath(path))) {
          existing.forEach((location) => fileWatchesOfAffectingLocations.get(location).files--);
          impliedFormatPackageJsons.delete(path);
        }
      });
    }
    directoryWatchesOfFailedLookups.forEach((watcher, path) => {
      if (watcher.refCount === 0) {
        directoryWatchesOfFailedLookups.delete(path);
        watcher.watcher.close();
      }
    });
    fileWatchesOfAffectingLocations.forEach((watcher, path) => {
      if (watcher.files === 0 && watcher.resolutions === 0) {
        fileWatchesOfAffectingLocations.delete(path);
        watcher.watcher.close();
      }
    });
    hasChangedAutomaticTypeDirectiveNames = false;
  }
  function resolveModuleName2(moduleName, containingFile, compilerOptions, redirectedReference, mode) {
    var _a;
    const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost;
    const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
    if (!resolutionHost.getGlobalCache) {
      return primaryResult;
    }
    const globalCache = resolutionHost.getGlobalCache();
    if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) {
      const { resolvedModule, failedLookupLocations, affectingLocations, resolutionDiagnostics } = loadModuleFromGlobalCache(
        Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName),
        resolutionHost.projectName,
        compilerOptions,
        host,
        globalCache,
        moduleResolutionCache
      );
      if (resolvedModule) {
        primaryResult.resolvedModule = resolvedModule;
        primaryResult.failedLookupLocations = updateResolutionField(primaryResult.failedLookupLocations, failedLookupLocations);
        primaryResult.affectingLocations = updateResolutionField(primaryResult.affectingLocations, affectingLocations);
        primaryResult.resolutionDiagnostics = updateResolutionField(primaryResult.resolutionDiagnostics, resolutionDiagnostics);
        return primaryResult;
      }
    }
    return primaryResult;
  }
  function createModuleResolutionLoader2(containingFile, redirectedReference, options) {
    return {
      nameAndMode: moduleResolutionNameAndModeGetter,
      resolve: (moduleName, resoluionMode) => resolveModuleName2(
        moduleName,
        containingFile,
        options,
        redirectedReference,
        resoluionMode
      )
    };
  }
  function resolveNamesWithLocalCache({
    entries,
    containingFile,
    containingSourceFile,
    redirectedReference,
    options,
    perFileCache,
    reusedNames,
    loader,
    getResolutionWithResolvedFileName,
    deferWatchingNonRelativeResolution,
    shouldRetryResolution,
    logChanges
  }) {
    var _a;
    const path = resolutionHost.toPath(containingFile);
    const resolutionsInFile = perFileCache.get(path) || perFileCache.set(path, createModeAwareCache()).get(path);
    const resolvedModules = [];
    const hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
    const program = resolutionHost.getCurrentProgram();
    const oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
    const unmatchedRedirects = oldRedirect ? !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : !!redirectedReference;
    const seenNamesInFile = createModeAwareCache();
    for (const entry of entries) {
      const name = loader.nameAndMode.getName(entry);
      const mode = loader.nameAndMode.getMode(entry, containingSourceFile);
      let resolution = resolutionsInFile.get(name, mode);
      if (!seenNamesInFile.has(name, mode) && (allModuleAndTypeResolutionsAreInvalidated || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate
      hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
        const existingResolution = resolution;
        resolution = loader.resolve(name, mode);
        if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) {
          resolutionHost.onDiscoveredSymlink();
        }
        resolutionsInFile.set(name, mode, resolution);
        watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution);
        if (existingResolution) {
          stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
        }
        if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
          filesWithChangedSetOfUnresolvedImports.push(path);
          logChanges = false;
        }
      } else {
        const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost;
        if (isTraceEnabled(options, host) && !seenNamesInFile.has(name, mode)) {
          const resolved = getResolutionWithResolvedFileName(resolution);
          trace(
            host,
            perFileCache === resolvedModuleNames ? (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved : (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved,
            name,
            containingFile,
            resolved == null ? void 0 : resolved.resolvedFileName,
            (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId)
          );
        }
      }
      Debug.assert(resolution !== void 0 && !resolution.isInvalidated);
      seenNamesInFile.set(name, mode, true);
      resolvedModules.push(resolution);
    }
    reusedNames == null ? void 0 : reusedNames.forEach((entry) => seenNamesInFile.set(
      loader.nameAndMode.getName(entry),
      loader.nameAndMode.getMode(entry, containingSourceFile),
      true
    ));
    if (resolutionsInFile.size() !== seenNamesInFile.size()) {
      resolutionsInFile.forEach((resolution, name, mode) => {
        if (!seenNamesInFile.has(name, mode)) {
          stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
          resolutionsInFile.delete(name, mode);
        }
      });
    }
    return resolvedModules;
    function resolutionIsEqualTo(oldResolution, newResolution) {
      if (oldResolution === newResolution) {
        return true;
      }
      if (!oldResolution || !newResolution) {
        return false;
      }
      const oldResult = getResolutionWithResolvedFileName(oldResolution);
      const newResult = getResolutionWithResolvedFileName(newResolution);
      if (oldResult === newResult) {
        return true;
      }
      if (!oldResult || !newResult) {
        return false;
      }
      return oldResult.resolvedFileName === newResult.resolvedFileName;
    }
  }
  function resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) {
    var _a;
    return resolveNamesWithLocalCache({
      entries: typeDirectiveReferences,
      containingFile,
      containingSourceFile,
      redirectedReference,
      options,
      reusedNames,
      perFileCache: resolvedTypeReferenceDirectives,
      loader: createTypeReferenceResolutionLoader(
        containingFile,
        redirectedReference,
        options,
        ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost,
        typeReferenceDirectiveResolutionCache
      ),
      getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective2,
      shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0,
      deferWatchingNonRelativeResolution: false
    });
  }
  function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) {
    return resolveNamesWithLocalCache({
      entries: moduleLiterals,
      containingFile,
      containingSourceFile,
      redirectedReference,
      options,
      reusedNames,
      perFileCache: resolvedModuleNames,
      loader: createModuleResolutionLoader2(
        containingFile,
        redirectedReference,
        options
      ),
      getResolutionWithResolvedFileName: getResolvedModule2,
      shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension),
      logChanges: logChangesWhenResolvingModule,
      deferWatchingNonRelativeResolution: true
      // Defer non relative resolution watch because we could be using ambient modules
    });
  }
  function resolveLibrary2(libraryName, resolveFrom, options, libFileName) {
    var _a;
    const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost;
    let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName);
    if (!resolution || resolution.isInvalidated) {
      const existingResolution = resolution;
      resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache);
      const path = resolutionHost.toPath(resolveFrom);
      watchFailedLookupLocationsOfExternalModuleResolutions(
        libraryName,
        resolution,
        path,
        getResolvedModule2,
        /*deferWatchingNonRelativeResolution*/
        false
      );
      resolvedLibraries.set(libFileName, resolution);
      if (existingResolution) {
        stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2);
      }
    } else {
      if (isTraceEnabled(options, host)) {
        const resolved = getResolvedModule2(resolution);
        trace(
          host,
          (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved,
          libraryName,
          resolveFrom,
          resolved == null ? void 0 : resolved.resolvedFileName,
          (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId)
        );
      }
    }
    return resolution;
  }
  function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) {
    const path = resolutionHost.toPath(containingFile);
    const resolutionsInFile = resolvedModuleNames.get(path);
    const resolution = resolutionsInFile == null ? void 0 : resolutionsInFile.get(
      moduleName,
      /*mode*/
      void 0
    );
    if (resolution && !resolution.isInvalidated)
      return resolution;
    return resolveModuleName2(moduleName, containingFile, resolutionHost.getCompilationSettings());
  }
  function isNodeModulesAtTypesDirectory(dirPath) {
    return endsWith(dirPath, "/node_modules/@types");
  }
  function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) {
    var _a;
    if (resolution.refCount) {
      resolution.refCount++;
      Debug.assertIsDefined(resolution.files);
    } else {
      resolution.refCount = 1;
      Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size));
      if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) {
        watchFailedLookupLocationOfResolution(resolution);
      } else {
        nonRelativeExternalModuleResolutions.add(name, resolution);
      }
      const resolved = getResolutionWithResolvedFileName(resolution);
      if (resolved && resolved.resolvedFileName) {
        const key = resolutionHost.toPath(resolved.resolvedFileName);
        let resolutions = resolvedFileToResolution.get(key);
        if (!resolutions)
          resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set());
        resolutions.add(resolution);
      }
    }
    (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath);
  }
  function watchFailedLookupLocation(failedLookupLocation, setAtRoot) {
    const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
    const toWatch = getDirectoryToWatchFailedLookupLocation(
      failedLookupLocation,
      failedLookupLocationPath,
      rootDir,
      rootPath,
      rootPathComponents,
      getCurrentDirectory
    );
    if (toWatch) {
      const { dir, dirPath, nonRecursive } = toWatch;
      if (dirPath === rootPath) {
        Debug.assert(nonRecursive);
        setAtRoot = true;
      } else {
        setDirectoryWatcher(dir, dirPath, nonRecursive);
      }
    }
    return setAtRoot;
  }
  function watchFailedLookupLocationOfResolution(resolution) {
    Debug.assert(!!resolution.refCount);
    const { failedLookupLocations, affectingLocations, node10Result } = resolution;
    if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result)
      return;
    if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result)
      resolutionsWithFailedLookups.add(resolution);
    let setAtRoot = false;
    if (failedLookupLocations) {
      for (const failedLookupLocation of failedLookupLocations) {
        setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot);
      }
    }
    if (node10Result)
      setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot);
    if (setAtRoot) {
      setDirectoryWatcher(
        rootDir,
        rootPath,
        /*nonRecursive*/
        true
      );
    }
    watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result);
  }
  function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) {
    Debug.assert(!!resolution.refCount);
    const { affectingLocations } = resolution;
    if (!(affectingLocations == null ? void 0 : affectingLocations.length))
      return;
    if (addToResolutionsWithOnlyAffectingLocations)
      resolutionsWithOnlyAffectingLocations.add(resolution);
    for (const affectingLocation of affectingLocations) {
      createFileWatcherOfAffectingLocation(
        affectingLocation,
        /*forResolution*/
        true
      );
    }
  }
  function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) {
    const fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation);
    if (fileWatcher) {
      if (forResolution)
        fileWatcher.resolutions++;
      else
        fileWatcher.files++;
      return;
    }
    let locationToWatch = affectingLocation;
    if (resolutionHost.realpath) {
      locationToWatch = resolutionHost.realpath(affectingLocation);
      if (affectingLocation !== locationToWatch) {
        const fileWatcher2 = fileWatchesOfAffectingLocations.get(locationToWatch);
        if (fileWatcher2) {
          if (forResolution)
            fileWatcher2.resolutions++;
          else
            fileWatcher2.files++;
          fileWatcher2.paths.add(affectingLocation);
          fileWatchesOfAffectingLocations.set(affectingLocation, fileWatcher2);
          return;
        }
      }
    }
    const paths = /* @__PURE__ */ new Set();
    paths.add(locationToWatch);
    let actualWatcher = canWatchAffectingLocation(resolutionHost.toPath(locationToWatch)) ? resolutionHost.watchAffectingFileLocation(locationToWatch, (fileName, eventKind) => {
      cachedDirectoryStructureHost == null ? void 0 : cachedDirectoryStructureHost.addOrDeleteFile(fileName, resolutionHost.toPath(locationToWatch), eventKind);
      const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap();
      paths.forEach((path) => {
        if (watcher.resolutions)
          (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path);
        if (watcher.files)
          (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path);
        packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path));
      });
      resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
    }) : noopFileWatcher;
    const watcher = {
      watcher: actualWatcher !== noopFileWatcher ? {
        close: () => {
          actualWatcher.close();
          actualWatcher = noopFileWatcher;
        }
      } : actualWatcher,
      resolutions: forResolution ? 1 : 0,
      files: forResolution ? 0 : 1,
      paths
    };
    fileWatchesOfAffectingLocations.set(locationToWatch, watcher);
    if (affectingLocation !== locationToWatch) {
      fileWatchesOfAffectingLocations.set(affectingLocation, watcher);
      paths.add(affectingLocation);
    }
  }
  function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
    const program = resolutionHost.getCurrentProgram();
    if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
      resolutions.forEach(watchFailedLookupLocationOfResolution);
    } else {
      resolutions.forEach((resolution) => watchAffectingLocationsOfResolution(
        resolution,
        /*addToResolutionsWithOnlyAffectingLocations*/
        true
      ));
    }
  }
  function setDirectoryWatcher(dir, dirPath, nonRecursive) {
    const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
    if (dirWatcher) {
      Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
      dirWatcher.refCount++;
    } else {
      directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive });
    }
  }
  function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) {
    const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
    const toWatch = getDirectoryToWatchFailedLookupLocation(
      failedLookupLocation,
      failedLookupLocationPath,
      rootDir,
      rootPath,
      rootPathComponents,
      getCurrentDirectory
    );
    if (toWatch) {
      const { dirPath } = toWatch;
      if (dirPath === rootPath) {
        removeAtRoot = true;
      } else {
        removeDirectoryWatcher(dirPath);
      }
    }
    return removeAtRoot;
  }
  function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
    Debug.checkDefined(resolution.files).delete(filePath);
    resolution.refCount--;
    if (resolution.refCount) {
      return;
    }
    const resolved = getResolutionWithResolvedFileName(resolution);
    if (resolved && resolved.resolvedFileName) {
      const key = resolutionHost.toPath(resolved.resolvedFileName);
      const resolutions = resolvedFileToResolution.get(key);
      if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size)
        resolvedFileToResolution.delete(key);
    }
    const { failedLookupLocations, affectingLocations, node10Result } = resolution;
    if (resolutionsWithFailedLookups.delete(resolution)) {
      let removeAtRoot = false;
      if (failedLookupLocations) {
        for (const failedLookupLocation of failedLookupLocations) {
          removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot);
        }
      }
      if (node10Result)
        removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot);
      if (removeAtRoot)
        removeDirectoryWatcher(rootPath);
    } else if (affectingLocations == null ? void 0 : affectingLocations.length) {
      resolutionsWithOnlyAffectingLocations.delete(resolution);
    }
    if (affectingLocations) {
      for (const affectingLocation of affectingLocations) {
        const watcher = fileWatchesOfAffectingLocations.get(affectingLocation);
        watcher.resolutions--;
      }
    }
  }
  function removeDirectoryWatcher(dirPath) {
    const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
    dirWatcher.refCount--;
  }
  function createDirectoryWatcher(directory, dirPath, nonRecursive) {
    return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, (fileOrDirectory) => {
      const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
      if (cachedDirectoryStructureHost) {
        cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
      }
      scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
    }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
  }
  function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
    const resolutions = cache.get(filePath);
    if (resolutions) {
      resolutions.forEach((resolution) => stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName));
      cache.delete(filePath);
    }
  }
  function removeResolutionsFromProjectReferenceRedirects(filePath) {
    if (!fileExtensionIs(filePath, ".json" /* Json */))
      return;
    const program = resolutionHost.getCurrentProgram();
    if (!program)
      return;
    const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
    if (!resolvedProjectReference)
      return;
    resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f)));
  }
  function removeResolutionsOfFile(filePath) {
    removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule2);
    removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective2);
  }
  function invalidateResolutions(resolutions, canInvalidate) {
    if (!resolutions)
      return false;
    let invalidated = false;
    resolutions.forEach((resolution) => {
      if (resolution.isInvalidated || !canInvalidate(resolution))
        return;
      resolution.isInvalidated = invalidated = true;
      for (const containingFilePath of Debug.checkDefined(resolution.files)) {
        (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(containingFilePath);
        hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile);
      }
    });
    return invalidated;
  }
  function invalidateResolutionOfFile(filePath) {
    removeResolutionsOfFile(filePath);
    const prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
    if (invalidateResolutions(resolvedFileToResolution.get(filePath), returnTrue) && hasChangedAutomaticTypeDirectiveNames && !prevHasChangedAutomaticTypeDirectiveNames) {
      resolutionHost.onChangedAutomaticTypeDirectiveNames();
    }
  }
  function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
    Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === void 0);
    filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
  }
  function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
    if (isCreatingWatchedDirectory) {
      (isInDirectoryChecks || (isInDirectoryChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath);
    } else {
      const updatedPath = removeIgnoredPath(fileOrDirectoryPath);
      if (!updatedPath)
        return false;
      fileOrDirectoryPath = updatedPath;
      if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
        return false;
      }
      const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath);
      if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) {
        (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath);
        (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath);
      } else {
        if (isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
          return false;
        }
        if (fileExtensionIs(fileOrDirectoryPath, ".map")) {
          return false;
        }
        (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath);
        const packagePath = parseNodeModuleFromPath(
          fileOrDirectoryPath,
          /*isFolder*/
          true
        );
        if (packagePath)
          (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath);
      }
    }
    resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
  }
  function invalidatePackageJsonMap() {
    const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap();
    if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) {
      packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0);
    }
  }
  function invalidateResolutionsOfFailedLookupLocations() {
    var _a;
    if (allModuleAndTypeResolutionsAreInvalidated) {
      affectingPathChecksForFile = void 0;
      invalidatePackageJsonMap();
      if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) {
        invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution);
      }
      failedLookupChecks = void 0;
      startsWithPathChecks = void 0;
      isInDirectoryChecks = void 0;
      affectingPathChecks = void 0;
      return true;
    }
    let invalidated = false;
    if (affectingPathChecksForFile) {
      (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => {
        if (some(f.packageJsonLocations, (location) => affectingPathChecksForFile.has(location))) {
          (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(f.path);
          invalidated = true;
        }
      });
      affectingPathChecksForFile = void 0;
    }
    if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks && !affectingPathChecks) {
      return invalidated;
    }
    invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated;
    invalidatePackageJsonMap();
    failedLookupChecks = void 0;
    startsWithPathChecks = void 0;
    isInDirectoryChecks = void 0;
    invalidated = invalidateResolutions(resolutionsWithOnlyAffectingLocations, canInvalidatedFailedLookupResolutionWithAffectingLocation) || invalidated;
    affectingPathChecks = void 0;
    return invalidated;
  }
  function canInvalidateFailedLookupResolution(resolution) {
    var _a;
    if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution))
      return true;
    if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks)
      return false;
    return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result));
  }
  function isInvalidatedFailedLookup(locationPath) {
    return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0);
  }
  function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) {
    var _a;
    return !!affectingPathChecks && ((_a = resolution.affectingLocations) == null ? void 0 : _a.some((location) => affectingPathChecks.has(location)));
  }
  function closeTypeRootsWatch() {
    clearMap(typeRootsWatches, closeFileWatcher);
  }
  function createTypeRootsWatch(typeRootPath, typeRoot) {
    return canWatchTypeRootPath(typeRootPath) ? resolutionHost.watchTypeRootsDirectory(typeRoot, (fileOrDirectory) => {
      const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
      if (cachedDirectoryStructureHost) {
        cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
      }
      hasChangedAutomaticTypeDirectiveNames = true;
      resolutionHost.onChangedAutomaticTypeDirectiveNames();
      const dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(
        typeRoot,
        typeRootPath,
        rootPath,
        rootPathComponents,
        getCurrentDirectory,
        (dirPath2) => directoryWatchesOfFailedLookups.has(dirPath2)
      );
      if (dirPath) {
        scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
      }
    }, 1 /* Recursive */) : noopFileWatcher;
  }
  function updateTypeRootsWatch() {
    const options = resolutionHost.getCompilationSettings();
    if (options.types) {
      closeTypeRootsWatch();
      return;
    }
    const typeRoots = getEffectiveTypeRoots(options, { getCurrentDirectory });
    if (typeRoots) {
      mutateMap(
        typeRootsWatches,
        arrayToMap(typeRoots, (tr) => resolutionHost.toPath(tr)),
        {
          createNewValue: createTypeRootsWatch,
          onDeleteValue: closeFileWatcher
        }
      );
    } else {
      closeTypeRootsWatch();
    }
  }
  function canWatchTypeRootPath(typeRoot) {
    if (resolutionHost.getCompilationSettings().typeRoots)
      return true;
    return canWatchAtTypes(resolutionHost.toPath(typeRoot));
  }
}
function resolutionIsSymlink(resolution) {
  var _a, _b;
  return !!(((_a = resolution.resolvedModule) == null ? void 0 : _a.originalPath) || ((_b = resolution.resolvedTypeReferenceDirective) == null ? void 0 : _b.originalPath));
}

// src/compiler/watch.ts
var sysFormatDiagnosticsHost = sys ? {
  getCurrentDirectory: () => sys.getCurrentDirectory(),
  getNewLine: () => sys.newLine,
  getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames)
} : void 0;
function createDiagnosticReporter(system, pretty) {
  const host = system === sys && sysFormatDiagnosticsHost ? sysFormatDiagnosticsHost : {
    getCurrentDirectory: () => system.getCurrentDirectory(),
    getNewLine: () => system.newLine,
    getCanonicalFileName: createGetCanonicalFileName(system.useCaseSensitiveFileNames)
  };
  if (!pretty) {
    return (diagnostic) => system.write(formatDiagnostic(diagnostic, host));
  }
  const diagnostics = new Array(1);
  return (diagnostic) => {
    diagnostics[0] = diagnostic;
    system.write(formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
    diagnostics[0] = void 0;
  };
}
function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
  if (system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && contains(screenStartingMessageCodes, diagnostic.code)) {
    system.clearScreen();
    return true;
  }
  return false;
}
var screenStartingMessageCodes = [
  Diagnostics.Starting_compilation_in_watch_mode.code,
  Diagnostics.File_change_detected_Starting_incremental_compilation.code
];
function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
  return contains(screenStartingMessageCodes, diagnostic.code) ? newLine + newLine : newLine;
}
function getLocaleTimeString(system) {
  return !system.now ? (/* @__PURE__ */ new Date()).toLocaleTimeString() : (
    // On some systems / builds of Node, there's a non-breaking space between the time and AM/PM.
    // This branch is solely for testing, so just switch it to a normal space for baseline stability.
    // See:
    //     - https://github.com/nodejs/node/issues/45171
    //     - https://github.com/nodejs/node/issues/45753
    system.now().toLocaleTimeString("en-US", { timeZone: "UTC" }).replace("\u202F", " ")
  );
}
function createWatchStatusReporter(system, pretty) {
  return pretty ? (diagnostic, newLine, options) => {
    clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
    let output = `[${formatColorAndReset(getLocaleTimeString(system), "\x1B[90m" /* Grey */)}] `;
    output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${newLine + newLine}`;
    system.write(output);
  } : (diagnostic, newLine, options) => {
    let output = "";
    if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
      output += newLine;
    }
    output += `${getLocaleTimeString(system)} - `;
    output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${getPlainDiagnosticFollowingNewLines(diagnostic, newLine)}`;
    system.write(output);
  };
}
function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) {
  const host = system;
  host.onUnRecoverableConfigFileDiagnostic = (diagnostic) => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic);
  const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend);
  host.onUnRecoverableConfigFileDiagnostic = void 0;
  return result;
}
function getErrorCountForSummary(diagnostics) {
  return countWhere(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */);
}
function getFilesInErrorForSummary(diagnostics) {
  const filesInError = filter(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */).map(
    (errorDiagnostic) => {
      if (errorDiagnostic.file === void 0)
        return;
      return `${errorDiagnostic.file.fileName}`;
    }
  );
  return filesInError.map((fileName) => {
    if (fileName === void 0) {
      return void 0;
    }
    const diagnosticForFileName = find(
      diagnostics,
      (diagnostic) => diagnostic.file !== void 0 && diagnostic.file.fileName === fileName
    );
    if (diagnosticForFileName !== void 0) {
      const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start);
      return {
        fileName,
        line: line + 1
      };
    }
  });
}
function getWatchErrorSummaryDiagnosticMessage(errorCount) {
  return errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes;
}
function prettyPathForFileError(error, cwd) {
  const line = formatColorAndReset(":" + error.line, "\x1B[90m" /* Grey */);
  if (pathIsAbsolute(error.fileName) && pathIsAbsolute(cwd)) {
    return getRelativePathFromDirectory(
      cwd,
      error.fileName,
      /*ignoreCase*/
      false
    ) + line;
  }
  return error.fileName + line;
}
function getErrorSummaryText(errorCount, filesInError, newLine, host) {
  if (errorCount === 0)
    return "";
  const nonNilFiles = filesInError.filter((fileInError) => fileInError !== void 0);
  const distinctFileNamesWithLines = nonNilFiles.map((fileInError) => `${fileInError.fileName}:${fileInError.line}`).filter((value, index, self) => self.indexOf(value) === index);
  const firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory());
  let messageAndArgs;
  if (errorCount === 1) {
    messageAndArgs = filesInError[0] !== void 0 ? [Diagnostics.Found_1_error_in_0, firstFileReference] : [Diagnostics.Found_1_error];
  } else {
    messageAndArgs = distinctFileNamesWithLines.length === 0 ? [Diagnostics.Found_0_errors, errorCount] : distinctFileNamesWithLines.length === 1 ? [Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1, errorCount, firstFileReference] : [Diagnostics.Found_0_errors_in_1_files, errorCount, distinctFileNamesWithLines.length];
  }
  const d = createCompilerDiagnostic(...messageAndArgs);
  const suffix = distinctFileNamesWithLines.length > 1 ? createTabularErrorsDisplay(nonNilFiles, host) : "";
  return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}${suffix}`;
}
function createTabularErrorsDisplay(filesInError, host) {
  const distinctFiles = filesInError.filter((value, index, self) => index === self.findIndex((file) => (file == null ? void 0 : file.fileName) === (value == null ? void 0 : value.fileName)));
  if (distinctFiles.length === 0)
    return "";
  const numberLength = (num) => Math.log(num) * Math.LOG10E + 1;
  const fileToErrorCount = distinctFiles.map((file) => [file, countWhere(filesInError, (fileInError) => fileInError.fileName === file.fileName)]);
  const maxErrors = fileToErrorCount.reduce((acc, value) => Math.max(acc, value[1] || 0), 0);
  const headerRow = Diagnostics.Errors_Files.message;
  const leftColumnHeadingLength = headerRow.split(" ")[0].length;
  const leftPaddingGoal = Math.max(leftColumnHeadingLength, numberLength(maxErrors));
  const headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0);
  let tabularData = "";
  tabularData += " ".repeat(headerPadding) + headerRow + "\n";
  fileToErrorCount.forEach((row) => {
    const [file, errorCount] = row;
    const errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0;
    const leftPadding = errorCountDigitsLength < leftPaddingGoal ? " ".repeat(leftPaddingGoal - errorCountDigitsLength) : "";
    const fileRef = prettyPathForFileError(file, host.getCurrentDirectory());
    tabularData += `${leftPadding}${errorCount}  ${fileRef}
`;
  });
  return tabularData;
}
function isBuilderProgram2(program) {
  return !!program.getState;
}
function listFiles(program, write) {
  const options = program.getCompilerOptions();
  if (options.explainFiles) {
    explainFiles(isBuilderProgram2(program) ? program.getProgram() : program, write);
  } else if (options.listFiles || options.listFilesOnly) {
    forEach(program.getSourceFiles(), (file) => {
      write(file.fileName);
    });
  }
}
function explainFiles(program, write) {
  var _a, _b;
  const reasons = program.getFileIncludeReasons();
  const relativeFileName = (fileName) => convertToRelativePath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName);
  for (const file of program.getSourceFiles()) {
    write(`${toFileName(file, relativeFileName)}`);
    (_a = reasons.get(file.path)) == null ? void 0 : _a.forEach((reason) => write(`  ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`));
    (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) == null ? void 0 : _b.forEach((d) => write(`  ${d.messageText}`));
  }
}
function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) {
  var _a;
  let result;
  if (file.path !== file.resolvedPath) {
    (result ?? (result = [])).push(chainDiagnosticMessages(
      /*details*/
      void 0,
      Diagnostics.File_is_output_of_project_reference_source_0,
      toFileName(file.originalFileName, fileNameConvertor)
    ));
  }
  if (file.redirectInfo) {
    (result ?? (result = [])).push(chainDiagnosticMessages(
      /*details*/
      void 0,
      Diagnostics.File_redirects_to_file_0,
      toFileName(file.redirectInfo.redirectTarget, fileNameConvertor)
    ));
  }
  if (isExternalOrCommonJsModule(file)) {
    switch (file.impliedNodeFormat) {
      case 99 /* ESNext */:
        if (file.packageJsonScope) {
          (result ?? (result = [])).push(chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module,
            toFileName(last(file.packageJsonLocations), fileNameConvertor)
          ));
        }
        break;
      case 1 /* CommonJS */:
        if (file.packageJsonScope) {
          (result ?? (result = [])).push(chainDiagnosticMessages(
            /*details*/
            void 0,
            file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type,
            toFileName(last(file.packageJsonLocations), fileNameConvertor)
          ));
        } else if ((_a = file.packageJsonLocations) == null ? void 0 : _a.length) {
          (result ?? (result = [])).push(chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found
          ));
        }
        break;
    }
  }
  return result;
}
function getMatchedFileSpec(program, fileName) {
  var _a;
  const configFile = program.getCompilerOptions().configFile;
  if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec))
    return void 0;
  const filePath = program.getCanonicalFileName(fileName);
  const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
  return find(configFile.configFileSpecs.validatedFilesSpec, (fileSpec) => program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath);
}
function getMatchedIncludeSpec(program, fileName) {
  var _a, _b;
  const configFile = program.getCompilerOptions().configFile;
  if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs))
    return void 0;
  if (configFile.configFileSpecs.isDefaultIncludeSpec)
    return true;
  const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */);
  const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
  const useCaseSensitiveFileNames = program.useCaseSensitiveFileNames();
  return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => {
    if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */))
      return false;
    const pattern = getPatternFromSpec(includeSpec, basePath, "files");
    return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames).test(fileName);
  });
}
function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) {
  var _a, _b;
  const options = program.getCompilerOptions();
  if (isReferencedFile(reason)) {
    const referenceLocation = getReferencedFileLocation((path) => program.getSourceFileByPath(path), reason);
    const referenceText = isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : `"${referenceLocation.text}"`;
    let message;
    Debug.assert(isReferenceFileLocation(referenceLocation) || reason.kind === 3 /* Import */, "Only synthetic references are imports");
    switch (reason.kind) {
      case 3 /* Import */:
        if (isReferenceFileLocation(referenceLocation)) {
          message = referenceLocation.packageId ? Diagnostics.Imported_via_0_from_file_1_with_packageId_2 : Diagnostics.Imported_via_0_from_file_1;
        } else if (referenceLocation.text === externalHelpersModuleNameText) {
          message = referenceLocation.packageId ? Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions : Diagnostics.Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions;
        } else {
          message = referenceLocation.packageId ? Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions : Diagnostics.Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions;
        }
        break;
      case 4 /* ReferenceFile */:
        Debug.assert(!referenceLocation.packageId);
        message = Diagnostics.Referenced_via_0_from_file_1;
        break;
      case 5 /* TypeReferenceDirective */:
        message = referenceLocation.packageId ? Diagnostics.Type_library_referenced_via_0_from_file_1_with_packageId_2 : Diagnostics.Type_library_referenced_via_0_from_file_1;
        break;
      case 7 /* LibReferenceDirective */:
        Debug.assert(!referenceLocation.packageId);
        message = Diagnostics.Library_referenced_via_0_from_file_1;
        break;
      default:
        Debug.assertNever(reason);
    }
    return chainDiagnosticMessages(
      /*details*/
      void 0,
      message,
      referenceText,
      toFileName(referenceLocation.file, fileNameConvertor),
      referenceLocation.packageId && packageIdToString(referenceLocation.packageId)
    );
  }
  switch (reason.kind) {
    case 0 /* RootFile */:
      if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs))
        return chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Root_file_specified_for_compilation
        );
      const fileName = getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory());
      const matchedByFiles = getMatchedFileSpec(program, fileName);
      if (matchedByFiles)
        return chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Part_of_files_list_in_tsconfig_json
        );
      const matchedByInclude = getMatchedIncludeSpec(program, fileName);
      return isString(matchedByInclude) ? chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics.Matched_by_include_pattern_0_in_1,
        matchedByInclude,
        toFileName(options.configFile, fileNameConvertor)
      ) : (
        // Could be additional files specified as roots or matched by default include
        chainDiagnosticMessages(
          /*details*/
          void 0,
          matchedByInclude ? Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : Diagnostics.Root_file_specified_for_compilation
        )
      );
    case 1 /* SourceFromProjectReference */:
    case 2 /* OutputFromProjectReference */:
      const isOutput = reason.kind === 2 /* OutputFromProjectReference */;
      const referencedResolvedRef = Debug.checkDefined((_b = program.getResolvedProjectReferences()) == null ? void 0 : _b[reason.index]);
      return chainDiagnosticMessages(
        /*details*/
        void 0,
        outFile(options) ? isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_1_specified : Diagnostics.Source_from_referenced_project_0_included_because_1_specified : isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none,
        toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor),
        options.outFile ? "--outFile" : "--out"
      );
    case 8 /* AutomaticTypeDirectiveFile */: {
      const messageAndArgs = options.types ? reason.packageId ? [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, reason.typeReference] : reason.packageId ? [Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference];
      return chainDiagnosticMessages(
        /*details*/
        void 0,
        ...messageAndArgs
      );
    }
    case 6 /* LibFile */: {
      if (reason.index !== void 0)
        return chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Library_0_specified_in_compilerOptions,
          options.lib[reason.index]
        );
      const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === getEmitScriptTarget(options) ? key : void 0);
      const messageAndArgs = target ? [Diagnostics.Default_library_for_target_0, target] : [Diagnostics.Default_library];
      return chainDiagnosticMessages(
        /*details*/
        void 0,
        ...messageAndArgs
      );
    }
    default:
      Debug.assertNever(reason);
  }
}
function toFileName(file, fileNameConvertor) {
  const fileName = isString(file) ? file : file.fileName;
  return fileNameConvertor ? fileNameConvertor(fileName) : fileName;
}
function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  const isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
  const allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
  const configFileParsingDiagnosticsLength = allDiagnostics.length;
  addRange(allDiagnostics, program.getSyntacticDiagnostics(
    /*sourceFile*/
    void 0,
    cancellationToken
  ));
  if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
    addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
    if (!isListFilesOnly) {
      addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
      if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
        addRange(allDiagnostics, program.getSemanticDiagnostics(
          /*sourceFile*/
          void 0,
          cancellationToken
        ));
      }
    }
  }
  const emitResult = isListFilesOnly ? { emitSkipped: true, diagnostics: emptyArray } : program.emit(
    /*targetSourceFile*/
    void 0,
    writeFile2,
    cancellationToken,
    emitOnlyDtsFiles,
    customTransformers
  );
  const { emittedFiles, diagnostics: emitDiagnostics } = emitResult;
  addRange(allDiagnostics, emitDiagnostics);
  const diagnostics = sortAndDeduplicateDiagnostics(allDiagnostics);
  diagnostics.forEach(reportDiagnostic);
  if (write) {
    const currentDir = program.getCurrentDirectory();
    forEach(emittedFiles, (file) => {
      const filepath = getNormalizedAbsolutePath(file, currentDir);
      write(`TSFILE: ${filepath}`);
    });
    listFiles(program, write);
  }
  if (reportSummary) {
    reportSummary(getErrorCountForSummary(diagnostics), getFilesInErrorForSummary(diagnostics));
  }
  return {
    emitResult,
    diagnostics
  };
}
function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) {
  const { emitResult, diagnostics } = emitFilesAndReportErrors(
    program,
    reportDiagnostic,
    write,
    reportSummary,
    writeFile2,
    cancellationToken,
    emitOnlyDtsFiles,
    customTransformers
  );
  if (emitResult.emitSkipped && diagnostics.length > 0) {
    return 1 /* DiagnosticsPresent_OutputsSkipped */;
  } else if (diagnostics.length > 0) {
    return 2 /* DiagnosticsPresent_OutputsGenerated */;
  }
  return 0 /* Success */;
}
var noopFileWatcher = { close: noop };
var returnNoopFileWatcher = () => noopFileWatcher;
function createWatchHost(system = sys, reportWatchStatus2) {
  const onWatchStatusChange = reportWatchStatus2 || createWatchStatusReporter(system);
  return {
    onWatchStatusChange,
    watchFile: maybeBind(system, system.watchFile) || returnNoopFileWatcher,
    watchDirectory: maybeBind(system, system.watchDirectory) || returnNoopFileWatcher,
    setTimeout: maybeBind(system, system.setTimeout) || noop,
    clearTimeout: maybeBind(system, system.clearTimeout) || noop
  };
}
var WatchType = {
  ConfigFile: "Config file",
  ExtendedConfigFile: "Extended config file",
  SourceFile: "Source file",
  MissingFile: "Missing file",
  WildcardDirectory: "Wild card directory",
  FailedLookupLocations: "Failed Lookup Locations",
  AffectingFileLocation: "File location affecting resolution",
  TypeRoots: "Type roots",
  ConfigFileOfReferencedProject: "Config file of referened project",
  ExtendedConfigOfReferencedProject: "Extended config file of referenced project",
  WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project",
  PackageJson: "package.json file",
  ClosedScriptInfo: "Closed Script info",
  ConfigFileForInferredRoot: "Config file for the inferred project root",
  NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache",
  MissingSourceMapFile: "Missing source map file",
  NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root",
  MissingGeneratedFile: "Missing generated file",
  NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation",
  TypingInstallerLocationFile: "File location for typing installer",
  TypingInstallerLocationDirectory: "Directory location for typing installer"
};
function createWatchFactory(host, options) {
  const watchLogLevel = host.trace ? options.extendedDiagnostics ? 2 /* Verbose */ : options.diagnostics ? 1 /* TriggerOnly */ : 0 /* None */ : 0 /* None */;
  const writeLog = watchLogLevel !== 0 /* None */ ? (s) => host.trace(s) : noop;
  const result = getWatchFactory(host, watchLogLevel, writeLog);
  result.writeLog = writeLog;
  return result;
}
function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) {
  const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
  const compilerHost = {
    getSourceFile: createGetSourceFile(
      (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding),
      getCompilerOptions,
      /*setParentNodes*/
      void 0
    ),
    getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation),
    getDefaultLibFileName: (options) => host.getDefaultLibFileName(options),
    writeFile: createWriteFileMeasuringIO(
      (path, data, writeByteOrderMark) => host.writeFile(path, data, writeByteOrderMark),
      (path) => host.createDirectory(path),
      (path) => host.directoryExists(path)
    ),
    getCurrentDirectory: memoize(() => host.getCurrentDirectory()),
    useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
    getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames),
    getNewLine: () => getNewLineCharacter(getCompilerOptions()),
    fileExists: (f) => host.fileExists(f),
    readFile: (f) => host.readFile(f),
    trace: maybeBind(host, host.trace),
    directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
    getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
    realpath: maybeBind(host, host.realpath),
    getEnvironmentVariable: maybeBind(host, host.getEnvironmentVariable) || (() => ""),
    createHash: maybeBind(host, host.createHash),
    readDirectory: maybeBind(host, host.readDirectory),
    storeFilesChangingSignatureDuringEmit: host.storeFilesChangingSignatureDuringEmit
  };
  return compilerHost;
}
function getSourceFileVersionAsHashFromText(host, text) {
  if (text.match(sourceMapCommentRegExpDontCareLineStart)) {
    let lineEnd = text.length;
    let lineStart = lineEnd;
    for (let pos = lineEnd - 1; pos >= 0; pos--) {
      const ch = text.charCodeAt(pos);
      switch (ch) {
        case 10 /* lineFeed */:
          if (pos && text.charCodeAt(pos - 1) === 13 /* carriageReturn */) {
            pos--;
          }
        case 13 /* carriageReturn */:
          break;
        default:
          if (ch < 127 /* maxAsciiCharacter */ || !isLineBreak(ch)) {
            lineStart = pos;
            continue;
          }
          break;
      }
      const line = text.substring(lineStart, lineEnd);
      if (line.match(sourceMapCommentRegExp)) {
        text = text.substring(0, lineStart);
        break;
      } else if (!line.match(whitespaceOrMapCommentRegExp)) {
        break;
      }
      lineEnd = lineStart;
    }
  }
  return (host.createHash || generateDjb2Hash)(text);
}
function setGetSourceFileAsHashVersioned(compilerHost) {
  const originalGetSourceFile = compilerHost.getSourceFile;
  compilerHost.getSourceFile = (...args) => {
    const result = originalGetSourceFile.call(compilerHost, ...args);
    if (result) {
      result.version = getSourceFileVersionAsHashFromText(compilerHost, result.text);
    }
    return result;
  };
}
function createProgramHost(system, createProgram2) {
  const getDefaultLibLocation = memoize(() => getDirectoryPath(normalizePath(system.getExecutingFilePath())));
  return {
    useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames,
    getNewLine: () => system.newLine,
    getCurrentDirectory: memoize(() => system.getCurrentDirectory()),
    getDefaultLibLocation,
    getDefaultLibFileName: (options) => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)),
    fileExists: (path) => system.fileExists(path),
    readFile: (path, encoding) => system.readFile(path, encoding),
    directoryExists: (path) => system.directoryExists(path),
    getDirectories: (path) => system.getDirectories(path),
    readDirectory: (path, extensions, exclude, include, depth) => system.readDirectory(path, extensions, exclude, include, depth),
    realpath: maybeBind(system, system.realpath),
    getEnvironmentVariable: maybeBind(system, system.getEnvironmentVariable),
    trace: (s) => system.write(s + system.newLine),
    createDirectory: (path) => system.createDirectory(path),
    writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark),
    createHash: maybeBind(system, system.createHash),
    createProgram: createProgram2 || createEmitAndSemanticDiagnosticsBuilderProgram,
    storeFilesChangingSignatureDuringEmit: system.storeFilesChangingSignatureDuringEmit,
    now: maybeBind(system, system.now)
  };
}
function createWatchCompilerHost(system = sys, createProgram2, reportDiagnostic, reportWatchStatus2) {
  const write = (s) => system.write(s + system.newLine);
  const result = createProgramHost(system, createProgram2);
  copyProperties(result, createWatchHost(system, reportWatchStatus2));
  result.afterProgramCreate = (builderProgram) => {
    const compilerOptions = builderProgram.getCompilerOptions();
    const newLine = getNewLineCharacter(compilerOptions);
    emitFilesAndReportErrors(
      builderProgram,
      reportDiagnostic,
      write,
      (errorCount) => result.onWatchStatusChange(
        createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount),
        newLine,
        compilerOptions,
        errorCount
      )
    );
  };
  return result;
}
function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
  reportDiagnostic(diagnostic);
  system.exit(1 /* DiagnosticsPresent_OutputsSkipped */);
}
function createWatchCompilerHostOfConfigFile({
  configFileName,
  optionsToExtend,
  watchOptionsToExtend,
  extraFileExtensions,
  system,
  createProgram: createProgram2,
  reportDiagnostic,
  reportWatchStatus: reportWatchStatus2
}) {
  const diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
  const host = createWatchCompilerHost(system, createProgram2, diagnosticReporter, reportWatchStatus2);
  host.onUnRecoverableConfigFileDiagnostic = (diagnostic) => reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic);
  host.configFileName = configFileName;
  host.optionsToExtend = optionsToExtend;
  host.watchOptionsToExtend = watchOptionsToExtend;
  host.extraFileExtensions = extraFileExtensions;
  return host;
}
function createWatchCompilerHostOfFilesAndCompilerOptions({
  rootFiles,
  options,
  watchOptions,
  projectReferences,
  system,
  createProgram: createProgram2,
  reportDiagnostic,
  reportWatchStatus: reportWatchStatus2
}) {
  const host = createWatchCompilerHost(system, createProgram2, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus2);
  host.rootFiles = rootFiles;
  host.options = options;
  host.watchOptions = watchOptions;
  host.projectReferences = projectReferences;
  return host;
}
function performIncrementalCompilation(input) {
  const system = input.system || sys;
  const host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
  const builderProgram = createIncrementalProgram(input);
  const exitStatus = emitFilesAndReportErrorsAndGetExitStatus(
    builderProgram,
    input.reportDiagnostic || createDiagnosticReporter(system),
    (s) => host.trace && host.trace(s),
    input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : void 0
  );
  if (input.afterProgramEmitAndDiagnostics)
    input.afterProgramEmitAndDiagnostics(builderProgram);
  return exitStatus;
}

// src/compiler/watchPublic.ts
function readBuilderProgram(compilerOptions, host) {
  const buildInfoPath = getTsBuildInfoEmitOutputFilePath(compilerOptions);
  if (!buildInfoPath)
    return void 0;
  let buildInfo;
  if (host.getBuildInfo) {
    buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath);
  } else {
    const content = host.readFile(buildInfoPath);
    if (!content)
      return void 0;
    buildInfo = getBuildInfo(buildInfoPath, content);
  }
  if (!buildInfo || buildInfo.version !== version || !buildInfo.program)
    return void 0;
  return createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host);
}
function createIncrementalCompilerHost(options, system = sys) {
  const host = createCompilerHostWorker(
    options,
    /*setParentNodes*/
    void 0,
    system
  );
  host.createHash = maybeBind(system, system.createHash);
  host.storeFilesChangingSignatureDuringEmit = system.storeFilesChangingSignatureDuringEmit;
  setGetSourceFileAsHashVersioned(host);
  changeCompilerHostLikeToUseCache(host, (fileName) => toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName));
  return host;
}
function createIncrementalProgram({
  rootNames,
  options,
  configFileParsingDiagnostics,
  projectReferences,
  host,
  createProgram: createProgram2
}) {
  host = host || createIncrementalCompilerHost(options);
  createProgram2 = createProgram2 || createEmitAndSemanticDiagnosticsBuilderProgram;
  const oldProgram = readBuilderProgram(options, host);
  return createProgram2(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
}
function createWatchCompilerHost2(rootFilesOrConfigFileName, options, system, createProgram2, reportDiagnostic, reportWatchStatus2, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
  if (isArray(rootFilesOrConfigFileName)) {
    return createWatchCompilerHostOfFilesAndCompilerOptions({
      rootFiles: rootFilesOrConfigFileName,
      options,
      watchOptions: watchOptionsOrExtraFileExtensions,
      projectReferences: projectReferencesOrWatchOptionsToExtend,
      system,
      createProgram: createProgram2,
      reportDiagnostic,
      reportWatchStatus: reportWatchStatus2
    });
  } else {
    return createWatchCompilerHostOfConfigFile({
      configFileName: rootFilesOrConfigFileName,
      optionsToExtend: options,
      watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
      extraFileExtensions: watchOptionsOrExtraFileExtensions,
      system,
      createProgram: createProgram2,
      reportDiagnostic,
      reportWatchStatus: reportWatchStatus2
    });
  }
}
function createWatchProgram(host) {
  let builderProgram;
  let reloadLevel;
  let missingFilesMap;
  let watchedWildcardDirectories;
  let timerToUpdateProgram;
  let timerToInvalidateFailedLookupResolutions;
  let parsedConfigs;
  let sharedExtendedConfigFileWatchers;
  let extendedConfigCache = host.extendedConfigCache;
  let reportFileChangeDetectedOnCreateProgram = false;
  const sourceFilesCache = /* @__PURE__ */ new Map();
  let missingFilePathsRequestedForRelease;
  let hasChangedCompilerOptions = false;
  const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
  const currentDirectory = host.getCurrentDirectory();
  const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host;
  let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host;
  let wildcardDirectories;
  let configFileParsingDiagnostics;
  let canConfigFileJsonReportNoInputFiles = false;
  let hasChangedConfigFileParsingErrors = false;
  const cachedDirectoryStructureHost = configFileName === void 0 ? void 0 : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
  const directoryStructureHost = cachedDirectoryStructureHost || host;
  const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
  let newLine = updateNewLine();
  if (configFileName && host.configFileParsingResult) {
    setConfigFileParsingResult(host.configFileParsingResult);
    newLine = updateNewLine();
  }
  reportWatchDiagnostic(Diagnostics.Starting_compilation_in_watch_mode);
  if (configFileName && !host.configFileParsingResult) {
    newLine = getNewLineCharacter(optionsToExtendForConfigFile);
    Debug.assert(!rootFileNames);
    parseConfigFile2();
    newLine = updateNewLine();
  }
  Debug.assert(compilerOptions);
  Debug.assert(rootFileNames);
  const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions);
  const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
  writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`);
  let configFileWatcher;
  if (configFileName) {
    configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile);
  }
  const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost);
  setGetSourceFileAsHashVersioned(compilerHost);
  const getNewSourceFile = compilerHost.getSourceFile;
  compilerHost.getSourceFile = (fileName, ...args) => getVersionedSourceFileByPath(fileName, toPath3(fileName), ...args);
  compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
  compilerHost.getNewLine = () => newLine;
  compilerHost.fileExists = fileExists;
  compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
  compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine;
  compilerHost.toPath = toPath3;
  compilerHost.getCompilationSettings = () => compilerOptions;
  compilerHost.useSourceOfProjectReferenceRedirect = maybeBind(host, host.useSourceOfProjectReferenceRedirect);
  compilerHost.watchDirectoryOfFailedLookupLocation = (dir, cb, flags) => watchDirectory(dir, cb, flags, watchOptions, WatchType.FailedLookupLocations);
  compilerHost.watchAffectingFileLocation = (file, cb) => watchFile2(file, cb, 2e3 /* High */, watchOptions, WatchType.AffectingFileLocation);
  compilerHost.watchTypeRootsDirectory = (dir, cb, flags) => watchDirectory(dir, cb, flags, watchOptions, WatchType.TypeRoots);
  compilerHost.getCachedDirectoryStructureHost = () => cachedDirectoryStructureHost;
  compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
  compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
  compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
  compilerHost.fileIsOpen = returnFalse;
  compilerHost.getCurrentProgram = getCurrentProgram;
  compilerHost.writeLog = writeLog;
  compilerHost.getParsedCommandLine = getParsedCommandLine;
  const resolutionCache = createResolutionCache(
    compilerHost,
    configFileName ? getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory,
    /*logChangesWhenResolvingModule*/
    false
  );
  compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals);
  compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames);
  if (!compilerHost.resolveModuleNameLiterals && !compilerHost.resolveModuleNames) {
    compilerHost.resolveModuleNameLiterals = resolutionCache.resolveModuleNameLiterals.bind(resolutionCache);
  }
  compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences);
  compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives);
  if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) {
    compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache);
  }
  compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host);
  compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : () => resolutionCache.getModuleResolutionCache();
  const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
  const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse;
  const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse;
  builderProgram = readBuilderProgram(compilerOptions, compilerHost);
  synchronizeProgram();
  watchConfigFileWildCardDirectories();
  if (configFileName)
    updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile);
  return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close };
  function close() {
    clearInvalidateResolutionsOfFailedLookupLocations();
    resolutionCache.clear();
    clearMap(sourceFilesCache, (value) => {
      if (value && value.fileWatcher) {
        value.fileWatcher.close();
        value.fileWatcher = void 0;
      }
    });
    if (configFileWatcher) {
      configFileWatcher.close();
      configFileWatcher = void 0;
    }
    extendedConfigCache == null ? void 0 : extendedConfigCache.clear();
    extendedConfigCache = void 0;
    if (sharedExtendedConfigFileWatchers) {
      clearMap(sharedExtendedConfigFileWatchers, closeFileWatcherOf);
      sharedExtendedConfigFileWatchers = void 0;
    }
    if (watchedWildcardDirectories) {
      clearMap(watchedWildcardDirectories, closeFileWatcherOf);
      watchedWildcardDirectories = void 0;
    }
    if (missingFilesMap) {
      clearMap(missingFilesMap, closeFileWatcher);
      missingFilesMap = void 0;
    }
    if (parsedConfigs) {
      clearMap(parsedConfigs, (config) => {
        var _a;
        (_a = config.watcher) == null ? void 0 : _a.close();
        config.watcher = void 0;
        if (config.watchedDirectories)
          clearMap(config.watchedDirectories, closeFileWatcherOf);
        config.watchedDirectories = void 0;
      });
      parsedConfigs = void 0;
    }
  }
  function getCurrentBuilderProgram() {
    return builderProgram;
  }
  function getCurrentProgram() {
    return builderProgram && builderProgram.getProgramOrUndefined();
  }
  function synchronizeProgram() {
    writeLog(`Synchronizing program`);
    Debug.assert(compilerOptions);
    Debug.assert(rootFileNames);
    clearInvalidateResolutionsOfFailedLookupLocations();
    const program = getCurrentBuilderProgram();
    if (hasChangedCompilerOptions) {
      newLine = updateNewLine();
      if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
        debugger;
        resolutionCache.onChangesAffectModuleResolution();
      }
    }
    const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions);
    const {
      originalReadFile,
      originalFileExists,
      originalDirectoryExists,
      originalCreateDirectory,
      originalWriteFile,
      readFileWithCache
    } = changeCompilerHostLikeToUseCache(compilerHost, toPath3);
    if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) {
      if (hasChangedConfigFileParsingErrors) {
        if (reportFileChangeDetectedOnCreateProgram) {
          reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation);
        }
        builderProgram = createProgram2(
          /*rootNames*/
          void 0,
          /*options*/
          void 0,
          compilerHost,
          builderProgram,
          configFileParsingDiagnostics,
          projectReferences
        );
        hasChangedConfigFileParsingErrors = false;
      }
    } else {
      if (reportFileChangeDetectedOnCreateProgram) {
        reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation);
      }
      createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions);
    }
    reportFileChangeDetectedOnCreateProgram = false;
    if (host.afterProgramCreate && program !== builderProgram) {
      host.afterProgramCreate(builderProgram);
    }
    compilerHost.readFile = originalReadFile;
    compilerHost.fileExists = originalFileExists;
    compilerHost.directoryExists = originalDirectoryExists;
    compilerHost.createDirectory = originalCreateDirectory;
    compilerHost.writeFile = originalWriteFile;
    return builderProgram;
  }
  function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) {
    writeLog("CreatingProgramWith::");
    writeLog(`  roots: ${JSON.stringify(rootFileNames)}`);
    writeLog(`  options: ${JSON.stringify(compilerOptions)}`);
    if (projectReferences)
      writeLog(`  projectReferences: ${JSON.stringify(projectReferences)}`);
    const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
    hasChangedCompilerOptions = false;
    hasChangedConfigFileParsingErrors = false;
    resolutionCache.startCachingPerDirectoryResolution();
    compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions;
    compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions;
    compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
    const oldProgram = getCurrentProgram();
    builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
    resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram);
    updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = /* @__PURE__ */ new Map()), watchMissingFilePath);
    if (needsUpdateInTypeRootWatch) {
      resolutionCache.updateTypeRootsWatch();
    }
    if (missingFilePathsRequestedForRelease) {
      for (const missingFilePath of missingFilePathsRequestedForRelease) {
        if (!missingFilesMap.has(missingFilePath)) {
          sourceFilesCache.delete(missingFilePath);
        }
      }
      missingFilePathsRequestedForRelease = void 0;
    }
  }
  function updateRootFileNames(files) {
    Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
    rootFileNames = files;
    scheduleProgramUpdate();
  }
  function updateNewLine() {
    return getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile);
  }
  function toPath3(fileName) {
    return toPath(fileName, currentDirectory, getCanonicalFileName);
  }
  function isFileMissingOnHost(hostSourceFile) {
    return typeof hostSourceFile === "boolean";
  }
  function isFilePresenceUnknownOnHost(hostSourceFile) {
    return typeof hostSourceFile.version === "boolean";
  }
  function fileExists(fileName) {
    const path = toPath3(fileName);
    if (isFileMissingOnHost(sourceFilesCache.get(path))) {
      return false;
    }
    return directoryStructureHost.fileExists(fileName);
  }
  function getVersionedSourceFileByPath(fileName, path, languageVersionOrOptions, onError, shouldCreateNewSourceFile) {
    const hostSourceFile = sourceFilesCache.get(path);
    if (isFileMissingOnHost(hostSourceFile)) {
      return void 0;
    }
    if (hostSourceFile === void 0 || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
      const sourceFile = getNewSourceFile(fileName, languageVersionOrOptions, onError);
      if (hostSourceFile) {
        if (sourceFile) {
          hostSourceFile.sourceFile = sourceFile;
          hostSourceFile.version = sourceFile.version;
          if (!hostSourceFile.fileWatcher) {
            hostSourceFile.fileWatcher = watchFilePath(path, fileName, onSourceFileChange, 250 /* Low */, watchOptions, WatchType.SourceFile);
          }
        } else {
          if (hostSourceFile.fileWatcher) {
            hostSourceFile.fileWatcher.close();
          }
          sourceFilesCache.set(path, false);
        }
      } else {
        if (sourceFile) {
          const fileWatcher = watchFilePath(path, fileName, onSourceFileChange, 250 /* Low */, watchOptions, WatchType.SourceFile);
          sourceFilesCache.set(path, { sourceFile, version: sourceFile.version, fileWatcher });
        } else {
          sourceFilesCache.set(path, false);
        }
      }
      return sourceFile;
    }
    return hostSourceFile.sourceFile;
  }
  function nextSourceFileVersion(path) {
    const hostSourceFile = sourceFilesCache.get(path);
    if (hostSourceFile !== void 0) {
      if (isFileMissingOnHost(hostSourceFile)) {
        sourceFilesCache.set(path, { version: false });
      } else {
        hostSourceFile.version = false;
      }
    }
  }
  function getSourceVersion(path, readFileWithCache) {
    const hostSourceFile = sourceFilesCache.get(path);
    if (!hostSourceFile)
      return void 0;
    if (hostSourceFile.version)
      return hostSourceFile.version;
    const text = readFileWithCache(path);
    return text !== void 0 ? getSourceFileVersionAsHashFromText(compilerHost, text) : void 0;
  }
  function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
    const hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
    if (hostSourceFileInfo !== void 0) {
      if (isFileMissingOnHost(hostSourceFileInfo)) {
        (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
      } else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
        if (hostSourceFileInfo.fileWatcher) {
          hostSourceFileInfo.fileWatcher.close();
        }
        sourceFilesCache.delete(oldSourceFile.resolvedPath);
        if (!hasSourceFileByPath) {
          resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
        }
      }
    }
  }
  function reportWatchDiagnostic(message) {
    if (host.onWatchStatusChange) {
      host.onWatchStatusChange(createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
    }
  }
  function hasChangedAutomaticTypeDirectiveNames() {
    return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
  }
  function clearInvalidateResolutionsOfFailedLookupLocations() {
    if (!timerToInvalidateFailedLookupResolutions)
      return false;
    host.clearTimeout(timerToInvalidateFailedLookupResolutions);
    timerToInvalidateFailedLookupResolutions = void 0;
    return true;
  }
  function scheduleInvalidateResolutionsOfFailedLookupLocations() {
    if (!host.setTimeout || !host.clearTimeout) {
      return resolutionCache.invalidateResolutionsOfFailedLookupLocations();
    }
    const pending = clearInvalidateResolutionsOfFailedLookupLocations();
    writeLog(`Scheduling invalidateFailedLookup${pending ? ", Cancelled earlier one" : ""}`);
    timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250, "timerToInvalidateFailedLookupResolutions");
  }
  function invalidateResolutionsOfFailedLookup() {
    timerToInvalidateFailedLookupResolutions = void 0;
    if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
      scheduleProgramUpdate();
    }
  }
  function scheduleProgramUpdate() {
    if (!host.setTimeout || !host.clearTimeout) {
      return;
    }
    if (timerToUpdateProgram) {
      host.clearTimeout(timerToUpdateProgram);
    }
    writeLog("Scheduling update");
    timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250, "timerToUpdateProgram");
  }
  function scheduleProgramReload() {
    Debug.assert(!!configFileName);
    reloadLevel = 2 /* Full */;
    scheduleProgramUpdate();
  }
  function updateProgramWithWatchStatus() {
    timerToUpdateProgram = void 0;
    reportFileChangeDetectedOnCreateProgram = true;
    updateProgram();
  }
  function updateProgram() {
    var _a, _b, _c, _d;
    switch (reloadLevel) {
      case 1 /* Partial */:
        (_a = perfLogger) == null ? void 0 : _a.logStartUpdateProgram("PartialConfigReload");
        reloadFileNamesFromConfigFile();
        break;
      case 2 /* Full */:
        (_b = perfLogger) == null ? void 0 : _b.logStartUpdateProgram("FullConfigReload");
        reloadConfigFile();
        break;
      default:
        (_c = perfLogger) == null ? void 0 : _c.logStartUpdateProgram("SynchronizeProgram");
        synchronizeProgram();
        break;
    }
    (_d = perfLogger) == null ? void 0 : _d.logStopUpdateProgram("Done");
    return getCurrentBuilderProgram();
  }
  function reloadFileNamesFromConfigFile() {
    writeLog("Reloading new file names and options");
    Debug.assert(compilerOptions);
    Debug.assert(configFileName);
    reloadLevel = 0 /* None */;
    rootFileNames = getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
    if (updateErrorForNoInputFiles(rootFileNames, getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
      hasChangedConfigFileParsingErrors = true;
    }
    synchronizeProgram();
  }
  function reloadConfigFile() {
    Debug.assert(configFileName);
    writeLog(`Reloading config file: ${configFileName}`);
    reloadLevel = 0 /* None */;
    if (cachedDirectoryStructureHost) {
      cachedDirectoryStructureHost.clearCache();
    }
    parseConfigFile2();
    hasChangedCompilerOptions = true;
    synchronizeProgram();
    watchConfigFileWildCardDirectories();
    updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile);
  }
  function parseConfigFile2() {
    Debug.assert(configFileName);
    setConfigFileParsingResult(getParsedCommandLineOfConfigFile(
      configFileName,
      optionsToExtendForConfigFile,
      parseConfigFileHost,
      extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()),
      watchOptionsToExtend,
      extraFileExtensions
    ));
  }
  function setConfigFileParsingResult(configFileParseResult) {
    rootFileNames = configFileParseResult.fileNames;
    compilerOptions = configFileParseResult.options;
    watchOptions = configFileParseResult.watchOptions;
    projectReferences = configFileParseResult.projectReferences;
    wildcardDirectories = configFileParseResult.wildcardDirectories;
    configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult).slice();
    canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(configFileParseResult.raw);
    hasChangedConfigFileParsingErrors = true;
  }
  function getParsedCommandLine(configFileName2) {
    const configPath = toPath3(configFileName2);
    let config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath);
    if (config) {
      if (!config.reloadLevel)
        return config.parsedCommandLine;
      if (config.parsedCommandLine && config.reloadLevel === 1 /* Partial */ && !host.getParsedCommandLine) {
        writeLog("Reloading new file names and options");
        Debug.assert(compilerOptions);
        const fileNames = getFileNamesFromConfigSpecs(
          config.parsedCommandLine.options.configFile.configFileSpecs,
          getNormalizedAbsolutePath(getDirectoryPath(configFileName2), currentDirectory),
          compilerOptions,
          parseConfigFileHost
        );
        config.parsedCommandLine = { ...config.parsedCommandLine, fileNames };
        config.reloadLevel = void 0;
        return config.parsedCommandLine;
      }
    }
    writeLog(`Loading config file: ${configFileName2}`);
    const parsedCommandLine = host.getParsedCommandLine ? host.getParsedCommandLine(configFileName2) : getParsedCommandLineFromConfigFileHost(configFileName2);
    if (config) {
      config.parsedCommandLine = parsedCommandLine;
      config.reloadLevel = void 0;
    } else {
      (parsedConfigs || (parsedConfigs = /* @__PURE__ */ new Map())).set(configPath, config = { parsedCommandLine });
    }
    watchReferencedProject(configFileName2, configPath, config);
    return parsedCommandLine;
  }
  function getParsedCommandLineFromConfigFileHost(configFileName2) {
    const onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic;
    parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop;
    const parsedCommandLine = getParsedCommandLineOfConfigFile(
      configFileName2,
      /*optionsToExtend*/
      void 0,
      parseConfigFileHost,
      extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()),
      watchOptionsToExtend
    );
    parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic;
    return parsedCommandLine;
  }
  function onReleaseParsedCommandLine(fileName) {
    var _a;
    const path = toPath3(fileName);
    const config = parsedConfigs == null ? void 0 : parsedConfigs.get(path);
    if (!config)
      return;
    parsedConfigs.delete(path);
    if (config.watchedDirectories)
      clearMap(config.watchedDirectories, closeFileWatcherOf);
    (_a = config.watcher) == null ? void 0 : _a.close();
    clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers);
  }
  function watchFilePath(path, file, callback, pollingInterval, options, watchType) {
    return watchFile2(file, (fileName, eventKind) => callback(fileName, eventKind, path), pollingInterval, options, watchType);
  }
  function onSourceFileChange(fileName, eventKind, path) {
    updateCachedSystemWithFile(fileName, path, eventKind);
    if (eventKind === 2 /* Deleted */ && sourceFilesCache.has(path)) {
      resolutionCache.invalidateResolutionOfFile(path);
    }
    nextSourceFileVersion(path);
    scheduleProgramUpdate();
  }
  function updateCachedSystemWithFile(fileName, path, eventKind) {
    if (cachedDirectoryStructureHost) {
      cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
    }
  }
  function watchMissingFilePath(missingFilePath) {
    return (parsedConfigs == null ? void 0 : parsedConfigs.has(missingFilePath)) ? noopFileWatcher : watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, 500 /* Medium */, watchOptions, WatchType.MissingFile);
  }
  function onMissingFileChange(fileName, eventKind, missingFilePath) {
    updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
    if (eventKind === 0 /* Created */ && missingFilesMap.has(missingFilePath)) {
      missingFilesMap.get(missingFilePath).close();
      missingFilesMap.delete(missingFilePath);
      nextSourceFileVersion(missingFilePath);
      scheduleProgramUpdate();
    }
  }
  function watchConfigFileWildCardDirectories() {
    if (wildcardDirectories) {
      updateWatchingWildcardDirectories(
        watchedWildcardDirectories || (watchedWildcardDirectories = /* @__PURE__ */ new Map()),
        new Map(Object.entries(wildcardDirectories)),
        watchWildcardDirectory
      );
    } else if (watchedWildcardDirectories) {
      clearMap(watchedWildcardDirectories, closeFileWatcherOf);
    }
  }
  function watchWildcardDirectory(directory, flags) {
    return watchDirectory(
      directory,
      (fileOrDirectory) => {
        Debug.assert(configFileName);
        Debug.assert(compilerOptions);
        const fileOrDirectoryPath = toPath3(fileOrDirectory);
        if (cachedDirectoryStructureHost) {
          cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
        }
        nextSourceFileVersion(fileOrDirectoryPath);
        if (isIgnoredFileFromWildCardWatching({
          watchedDirPath: toPath3(directory),
          fileOrDirectory,
          fileOrDirectoryPath,
          configFileName,
          extraFileExtensions,
          options: compilerOptions,
          program: getCurrentBuilderProgram() || rootFileNames,
          currentDirectory,
          useCaseSensitiveFileNames,
          writeLog,
          toPath: toPath3
        }))
          return;
        if (reloadLevel !== 2 /* Full */) {
          reloadLevel = 1 /* Partial */;
          scheduleProgramUpdate();
        }
      },
      flags,
      watchOptions,
      WatchType.WildcardDirectory
    );
  }
  function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions2, watchType) {
    updateSharedExtendedConfigFileWatcher(
      forProjectPath,
      options,
      sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map()),
      (extendedConfigFileName, extendedConfigFilePath) => watchFile2(
        extendedConfigFileName,
        (_fileName, eventKind) => {
          var _a;
          updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind);
          if (extendedConfigCache)
            cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3);
          const projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a.projects;
          if (!(projects == null ? void 0 : projects.size))
            return;
          projects.forEach((projectPath) => {
            if (configFileName && toPath3(configFileName) === projectPath) {
              reloadLevel = 2 /* Full */;
            } else {
              const config = parsedConfigs == null ? void 0 : parsedConfigs.get(projectPath);
              if (config)
                config.reloadLevel = 2 /* Full */;
              resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath);
            }
            scheduleProgramUpdate();
          });
        },
        2e3 /* High */,
        watchOptions2,
        watchType
      ),
      toPath3
    );
  }
  function watchReferencedProject(configFileName2, configPath, commandLine) {
    var _a, _b, _c, _d, _e;
    commandLine.watcher || (commandLine.watcher = watchFile2(
      configFileName2,
      (_fileName, eventKind) => {
        updateCachedSystemWithFile(configFileName2, configPath, eventKind);
        const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath);
        if (config)
          config.reloadLevel = 2 /* Full */;
        resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath);
        scheduleProgramUpdate();
      },
      2e3 /* High */,
      ((_a = commandLine.parsedCommandLine) == null ? void 0 : _a.watchOptions) || watchOptions,
      WatchType.ConfigFileOfReferencedProject
    ));
    if ((_b = commandLine.parsedCommandLine) == null ? void 0 : _b.wildcardDirectories) {
      updateWatchingWildcardDirectories(
        commandLine.watchedDirectories || (commandLine.watchedDirectories = /* @__PURE__ */ new Map()),
        new Map(Object.entries((_c = commandLine.parsedCommandLine) == null ? void 0 : _c.wildcardDirectories)),
        (directory, flags) => {
          var _a2;
          return watchDirectory(
            directory,
            (fileOrDirectory) => {
              const fileOrDirectoryPath = toPath3(fileOrDirectory);
              if (cachedDirectoryStructureHost) {
                cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
              }
              nextSourceFileVersion(fileOrDirectoryPath);
              const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath);
              if (!(config == null ? void 0 : config.parsedCommandLine))
                return;
              if (isIgnoredFileFromWildCardWatching({
                watchedDirPath: toPath3(directory),
                fileOrDirectory,
                fileOrDirectoryPath,
                configFileName: configFileName2,
                options: config.parsedCommandLine.options,
                program: config.parsedCommandLine.fileNames,
                currentDirectory,
                useCaseSensitiveFileNames,
                writeLog,
                toPath: toPath3
              }))
                return;
              if (config.reloadLevel !== 2 /* Full */) {
                config.reloadLevel = 1 /* Partial */;
                scheduleProgramUpdate();
              }
            },
            flags,
            ((_a2 = commandLine.parsedCommandLine) == null ? void 0 : _a2.watchOptions) || watchOptions,
            WatchType.WildcardDirectoryOfReferencedProject
          );
        }
      );
    } else if (commandLine.watchedDirectories) {
      clearMap(commandLine.watchedDirectories, closeFileWatcherOf);
      commandLine.watchedDirectories = void 0;
    }
    updateExtendedConfigFilesWatches(
      configPath,
      (_d = commandLine.parsedCommandLine) == null ? void 0 : _d.options,
      ((_e = commandLine.parsedCommandLine) == null ? void 0 : _e.watchOptions) || watchOptions,
      WatchType.ExtendedConfigOfReferencedProject
    );
  }
}

// src/compiler/tsbuild.ts
var UpToDateStatusType = /* @__PURE__ */ ((UpToDateStatusType2) => {
  UpToDateStatusType2[UpToDateStatusType2["Unbuildable"] = 0] = "Unbuildable";
  UpToDateStatusType2[UpToDateStatusType2["UpToDate"] = 1] = "UpToDate";
  UpToDateStatusType2[UpToDateStatusType2["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
  UpToDateStatusType2[UpToDateStatusType2["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
  UpToDateStatusType2[UpToDateStatusType2["OutputMissing"] = 4] = "OutputMissing";
  UpToDateStatusType2[UpToDateStatusType2["ErrorReadingFile"] = 5] = "ErrorReadingFile";
  UpToDateStatusType2[UpToDateStatusType2["OutOfDateWithSelf"] = 6] = "OutOfDateWithSelf";
  UpToDateStatusType2[UpToDateStatusType2["OutOfDateWithUpstream"] = 7] = "OutOfDateWithUpstream";
  UpToDateStatusType2[UpToDateStatusType2["OutOfDateBuildInfo"] = 8] = "OutOfDateBuildInfo";
  UpToDateStatusType2[UpToDateStatusType2["OutOfDateOptions"] = 9] = "OutOfDateOptions";
  UpToDateStatusType2[UpToDateStatusType2["OutOfDateRoots"] = 10] = "OutOfDateRoots";
  UpToDateStatusType2[UpToDateStatusType2["UpstreamOutOfDate"] = 11] = "UpstreamOutOfDate";
  UpToDateStatusType2[UpToDateStatusType2["UpstreamBlocked"] = 12] = "UpstreamBlocked";
  UpToDateStatusType2[UpToDateStatusType2["ComputingUpstream"] = 13] = "ComputingUpstream";
  UpToDateStatusType2[UpToDateStatusType2["TsVersionOutputOfDate"] = 14] = "TsVersionOutputOfDate";
  UpToDateStatusType2[UpToDateStatusType2["UpToDateWithInputFileText"] = 15] = "UpToDateWithInputFileText";
  UpToDateStatusType2[UpToDateStatusType2["ContainerOnly"] = 16] = "ContainerOnly";
  UpToDateStatusType2[UpToDateStatusType2["ForceBuild"] = 17] = "ForceBuild";
  return UpToDateStatusType2;
})(UpToDateStatusType || {});
function resolveConfigFileProjectName(project) {
  if (fileExtensionIs(project, ".json" /* Json */)) {
    return project;
  }
  return combinePaths(project, "tsconfig.json");
}

// src/compiler/tsbuildPublic.ts
var minimumDate = /* @__PURE__ */ new Date(-864e13);
var maximumDate = /* @__PURE__ */ new Date(864e13);
function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
  const existingValue = configFileMap.get(resolved);
  let newValue;
  if (!existingValue) {
    newValue = createT();
    configFileMap.set(resolved, newValue);
  }
  return existingValue || newValue;
}
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
  return getOrCreateValueFromConfigFileMap(configFileMap, resolved, () => /* @__PURE__ */ new Map());
}
function getCurrentTime(host) {
  return host.now ? host.now() : /* @__PURE__ */ new Date();
}
function isCircularBuildOrder(buildOrder) {
  return !!buildOrder && !!buildOrder.buildOrder;
}
function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
  return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
}
function createBuilderStatusReporter(system, pretty) {
  return (diagnostic) => {
    let output = pretty ? `[${formatColorAndReset(getLocaleTimeString(system), "\x1B[90m" /* Grey */)}] ` : `${getLocaleTimeString(system)} - `;
    output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${system.newLine + system.newLine}`;
    system.write(output);
  };
}
function createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus) {
  const host = createProgramHost(system, createProgram2);
  host.getModifiedTime = system.getModifiedTime ? (path) => system.getModifiedTime(path) : returnUndefined;
  host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime(path, date) : noop;
  host.deleteFile = system.deleteFile ? (path) => system.deleteFile(path) : noop;
  host.reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system);
  host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
  host.now = maybeBind(system, system.now);
  return host;
}
function createSolutionBuilderHost(system = sys, createProgram2, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary2) {
  const host = createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus);
  host.reportErrorSummary = reportErrorSummary2;
  return host;
}
function createSolutionBuilderWithWatchHost(system = sys, createProgram2, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus2) {
  const host = createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus);
  const watchHost = createWatchHost(system, reportWatchStatus2);
  copyProperties(host, watchHost);
  return host;
}
function getCompilerOptionsOfBuildOptions(buildOptions) {
  const result = {};
  commonOptionsWithBuild.forEach((option) => {
    if (hasProperty(buildOptions, option.name))
      result[option.name] = buildOptions[option.name];
  });
  return result;
}
function createSolutionBuilder(host, rootNames, defaultOptions) {
  return createSolutionBuilderWorker(
    /*watch*/
    false,
    host,
    rootNames,
    defaultOptions
  );
}
function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
  return createSolutionBuilderWorker(
    /*watch*/
    true,
    host,
    rootNames,
    defaultOptions,
    baseWatchOptions
  );
}
function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
  const host = hostOrHostWithWatch;
  const hostWithWatch = hostOrHostWithWatch;
  const baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
  const compilerHost = createCompilerHostFromProgramHost(host, () => state.projectCompilerOptions);
  setGetSourceFileAsHashVersioned(compilerHost);
  compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName));
  compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals);
  compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences);
  compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary);
  compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames);
  compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives);
  compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache);
  let moduleResolutionCache, typeReferenceDirectiveResolutionCache;
  if (!compilerHost.resolveModuleNameLiterals && !compilerHost.resolveModuleNames) {
    moduleResolutionCache = createModuleResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName);
    compilerHost.resolveModuleNameLiterals = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(
      moduleNames,
      containingFile,
      redirectedReference,
      options2,
      containingSourceFile,
      host,
      moduleResolutionCache,
      createModuleResolutionLoader
    );
    compilerHost.getModuleResolutionCache = () => moduleResolutionCache;
  }
  if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) {
    typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(
      compilerHost.getCurrentDirectory(),
      compilerHost.getCanonicalFileName,
      /*options*/
      void 0,
      moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()
    );
    compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(
      typeDirectiveNames,
      containingFile,
      redirectedReference,
      options2,
      containingSourceFile,
      host,
      typeReferenceDirectiveResolutionCache,
      createTypeReferenceResolutionLoader
    );
  }
  let libraryResolutionCache;
  if (!compilerHost.resolveLibrary) {
    libraryResolutionCache = createModuleResolutionCache(
      compilerHost.getCurrentDirectory(),
      compilerHost.getCanonicalFileName,
      /*options*/
      void 0,
      moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()
    );
    compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(
      libraryName,
      resolveFrom,
      options2,
      host,
      libraryResolutionCache
    );
  }
  compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3(
    state,
    fileName,
    toResolvedConfigFilePath(state, configFilePath),
    /*modifiedTime*/
    void 0
  );
  const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(hostWithWatch, options);
  const state = {
    host,
    hostWithWatch,
    parseConfigFileHost: parseConfigHostFromCompilerHostLike(host),
    write: maybeBind(host, host.trace),
    // State of solution
    options,
    baseCompilerOptions,
    rootNames,
    baseWatchOptions,
    resolvedConfigFilePaths: /* @__PURE__ */ new Map(),
    configFileCache: /* @__PURE__ */ new Map(),
    projectStatus: /* @__PURE__ */ new Map(),
    extendedConfigCache: /* @__PURE__ */ new Map(),
    buildInfoCache: /* @__PURE__ */ new Map(),
    outputTimeStamps: /* @__PURE__ */ new Map(),
    builderPrograms: /* @__PURE__ */ new Map(),
    diagnostics: /* @__PURE__ */ new Map(),
    projectPendingBuild: /* @__PURE__ */ new Map(),
    projectErrorsReported: /* @__PURE__ */ new Map(),
    compilerHost,
    moduleResolutionCache,
    typeReferenceDirectiveResolutionCache,
    libraryResolutionCache,
    // Mutable state
    buildOrder: void 0,
    readFileWithCache: (f) => host.readFile(f),
    projectCompilerOptions: baseCompilerOptions,
    cache: void 0,
    allProjectBuildPending: true,
    needsSummary: true,
    watchAllProjectsPending: watch,
    // Watch state
    watch,
    allWatchedWildcardDirectories: /* @__PURE__ */ new Map(),
    allWatchedInputFiles: /* @__PURE__ */ new Map(),
    allWatchedConfigFiles: /* @__PURE__ */ new Map(),
    allWatchedExtendedConfigFiles: /* @__PURE__ */ new Map(),
    allWatchedPackageJsonFiles: /* @__PURE__ */ new Map(),
    filesWatched: /* @__PURE__ */ new Map(),
    lastCachedPackageJsonLookups: /* @__PURE__ */ new Map(),
    timerToBuildInvalidatedProject: void 0,
    reportFileChangeDetected: false,
    watchFile: watchFile2,
    watchDirectory,
    writeLog
  };
  return state;
}
function toPath2(state, fileName) {
  return toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
}
function toResolvedConfigFilePath(state, fileName) {
  const { resolvedConfigFilePaths } = state;
  const path = resolvedConfigFilePaths.get(fileName);
  if (path !== void 0)
    return path;
  const resolvedPath = toPath2(state, fileName);
  resolvedConfigFilePaths.set(fileName, resolvedPath);
  return resolvedPath;
}
function isParsedCommandLine(entry) {
  return !!entry.options;
}
function getCachedParsedConfigFile(state, configFilePath) {
  const value = state.configFileCache.get(configFilePath);
  return value && isParsedCommandLine(value) ? value : void 0;
}
function parseConfigFile(state, configFileName, configFilePath) {
  const { configFileCache } = state;
  const value = configFileCache.get(configFilePath);
  if (value) {
    return isParsedCommandLine(value) ? value : void 0;
  }
  mark("SolutionBuilder::beforeConfigFileParsing");
  let diagnostic;
  const { parseConfigFileHost, baseCompilerOptions, baseWatchOptions, extendedConfigCache, host } = state;
  let parsed;
  if (host.getParsedCommandLine) {
    parsed = host.getParsedCommandLine(configFileName);
    if (!parsed)
      diagnostic = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName);
  } else {
    parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = (d) => diagnostic = d;
    parsed = getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
    parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop;
  }
  configFileCache.set(configFilePath, parsed || diagnostic);
  mark("SolutionBuilder::afterConfigFileParsing");
  measure("SolutionBuilder::Config file parsing", "SolutionBuilder::beforeConfigFileParsing", "SolutionBuilder::afterConfigFileParsing");
  return parsed;
}
function resolveProjectName(state, name) {
  return resolveConfigFileProjectName(resolvePath(state.compilerHost.getCurrentDirectory(), name));
}
function createBuildOrder(state, roots) {
  const temporaryMarks = /* @__PURE__ */ new Map();
  const permanentMarks = /* @__PURE__ */ new Map();
  const circularityReportStack = [];
  let buildOrder;
  let circularDiagnostics;
  for (const root of roots) {
    visit(root);
  }
  return circularDiagnostics ? { buildOrder: buildOrder || emptyArray, circularDiagnostics } : buildOrder || emptyArray;
  function visit(configFileName, inCircularContext) {
    const projPath = toResolvedConfigFilePath(state, configFileName);
    if (permanentMarks.has(projPath))
      return;
    if (temporaryMarks.has(projPath)) {
      if (!inCircularContext) {
        (circularDiagnostics || (circularDiagnostics = [])).push(
          createCompilerDiagnostic(
            Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0,
            circularityReportStack.join("\r\n")
          )
        );
      }
      return;
    }
    temporaryMarks.set(projPath, true);
    circularityReportStack.push(configFileName);
    const parsed = parseConfigFile(state, configFileName, projPath);
    if (parsed && parsed.projectReferences) {
      for (const ref of parsed.projectReferences) {
        const resolvedRefPath = resolveProjectName(state, ref.path);
        visit(resolvedRefPath, inCircularContext || ref.circular);
      }
    }
    circularityReportStack.pop();
    permanentMarks.set(projPath, true);
    (buildOrder || (buildOrder = [])).push(configFileName);
  }
}
function getBuildOrder(state) {
  return state.buildOrder || createStateBuildOrder(state);
}
function createStateBuildOrder(state) {
  const buildOrder = createBuildOrder(state, state.rootNames.map((f) => resolveProjectName(state, f)));
  state.resolvedConfigFilePaths.clear();
  const currentProjects = new Map(
    getBuildOrderFromAnyBuildOrder(buildOrder).map(
      (resolved) => [toResolvedConfigFilePath(state, resolved), true]
    )
  );
  const noopOnDelete = { onDeleteValue: noop };
  mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete);
  mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete);
  if (state.watch) {
    mutateMapSkippingNewValues(
      state.allWatchedConfigFiles,
      currentProjects,
      { onDeleteValue: closeFileWatcher }
    );
    state.allWatchedExtendedConfigFiles.forEach((watcher) => {
      watcher.projects.forEach((project) => {
        if (!currentProjects.has(project)) {
          watcher.projects.delete(project);
        }
      });
      watcher.close();
    });
    mutateMapSkippingNewValues(
      state.allWatchedWildcardDirectories,
      currentProjects,
      { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcherOf) }
    );
    mutateMapSkippingNewValues(
      state.allWatchedInputFiles,
      currentProjects,
      { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcher) }
    );
    mutateMapSkippingNewValues(
      state.allWatchedPackageJsonFiles,
      currentProjects,
      { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcher) }
    );
  }
  return state.buildOrder = buildOrder;
}
function getBuildOrderFor(state, project, onlyReferences) {
  const resolvedProject = project && resolveProjectName(state, project);
  const buildOrderFromState = getBuildOrder(state);
  if (isCircularBuildOrder(buildOrderFromState))
    return buildOrderFromState;
  if (resolvedProject) {
    const projectPath = toResolvedConfigFilePath(state, resolvedProject);
    const projectIndex = findIndex(
      buildOrderFromState,
      (configFileName) => toResolvedConfigFilePath(state, configFileName) === projectPath
    );
    if (projectIndex === -1)
      return void 0;
  }
  const buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
  Debug.assert(!isCircularBuildOrder(buildOrder));
  Debug.assert(!onlyReferences || resolvedProject !== void 0);
  Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
  return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
}
function enableCache(state) {
  if (state.cache) {
    disableCache(state);
  }
  const { compilerHost, host } = state;
  const originalReadFileWithCache = state.readFileWithCache;
  const originalGetSourceFile = compilerHost.getSourceFile;
  const {
    originalReadFile,
    originalFileExists,
    originalDirectoryExists,
    originalCreateDirectory,
    originalWriteFile,
    getSourceFileWithCache,
    readFileWithCache
  } = changeCompilerHostLikeToUseCache(
    host,
    (fileName) => toPath2(state, fileName),
    (...args) => originalGetSourceFile.call(compilerHost, ...args)
  );
  state.readFileWithCache = readFileWithCache;
  compilerHost.getSourceFile = getSourceFileWithCache;
  state.cache = {
    originalReadFile,
    originalFileExists,
    originalDirectoryExists,
    originalCreateDirectory,
    originalWriteFile,
    originalReadFileWithCache,
    originalGetSourceFile
  };
}
function disableCache(state) {
  if (!state.cache)
    return;
  const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state;
  host.readFile = cache.originalReadFile;
  host.fileExists = cache.originalFileExists;
  host.directoryExists = cache.originalDirectoryExists;
  host.createDirectory = cache.originalCreateDirectory;
  host.writeFile = cache.originalWriteFile;
  compilerHost.getSourceFile = cache.originalGetSourceFile;
  state.readFileWithCache = cache.originalReadFileWithCache;
  extendedConfigCache.clear();
  moduleResolutionCache == null ? void 0 : moduleResolutionCache.clear();
  typeReferenceDirectiveResolutionCache == null ? void 0 : typeReferenceDirectiveResolutionCache.clear();
  libraryResolutionCache == null ? void 0 : libraryResolutionCache.clear();
  state.cache = void 0;
}
function clearProjectStatus(state, resolved) {
  state.projectStatus.delete(resolved);
  state.diagnostics.delete(resolved);
}
function addProjToQueue({ projectPendingBuild }, proj, reloadLevel) {
  const value = projectPendingBuild.get(proj);
  if (value === void 0) {
    projectPendingBuild.set(proj, reloadLevel);
  } else if (value < reloadLevel) {
    projectPendingBuild.set(proj, reloadLevel);
  }
}
function setupInitialBuild(state, cancellationToken) {
  if (!state.allProjectBuildPending)
    return;
  state.allProjectBuildPending = false;
  if (state.options.watch)
    reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode);
  enableCache(state);
  const buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
  buildOrder.forEach(
    (configFileName) => state.projectPendingBuild.set(
      toResolvedConfigFilePath(state, configFileName),
      0 /* None */
    )
  );
  if (cancellationToken) {
    cancellationToken.throwIfCancellationRequested();
  }
}
var InvalidatedProjectKind = /* @__PURE__ */ ((InvalidatedProjectKind2) => {
  InvalidatedProjectKind2[InvalidatedProjectKind2["Build"] = 0] = "Build";
  InvalidatedProjectKind2[InvalidatedProjectKind2["UpdateBundle"] = 1] = "UpdateBundle";
  InvalidatedProjectKind2[InvalidatedProjectKind2["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
  return InvalidatedProjectKind2;
})(InvalidatedProjectKind || {});
function doneInvalidatedProject(state, projectPath) {
  state.projectPendingBuild.delete(projectPath);
  return state.diagnostics.has(projectPath) ? 1 /* DiagnosticsPresent_OutputsSkipped */ : 0 /* Success */;
}
function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
  let updateOutputFileStampsPending = true;
  return {
    kind: 2 /* UpdateOutputFileStamps */,
    project,
    projectPath,
    buildOrder,
    getCompilerOptions: () => config.options,
    getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(),
    updateOutputFileStatmps: () => {
      updateOutputTimestamps(state, config, projectPath);
      updateOutputFileStampsPending = false;
    },
    done: () => {
      if (updateOutputFileStampsPending) {
        updateOutputTimestamps(state, config, projectPath);
      }
      mark("SolutionBuilder::Timestamps only updates");
      return doneInvalidatedProject(state, projectPath);
    }
  };
}
function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
  let step = kind === 0 /* Build */ ? 0 /* CreateProgram */ : 4 /* EmitBundle */;
  let program;
  let buildResult;
  let invalidatedProjectOfBundle;
  return kind === 0 /* Build */ ? {
    kind,
    project,
    projectPath,
    buildOrder,
    getCompilerOptions: () => config.options,
    getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(),
    getBuilderProgram: () => withProgramOrUndefined(identity),
    getProgram: () => withProgramOrUndefined(
      (program2) => program2.getProgramOrUndefined()
    ),
    getSourceFile: (fileName) => withProgramOrUndefined(
      (program2) => program2.getSourceFile(fileName)
    ),
    getSourceFiles: () => withProgramOrEmptyArray(
      (program2) => program2.getSourceFiles()
    ),
    getOptionsDiagnostics: (cancellationToken) => withProgramOrEmptyArray(
      (program2) => program2.getOptionsDiagnostics(cancellationToken)
    ),
    getGlobalDiagnostics: (cancellationToken) => withProgramOrEmptyArray(
      (program2) => program2.getGlobalDiagnostics(cancellationToken)
    ),
    getConfigFileParsingDiagnostics: () => withProgramOrEmptyArray(
      (program2) => program2.getConfigFileParsingDiagnostics()
    ),
    getSyntacticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray(
      (program2) => program2.getSyntacticDiagnostics(sourceFile, cancellationToken)
    ),
    getAllDependencies: (sourceFile) => withProgramOrEmptyArray(
      (program2) => program2.getAllDependencies(sourceFile)
    ),
    getSemanticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray(
      (program2) => program2.getSemanticDiagnostics(sourceFile, cancellationToken)
    ),
    getSemanticDiagnosticsOfNextAffectedFile: (cancellationToken, ignoreSourceFile) => withProgramOrUndefined(
      (program2) => program2.getSemanticDiagnosticsOfNextAffectedFile && program2.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile)
    ),
    emit: (targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) => {
      if (targetSourceFile || emitOnlyDtsFiles) {
        return withProgramOrUndefined(
          (program2) => {
            var _a, _b;
            return program2.emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project)));
          }
        );
      }
      executeSteps(2 /* SemanticDiagnostics */, cancellationToken);
      if (step === 5 /* EmitBuildInfo */) {
        return emitBuildInfo(writeFile2, cancellationToken);
      }
      if (step !== 3 /* Emit */)
        return void 0;
      return emit(writeFile2, cancellationToken, customTransformers);
    },
    done
  } : {
    kind,
    project,
    projectPath,
    buildOrder,
    getCompilerOptions: () => config.options,
    getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(),
    emit: (writeFile2, customTransformers) => {
      if (step !== 4 /* EmitBundle */)
        return invalidatedProjectOfBundle;
      return emitBundle(writeFile2, customTransformers);
    },
    done
  };
  function done(cancellationToken, writeFile2, customTransformers) {
    executeSteps(8 /* Done */, cancellationToken, writeFile2, customTransformers);
    if (kind === 0 /* Build */)
      mark("SolutionBuilder::Projects built");
    else
      mark("SolutionBuilder::Bundles updated");
    return doneInvalidatedProject(state, projectPath);
  }
  function withProgramOrUndefined(action) {
    executeSteps(0 /* CreateProgram */);
    return program && action(program);
  }
  function withProgramOrEmptyArray(action) {
    return withProgramOrUndefined(action) || emptyArray;
  }
  function createProgram2() {
    var _a, _b;
    Debug.assert(program === void 0);
    if (state.options.dry) {
      reportStatus(state, Diagnostics.A_non_dry_build_would_build_project_0, project);
      buildResult = 1 /* Success */;
      step = 7 /* QueueReferencingProjects */;
      return;
    }
    if (state.options.verbose)
      reportStatus(state, Diagnostics.Building_project_0, project);
    if (config.fileNames.length === 0) {
      reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
      buildResult = 0 /* None */;
      step = 7 /* QueueReferencingProjects */;
      return;
    }
    const { host, compilerHost } = state;
    state.projectCompilerOptions = config.options;
    (_a = state.moduleResolutionCache) == null ? void 0 : _a.update(config.options);
    (_b = state.typeReferenceDirectiveResolutionCache) == null ? void 0 : _b.update(config.options);
    program = host.createProgram(
      config.fileNames,
      config.options,
      compilerHost,
      getOldProgram(state, projectPath, config),
      getConfigFileParsingDiagnostics(config),
      config.projectReferences
    );
    if (state.watch) {
      state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && map(
        state.moduleResolutionCache.getPackageJsonInfoCache().entries(),
        ([path, data]) => [state.host.realpath && data ? toPath2(state, state.host.realpath(path)) : path, data]
      ));
      state.builderPrograms.set(projectPath, program);
    }
    step++;
  }
  function handleDiagnostics(diagnostics, errorFlags, errorType) {
    if (diagnostics.length) {
      ({ buildResult, step } = buildErrors(
        state,
        projectPath,
        program,
        config,
        diagnostics,
        errorFlags,
        errorType
      ));
    } else {
      step++;
    }
  }
  function getSyntaxDiagnostics(cancellationToken) {
    Debug.assertIsDefined(program);
    handleDiagnostics(
      [
        ...program.getConfigFileParsingDiagnostics(),
        ...program.getOptionsDiagnostics(cancellationToken),
        ...program.getGlobalDiagnostics(cancellationToken),
        ...program.getSyntacticDiagnostics(
          /*sourceFile*/
          void 0,
          cancellationToken
        )
      ],
      8 /* SyntaxErrors */,
      "Syntactic"
    );
  }
  function getSemanticDiagnostics(cancellationToken) {
    handleDiagnostics(
      Debug.checkDefined(program).getSemanticDiagnostics(
        /*sourceFile*/
        void 0,
        cancellationToken
      ),
      16 /* TypeErrors */,
      "Semantic"
    );
  }
  function emit(writeFileCallback, cancellationToken, customTransformers) {
    var _a, _b, _c;
    Debug.assertIsDefined(program);
    Debug.assert(step === 3 /* Emit */);
    const saved = program.saveEmitState();
    let declDiagnostics;
    const reportDeclarationDiagnostics = (d) => (declDiagnostics || (declDiagnostics = [])).push(d);
    const outputFiles = [];
    const { emitResult } = emitFilesAndReportErrors(
      program,
      reportDeclarationDiagnostics,
      /*write*/
      void 0,
      /*reportSummary*/
      void 0,
      (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => outputFiles.push({ name, text, writeByteOrderMark, data }),
      cancellationToken,
      /*emitOnlyDtsFiles*/
      false,
      customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))
    );
    if (declDiagnostics) {
      program.restoreEmitState(saved);
      ({ buildResult, step } = buildErrors(
        state,
        projectPath,
        program,
        config,
        declDiagnostics,
        32 /* DeclarationEmitErrors */,
        "Declaration file"
      ));
      return {
        emitSkipped: true,
        diagnostics: emitResult.diagnostics
      };
    }
    const { host, compilerHost } = state;
    const resultFlags = ((_c = program.hasChangedEmitSignature) == null ? void 0 : _c.call(program)) ? 0 /* None */ : 2 /* DeclarationOutputUnchanged */;
    const emitterDiagnostics = createDiagnosticCollection();
    const emittedOutputs = /* @__PURE__ */ new Map();
    const options = program.getCompilerOptions();
    const isIncremental = isIncrementalCompilation(options);
    let outputTimeStampMap;
    let now;
    outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => {
      const path = toPath2(state, name);
      emittedOutputs.set(toPath2(state, name), name);
      if (data == null ? void 0 : data.buildInfo)
        setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags);
      const modifiedTime = (data == null ? void 0 : data.differsOnlyInMap) ? getModifiedTime(state.host, name) : void 0;
      writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
      if (data == null ? void 0 : data.differsOnlyInMap)
        state.host.setModifiedTime(name, modifiedTime);
      else if (!isIncremental && state.watch) {
        (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host)));
      }
    });
    finishEmit(
      emitterDiagnostics,
      emittedOutputs,
      outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()),
      resultFlags
    );
    return emitResult;
  }
  function emitBuildInfo(writeFileCallback, cancellationToken) {
    Debug.assertIsDefined(program);
    Debug.assert(step === 5 /* EmitBuildInfo */);
    const emitResult = program.emitBuildInfo((name, text, writeByteOrderMark, onError, sourceFiles, data) => {
      if (data == null ? void 0 : data.buildInfo)
        setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), 2 /* DeclarationOutputUnchanged */);
      if (writeFileCallback)
        writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data);
      else
        state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data);
    }, cancellationToken);
    if (emitResult.diagnostics.length) {
      reportErrors(state, emitResult.diagnostics);
      state.diagnostics.set(projectPath, [...state.diagnostics.get(projectPath), ...emitResult.diagnostics]);
      buildResult = 64 /* EmitErrors */ & buildResult;
    }
    if (emitResult.emittedFiles && state.write) {
      emitResult.emittedFiles.forEach((name) => listEmittedFile(state, config, name));
    }
    afterProgramDone(state, program, config);
    step = 7 /* QueueReferencingProjects */;
    return emitResult;
  }
  function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) {
    const emitDiagnostics = emitterDiagnostics.getDiagnostics();
    if (emitDiagnostics.length) {
      ({ buildResult, step } = buildErrors(
        state,
        projectPath,
        program,
        config,
        emitDiagnostics,
        64 /* EmitErrors */,
        "Emit"
      ));
      return emitDiagnostics;
    }
    if (state.write) {
      emittedOutputs.forEach((name) => listEmittedFile(state, config, name));
    }
    updateOutputTimestampsWorker(state, config, projectPath, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
    state.diagnostics.delete(projectPath);
    state.projectStatus.set(projectPath, {
      type: 1 /* UpToDate */,
      oldestOutputFileName
    });
    afterProgramDone(state, program, config);
    step = 7 /* QueueReferencingProjects */;
    buildResult = resultFlags;
    return emitDiagnostics;
  }
  function emitBundle(writeFileCallback, customTransformers) {
    var _a, _b, _c, _d;
    Debug.assert(kind === 1 /* UpdateBundle */);
    if (state.options.dry) {
      reportStatus(state, Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
      buildResult = 1 /* Success */;
      step = 7 /* QueueReferencingProjects */;
      return void 0;
    }
    if (state.options.verbose)
      reportStatus(state, Diagnostics.Updating_output_of_project_0, project);
    const { compilerHost } = state;
    state.projectCompilerOptions = config.options;
    (_b = (_a = state.host).beforeEmitBundle) == null ? void 0 : _b.call(_a, config);
    const outputFiles = emitUsingBuildInfo(
      config,
      compilerHost,
      (ref) => {
        const refName = resolveProjectName(state, ref.path);
        return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
      },
      customTransformers || ((_d = (_c = state.host).getCustomTransformers) == null ? void 0 : _d.call(_c, project))
    );
    if (isString(outputFiles)) {
      reportStatus(state, Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
      step = 6 /* BuildInvalidatedProjectOfBundle */;
      return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(
        0 /* Build */,
        state,
        project,
        projectPath,
        projectIndex,
        config,
        buildOrder
      );
    }
    Debug.assert(!!outputFiles.length);
    const emitterDiagnostics = createDiagnosticCollection();
    const emittedOutputs = /* @__PURE__ */ new Map();
    let resultFlags = 2 /* DeclarationOutputUnchanged */;
    const existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo || void 0;
    outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => {
      var _a2, _b2;
      emittedOutputs.set(toPath2(state, name), name);
      if (data == null ? void 0 : data.buildInfo) {
        if (((_a2 = data.buildInfo.program) == null ? void 0 : _a2.outSignature) !== ((_b2 = existingBuildInfo == null ? void 0 : existingBuildInfo.program) == null ? void 0 : _b2.outSignature)) {
          resultFlags &= ~2 /* DeclarationOutputUnchanged */;
        }
        setBuildInfo(state, data.buildInfo, projectPath, config.options, resultFlags);
      }
      writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
    });
    const emitDiagnostics = finishEmit(
      emitterDiagnostics,
      emittedOutputs,
      outputFiles[0].name,
      resultFlags
    );
    return { emitSkipped: false, diagnostics: emitDiagnostics };
  }
  function executeSteps(till, cancellationToken, writeFile2, customTransformers) {
    while (step <= till && step < 8 /* Done */) {
      const currentStep = step;
      switch (step) {
        case 0 /* CreateProgram */:
          createProgram2();
          break;
        case 1 /* SyntaxDiagnostics */:
          getSyntaxDiagnostics(cancellationToken);
          break;
        case 2 /* SemanticDiagnostics */:
          getSemanticDiagnostics(cancellationToken);
          break;
        case 3 /* Emit */:
          emit(writeFile2, cancellationToken, customTransformers);
          break;
        case 5 /* EmitBuildInfo */:
          emitBuildInfo(writeFile2, cancellationToken);
          break;
        case 4 /* EmitBundle */:
          emitBundle(writeFile2, customTransformers);
          break;
        case 6 /* BuildInvalidatedProjectOfBundle */:
          Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile2, customTransformers);
          step = 8 /* Done */;
          break;
        case 7 /* QueueReferencingProjects */:
          queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.checkDefined(buildResult));
          step++;
          break;
        case 8 /* Done */:
        default:
          assertType(step);
      }
      Debug.assert(step > currentStep);
    }
  }
}
function needsBuild({ options }, status, config) {
  if (status.type !== 3 /* OutOfDateWithPrepend */ || options.force)
    return true;
  return config.fileNames.length === 0 || !!getConfigFileParsingDiagnostics(config).length || !isIncrementalCompilation(config.options);
}
function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) {
  if (!state.projectPendingBuild.size)
    return void 0;
  if (isCircularBuildOrder(buildOrder))
    return void 0;
  const { options, projectPendingBuild } = state;
  for (let projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
    const project = buildOrder[projectIndex];
    const projectPath = toResolvedConfigFilePath(state, project);
    const reloadLevel = state.projectPendingBuild.get(projectPath);
    if (reloadLevel === void 0)
      continue;
    if (reportQueue) {
      reportQueue = false;
      reportBuildQueue(state, buildOrder);
    }
    const config = parseConfigFile(state, project, projectPath);
    if (!config) {
      reportParseConfigFileDiagnostic(state, projectPath);
      projectPendingBuild.delete(projectPath);
      continue;
    }
    if (reloadLevel === 2 /* Full */) {
      watchConfigFile(state, project, projectPath, config);
      watchExtendedConfigFiles(state, projectPath, config);
      watchWildCardDirectories(state, project, projectPath, config);
      watchInputFiles(state, project, projectPath, config);
      watchPackageJsonFiles(state, project, projectPath, config);
    } else if (reloadLevel === 1 /* Partial */) {
      config.fileNames = getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, getDirectoryPath(project), config.options, state.parseConfigFileHost);
      updateErrorForNoInputFiles(config.fileNames, project, config.options.configFile.configFileSpecs, config.errors, canJsonReportNoInputFiles(config.raw));
      watchInputFiles(state, project, projectPath, config);
      watchPackageJsonFiles(state, project, projectPath, config);
    }
    const status = getUpToDateStatus(state, config, projectPath);
    if (!options.force) {
      if (status.type === 1 /* UpToDate */) {
        verboseReportProjectStatus(state, project, status);
        reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
        projectPendingBuild.delete(projectPath);
        if (options.dry) {
          reportStatus(state, Diagnostics.Project_0_is_up_to_date, project);
        }
        continue;
      }
      if (status.type === 2 /* UpToDateWithUpstreamTypes */ || status.type === 15 /* UpToDateWithInputFileText */) {
        reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
        return {
          kind: 2 /* UpdateOutputFileStamps */,
          status,
          project,
          projectPath,
          projectIndex,
          config
        };
      }
    }
    if (status.type === 12 /* UpstreamBlocked */) {
      verboseReportProjectStatus(state, project, status);
      reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
      projectPendingBuild.delete(projectPath);
      if (options.verbose) {
        reportStatus(
          state,
          status.upstreamProjectBlocked ? Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built : Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors,
          project,
          status.upstreamProjectName
        );
      }
      continue;
    }
    if (status.type === 16 /* ContainerOnly */) {
      verboseReportProjectStatus(state, project, status);
      reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
      projectPendingBuild.delete(projectPath);
      continue;
    }
    return {
      kind: needsBuild(state, status, config) ? 0 /* Build */ : 1 /* UpdateBundle */,
      status,
      project,
      projectPath,
      projectIndex,
      config
    };
  }
  return void 0;
}
function createInvalidatedProjectWithInfo(state, info, buildOrder) {
  verboseReportProjectStatus(state, info.project, info.status);
  return info.kind !== 2 /* UpdateOutputFileStamps */ ? createBuildOrUpdateInvalidedProject(
    info.kind,
    state,
    info.project,
    info.projectPath,
    info.projectIndex,
    info.config,
    buildOrder
  ) : createUpdateOutputFileStampsProject(
    state,
    info.project,
    info.projectPath,
    info.config,
    buildOrder
  );
}
function getNextInvalidatedProject(state, buildOrder, reportQueue) {
  const info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue);
  if (!info)
    return info;
  return createInvalidatedProjectWithInfo(state, info, buildOrder);
}
function listEmittedFile({ write }, proj, file) {
  if (write && proj.options.listEmittedFiles) {
    write(`TSFILE: ${file}`);
  }
}
function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) {
  if (options.force)
    return void 0;
  const value = builderPrograms.get(proj);
  if (value)
    return value;
  return readBuilderProgram(parsed.options, compilerHost);
}
function afterProgramDone(state, program, config) {
  if (program) {
    if (state.write)
      listFiles(program, state.write);
    if (state.host.afterProgramEmitAndDiagnostics) {
      state.host.afterProgramEmitAndDiagnostics(program);
    }
    program.releaseProgram();
  } else if (state.host.afterEmitBundle) {
    state.host.afterEmitBundle(config);
  }
  state.projectCompilerOptions = state.baseCompilerOptions;
}
function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
  const canEmitBuildInfo = program && !outFile(program.getCompilerOptions());
  reportAndStoreErrors(state, resolvedPath, diagnostics);
  state.projectStatus.set(resolvedPath, { type: 0 /* Unbuildable */, reason: `${errorType} errors` });
  if (canEmitBuildInfo)
    return { buildResult, step: 5 /* EmitBuildInfo */ };
  afterProgramDone(state, program, config);
  return { buildResult, step: 7 /* QueueReferencingProjects */ };
}
function isFileWatcherWithModifiedTime(value) {
  return !!value.watcher;
}
function getModifiedTime2(state, fileName) {
  const path = toPath2(state, fileName);
  const existing = state.filesWatched.get(path);
  if (state.watch && !!existing) {
    if (!isFileWatcherWithModifiedTime(existing))
      return existing;
    if (existing.modifiedTime)
      return existing.modifiedTime;
  }
  const result = getModifiedTime(state.host, fileName);
  if (state.watch) {
    if (existing)
      existing.modifiedTime = result;
    else
      state.filesWatched.set(path, result);
  }
  return result;
}
function watchFile(state, file, callback, pollingInterval, options, watchType, project) {
  const path = toPath2(state, file);
  const existing = state.filesWatched.get(path);
  if (existing && isFileWatcherWithModifiedTime(existing)) {
    existing.callbacks.push(callback);
  } else {
    const watcher = state.watchFile(
      file,
      (fileName, eventKind, modifiedTime) => {
        const existing2 = Debug.checkDefined(state.filesWatched.get(path));
        Debug.assert(isFileWatcherWithModifiedTime(existing2));
        existing2.modifiedTime = modifiedTime;
        existing2.callbacks.forEach((cb) => cb(fileName, eventKind, modifiedTime));
      },
      pollingInterval,
      options,
      watchType,
      project
    );
    state.filesWatched.set(path, { callbacks: [callback], watcher, modifiedTime: existing });
  }
  return {
    close: () => {
      const existing2 = Debug.checkDefined(state.filesWatched.get(path));
      Debug.assert(isFileWatcherWithModifiedTime(existing2));
      if (existing2.callbacks.length === 1) {
        state.filesWatched.delete(path);
        closeFileWatcherOf(existing2);
      } else {
        unorderedRemoveItem(existing2.callbacks, callback);
      }
    }
  };
}
function getOutputTimeStampMap(state, resolvedConfigFilePath) {
  if (!state.watch)
    return void 0;
  let result = state.outputTimeStamps.get(resolvedConfigFilePath);
  if (!result)
    state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map());
  return result;
}
function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) {
  const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
  const existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath);
  const modifiedTime = getCurrentTime(state.host);
  if (existing) {
    existing.buildInfo = buildInfo;
    existing.modifiedTime = modifiedTime;
    if (!(resultFlags & 2 /* DeclarationOutputUnchanged */))
      existing.latestChangedDtsTime = modifiedTime;
  } else {
    state.buildInfoCache.set(resolvedConfigPath, {
      path: toPath2(state, buildInfoPath),
      buildInfo,
      modifiedTime,
      latestChangedDtsTime: resultFlags & 2 /* DeclarationOutputUnchanged */ ? void 0 : modifiedTime
    });
  }
}
function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) {
  const path = toPath2(state, buildInfoPath);
  const existing = state.buildInfoCache.get(resolvedConfigPath);
  return (existing == null ? void 0 : existing.path) === path ? existing : void 0;
}
function getBuildInfo3(state, buildInfoPath, resolvedConfigPath, modifiedTime) {
  const path = toPath2(state, buildInfoPath);
  const existing = state.buildInfoCache.get(resolvedConfigPath);
  if (existing !== void 0 && existing.path === path) {
    return existing.buildInfo || void 0;
  }
  const value = state.readFileWithCache(buildInfoPath);
  const buildInfo = value ? getBuildInfo(buildInfoPath, value) : void 0;
  state.buildInfoCache.set(resolvedConfigPath, { path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || missingFileModifiedTime });
  return buildInfo;
}
function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
  const tsconfigTime = getModifiedTime2(state, configFile);
  if (oldestOutputFileTime < tsconfigTime) {
    return {
      type: 6 /* OutOfDateWithSelf */,
      outOfDateOutputFileName: oldestOutputFileName,
      newerInputFileName: configFile
    };
  }
}
function getUpToDateStatusWorker(state, project, resolvedPath) {
  var _a, _b;
  if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) {
    return {
      type: 16 /* ContainerOnly */
    };
  }
  let referenceStatuses;
  const force = !!state.options.force;
  if (project.projectReferences) {
    state.projectStatus.set(resolvedPath, { type: 13 /* ComputingUpstream */ });
    for (const ref of project.projectReferences) {
      const resolvedRef = resolveProjectReferencePath(ref);
      const resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
      const resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath);
      const refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath);
      if (refStatus.type === 13 /* ComputingUpstream */ || refStatus.type === 16 /* ContainerOnly */) {
        continue;
      }
      if (refStatus.type === 0 /* Unbuildable */ || refStatus.type === 12 /* UpstreamBlocked */) {
        return {
          type: 12 /* UpstreamBlocked */,
          upstreamProjectName: ref.path,
          upstreamProjectBlocked: refStatus.type === 12 /* UpstreamBlocked */
        };
      }
      if (refStatus.type !== 1 /* UpToDate */) {
        return {
          type: 11 /* UpstreamOutOfDate */,
          upstreamProjectName: ref.path
        };
      }
      if (!force)
        (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig });
    }
  }
  if (force)
    return { type: 17 /* ForceBuild */ };
  const { host } = state;
  const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options);
  let oldestOutputFileName;
  let oldestOutputFileTime = maximumDate;
  let buildInfoTime;
  let buildInfoProgram;
  let buildInfoVersionMap;
  if (buildInfoPath) {
    const buildInfoCacheEntry2 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath);
    buildInfoTime = (buildInfoCacheEntry2 == null ? void 0 : buildInfoCacheEntry2.modifiedTime) || getModifiedTime(host, buildInfoPath);
    if (buildInfoTime === missingFileModifiedTime) {
      if (!buildInfoCacheEntry2) {
        state.buildInfoCache.set(resolvedPath, {
          path: toPath2(state, buildInfoPath),
          buildInfo: false,
          modifiedTime: buildInfoTime
        });
      }
      return {
        type: 4 /* OutputMissing */,
        missingOutputFileName: buildInfoPath
      };
    }
    const buildInfo = getBuildInfo3(state, buildInfoPath, resolvedPath, buildInfoTime);
    if (!buildInfo) {
      return {
        type: 5 /* ErrorReadingFile */,
        fileName: buildInfoPath
      };
    }
    if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== version) {
      return {
        type: 14 /* TsVersionOutputOfDate */,
        version: buildInfo.version
      };
    }
    if (buildInfo.program) {
      if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? (_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length : some(buildInfo.program.semanticDiagnosticsPerFile, isArray))) {
        return {
          type: 8 /* OutOfDateBuildInfo */,
          buildInfoFile: buildInfoPath
        };
      }
      if (!project.options.noEmit && getPendingEmitKind(project.options, buildInfo.program.options || {})) {
        return {
          type: 9 /* OutOfDateOptions */,
          buildInfoFile: buildInfoPath
        };
      }
      buildInfoProgram = buildInfo.program;
    }
    oldestOutputFileTime = buildInfoTime;
    oldestOutputFileName = buildInfoPath;
  }
  let newestInputFileName = void 0;
  let newestInputFileTime = minimumDate;
  let pseudoInputUpToDate = false;
  const seenRoots = /* @__PURE__ */ new Set();
  for (const inputFile of project.fileNames) {
    const inputTime = getModifiedTime2(state, inputFile);
    if (inputTime === missingFileModifiedTime) {
      return {
        type: 0 /* Unbuildable */,
        reason: `${inputFile} does not exist`
      };
    }
    if (buildInfoTime && buildInfoTime < inputTime) {
      let version2;
      let currentVersion;
      if (buildInfoProgram) {
        if (!buildInfoVersionMap)
          buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host);
        version2 = buildInfoVersionMap.fileInfos.get(toPath2(state, inputFile));
        const text = version2 ? state.readFileWithCache(inputFile) : void 0;
        currentVersion = text !== void 0 ? getSourceFileVersionAsHashFromText(host, text) : void 0;
        if (version2 && version2 === currentVersion)
          pseudoInputUpToDate = true;
      }
      if (!version2 || version2 !== currentVersion) {
        return {
          type: 6 /* OutOfDateWithSelf */,
          outOfDateOutputFileName: buildInfoPath,
          newerInputFileName: inputFile
        };
      }
    }
    if (inputTime > newestInputFileTime) {
      newestInputFileName = inputFile;
      newestInputFileTime = inputTime;
    }
    if (buildInfoProgram)
      seenRoots.add(toPath2(state, inputFile));
  }
  if (buildInfoProgram) {
    if (!buildInfoVersionMap)
      buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host);
    for (const existingRoot of buildInfoVersionMap.roots) {
      if (!seenRoots.has(existingRoot)) {
        return {
          type: 10 /* OutOfDateRoots */,
          buildInfoFile: buildInfoPath,
          inputFile: existingRoot
        };
      }
    }
  }
  if (!buildInfoPath) {
    const outputs = getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
    const outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath);
    for (const output of outputs) {
      const path = toPath2(state, output);
      let outputTime = outputTimeStampMap == null ? void 0 : outputTimeStampMap.get(path);
      if (!outputTime) {
        outputTime = getModifiedTime(state.host, output);
        outputTimeStampMap == null ? void 0 : outputTimeStampMap.set(path, outputTime);
      }
      if (outputTime === missingFileModifiedTime) {
        return {
          type: 4 /* OutputMissing */,
          missingOutputFileName: output
        };
      }
      if (outputTime < newestInputFileTime) {
        return {
          type: 6 /* OutOfDateWithSelf */,
          outOfDateOutputFileName: output,
          newerInputFileName: newestInputFileName
        };
      }
      if (outputTime < oldestOutputFileTime) {
        oldestOutputFileTime = outputTime;
        oldestOutputFileName = output;
      }
    }
  }
  const buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath);
  let pseudoUpToDate = false;
  let usesPrepend = false;
  let upstreamChangedProject;
  if (referenceStatuses) {
    for (const { ref, refStatus, resolvedConfig, resolvedRefPath } of referenceStatuses) {
      usesPrepend = usesPrepend || !!ref.prepend;
      if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
        continue;
      }
      if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath)) {
        return {
          type: 7 /* OutOfDateWithUpstream */,
          outOfDateOutputFileName: buildInfoPath,
          newerProjectName: ref.path
        };
      }
      const newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath);
      if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
        pseudoUpToDate = true;
        upstreamChangedProject = ref.path;
        continue;
      }
      Debug.assert(oldestOutputFileName !== void 0, "Should have an oldest output filename here");
      return {
        type: 7 /* OutOfDateWithUpstream */,
        outOfDateOutputFileName: oldestOutputFileName,
        newerProjectName: ref.path
      };
    }
  }
  const configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
  if (configStatus)
    return configStatus;
  const extendedConfigStatus = forEach(project.options.configFile.extendedSourceFiles || emptyArray, (configFile) => checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName));
  if (extendedConfigStatus)
    return extendedConfigStatus;
  const dependentPackageFileStatus = forEach(
    state.lastCachedPackageJsonLookups.get(resolvedPath) || emptyArray,
    ([path]) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName)
  );
  if (dependentPackageFileStatus)
    return dependentPackageFileStatus;
  if (usesPrepend && pseudoUpToDate) {
    return {
      type: 3 /* OutOfDateWithPrepend */,
      outOfDateOutputFileName: oldestOutputFileName,
      newerProjectName: upstreamChangedProject
    };
  }
  return {
    type: pseudoUpToDate ? 2 /* UpToDateWithUpstreamTypes */ : pseudoInputUpToDate ? 15 /* UpToDateWithInputFileText */ : 1 /* UpToDate */,
    newestInputFileTime,
    newestInputFileName,
    oldestOutputFileName
  };
}
function hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath) {
  const refBuildInfo = state.buildInfoCache.get(resolvedRefPath);
  return refBuildInfo.path === buildInfoCacheEntry.path;
}
function getUpToDateStatus(state, project, resolvedPath) {
  if (project === void 0) {
    return { type: 0 /* Unbuildable */, reason: "File deleted mid-build" };
  }
  const prior = state.projectStatus.get(resolvedPath);
  if (prior !== void 0) {
    return prior;
  }
  mark("SolutionBuilder::beforeUpToDateCheck");
  const actual = getUpToDateStatusWorker(state, project, resolvedPath);
  mark("SolutionBuilder::afterUpToDateCheck");
  measure("SolutionBuilder::Up-to-date check", "SolutionBuilder::beforeUpToDateCheck", "SolutionBuilder::afterUpToDateCheck");
  state.projectStatus.set(resolvedPath, actual);
  return actual;
}
function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) {
  if (proj.options.noEmit)
    return;
  let now;
  const buildInfoPath = getTsBuildInfoEmitOutputFilePath(proj.options);
  if (buildInfoPath) {
    if (!(skipOutputs == null ? void 0 : skipOutputs.has(toPath2(state, buildInfoPath)))) {
      if (!!state.options.verbose)
        reportStatus(state, verboseMessage, proj.options.configFilePath);
      state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host));
      getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now;
    }
    state.outputTimeStamps.delete(projectPath);
    return;
  }
  const { host } = state;
  const outputs = getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
  const outputTimeStampMap = getOutputTimeStampMap(state, projectPath);
  const modifiedOutputs = outputTimeStampMap ? /* @__PURE__ */ new Set() : void 0;
  if (!skipOutputs || outputs.length !== skipOutputs.size) {
    let reportVerbose = !!state.options.verbose;
    for (const file of outputs) {
      const path = toPath2(state, file);
      if (skipOutputs == null ? void 0 : skipOutputs.has(path))
        continue;
      if (reportVerbose) {
        reportVerbose = false;
        reportStatus(state, verboseMessage, proj.options.configFilePath);
      }
      host.setModifiedTime(file, now || (now = getCurrentTime(state.host)));
      if (outputTimeStampMap) {
        outputTimeStampMap.set(path, now);
        modifiedOutputs.add(path);
      }
    }
  }
  outputTimeStampMap == null ? void 0 : outputTimeStampMap.forEach((_value, key) => {
    if (!(skipOutputs == null ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key))
      outputTimeStampMap.delete(key);
  });
}
function getLatestChangedDtsTime(state, options, resolvedConfigPath) {
  if (!options.composite)
    return void 0;
  const entry = Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath));
  if (entry.latestChangedDtsTime !== void 0)
    return entry.latestChangedDtsTime || void 0;
  const latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, getDirectoryPath(entry.path))) : void 0;
  entry.latestChangedDtsTime = latestChangedDtsTime || false;
  return latestChangedDtsTime;
}
function updateOutputTimestamps(state, proj, resolvedPath) {
  if (state.options.dry) {
    return reportStatus(state, Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
  }
  updateOutputTimestampsWorker(state, proj, resolvedPath, Diagnostics.Updating_output_timestamps_of_project_0);
  state.projectStatus.set(resolvedPath, {
    type: 1 /* UpToDate */,
    oldestOutputFileName: getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
  });
}
function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
  if (buildResult & 124 /* AnyErrors */)
    return;
  if (!config.options.composite)
    return;
  for (let index = projectIndex + 1; index < buildOrder.length; index++) {
    const nextProject = buildOrder[index];
    const nextProjectPath = toResolvedConfigFilePath(state, nextProject);
    if (state.projectPendingBuild.has(nextProjectPath))
      continue;
    const nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
    if (!nextProjectConfig || !nextProjectConfig.projectReferences)
      continue;
    for (const ref of nextProjectConfig.projectReferences) {
      const resolvedRefPath = resolveProjectName(state, ref.path);
      if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
        continue;
      const status = state.projectStatus.get(nextProjectPath);
      if (status) {
        switch (status.type) {
          case 1 /* UpToDate */:
            if (buildResult & 2 /* DeclarationOutputUnchanged */) {
              if (ref.prepend) {
                state.projectStatus.set(nextProjectPath, {
                  type: 3 /* OutOfDateWithPrepend */,
                  outOfDateOutputFileName: status.oldestOutputFileName,
                  newerProjectName: project
                });
              } else {
                status.type = 2 /* UpToDateWithUpstreamTypes */;
              }
              break;
            }
          case 15 /* UpToDateWithInputFileText */:
          case 2 /* UpToDateWithUpstreamTypes */:
          case 3 /* OutOfDateWithPrepend */:
            if (!(buildResult & 2 /* DeclarationOutputUnchanged */)) {
              state.projectStatus.set(nextProjectPath, {
                type: 7 /* OutOfDateWithUpstream */,
                outOfDateOutputFileName: status.type === 3 /* OutOfDateWithPrepend */ ? status.outOfDateOutputFileName : status.oldestOutputFileName,
                newerProjectName: project
              });
            }
            break;
          case 12 /* UpstreamBlocked */:
            if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
              clearProjectStatus(state, nextProjectPath);
            }
            break;
        }
      }
      addProjToQueue(state, nextProjectPath, 0 /* None */);
      break;
    }
  }
}
function build(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) {
  mark("SolutionBuilder::beforeBuild");
  const result = buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences);
  mark("SolutionBuilder::afterBuild");
  measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild");
  return result;
}
function buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) {
  const buildOrder = getBuildOrderFor(state, project, onlyReferences);
  if (!buildOrder)
    return 3 /* InvalidProject_OutputsSkipped */;
  setupInitialBuild(state, cancellationToken);
  let reportQueue = true;
  let successfulProjects = 0;
  while (true) {
    const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
    if (!invalidatedProject)
      break;
    reportQueue = false;
    invalidatedProject.done(cancellationToken, writeFile2, getCustomTransformers == null ? void 0 : getCustomTransformers(invalidatedProject.project));
    if (!state.diagnostics.has(invalidatedProject.projectPath))
      successfulProjects++;
  }
  disableCache(state);
  reportErrorSummary(state, buildOrder);
  startWatching(state, buildOrder);
  return isCircularBuildOrder(buildOrder) ? 4 /* ProjectReferenceCycle_OutputsSkipped */ : !buildOrder.some((p) => state.diagnostics.has(toResolvedConfigFilePath(state, p))) ? 0 /* Success */ : successfulProjects ? 2 /* DiagnosticsPresent_OutputsGenerated */ : 1 /* DiagnosticsPresent_OutputsSkipped */;
}
function clean(state, project, onlyReferences) {
  mark("SolutionBuilder::beforeClean");
  const result = cleanWorker(state, project, onlyReferences);
  mark("SolutionBuilder::afterClean");
  measure("SolutionBuilder::Clean", "SolutionBuilder::beforeClean", "SolutionBuilder::afterClean");
  return result;
}
function cleanWorker(state, project, onlyReferences) {
  const buildOrder = getBuildOrderFor(state, project, onlyReferences);
  if (!buildOrder)
    return 3 /* InvalidProject_OutputsSkipped */;
  if (isCircularBuildOrder(buildOrder)) {
    reportErrors(state, buildOrder.circularDiagnostics);
    return 4 /* ProjectReferenceCycle_OutputsSkipped */;
  }
  const { options, host } = state;
  const filesToDelete = options.dry ? [] : void 0;
  for (const proj of buildOrder) {
    const resolvedPath = toResolvedConfigFilePath(state, proj);
    const parsed = parseConfigFile(state, proj, resolvedPath);
    if (parsed === void 0) {
      reportParseConfigFileDiagnostic(state, resolvedPath);
      continue;
    }
    const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
    if (!outputs.length)
      continue;
    const inputFileNames = new Set(parsed.fileNames.map((f) => toPath2(state, f)));
    for (const output of outputs) {
      if (inputFileNames.has(toPath2(state, output)))
        continue;
      if (host.fileExists(output)) {
        if (filesToDelete) {
          filesToDelete.push(output);
        } else {
          host.deleteFile(output);
          invalidateProject(state, resolvedPath, 0 /* None */);
        }
      }
    }
  }
  if (filesToDelete) {
    reportStatus(state, Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map((f) => `\r
 * ${f}`).join(""));
  }
  return 0 /* Success */;
}
function invalidateProject(state, resolved, reloadLevel) {
  if (state.host.getParsedCommandLine && reloadLevel === 1 /* Partial */) {
    reloadLevel = 2 /* Full */;
  }
  if (reloadLevel === 2 /* Full */) {
    state.configFileCache.delete(resolved);
    state.buildOrder = void 0;
  }
  state.needsSummary = true;
  clearProjectStatus(state, resolved);
  addProjToQueue(state, resolved, reloadLevel);
  enableCache(state);
}
function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
  state.reportFileChangeDetected = true;
  invalidateProject(state, resolvedPath, reloadLevel);
  scheduleBuildInvalidatedProject(
    state,
    250,
    /*changeDetected*/
    true
  );
}
function scheduleBuildInvalidatedProject(state, time, changeDetected) {
  const { hostWithWatch } = state;
  if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
    return;
  }
  if (state.timerToBuildInvalidatedProject) {
    hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
  }
  state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, time, "timerToBuildInvalidatedProject", state, changeDetected);
}
function buildNextInvalidatedProject(_timeoutType, state, changeDetected) {
  mark("SolutionBuilder::beforeBuild");
  const buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected);
  mark("SolutionBuilder::afterBuild");
  measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild");
  if (buildOrder)
    reportErrorSummary(state, buildOrder);
}
function buildNextInvalidatedProjectWorker(state, changeDetected) {
  state.timerToBuildInvalidatedProject = void 0;
  if (state.reportFileChangeDetected) {
    state.reportFileChangeDetected = false;
    state.projectErrorsReported.clear();
    reportWatchStatus(state, Diagnostics.File_change_detected_Starting_incremental_compilation);
  }
  let projectsBuilt = 0;
  const buildOrder = getBuildOrder(state);
  const invalidatedProject = getNextInvalidatedProject(
    state,
    buildOrder,
    /*reportQueue*/
    false
  );
  if (invalidatedProject) {
    invalidatedProject.done();
    projectsBuilt++;
    while (state.projectPendingBuild.size) {
      if (state.timerToBuildInvalidatedProject)
        return;
      const info = getNextInvalidatedProjectCreateInfo(
        state,
        buildOrder,
        /*reportQueue*/
        false
      );
      if (!info)
        break;
      if (info.kind !== 2 /* UpdateOutputFileStamps */ && (changeDetected || projectsBuilt === 5)) {
        scheduleBuildInvalidatedProject(
          state,
          100,
          /*changeDetected*/
          false
        );
        return;
      }
      const project = createInvalidatedProjectWithInfo(state, info, buildOrder);
      project.done();
      if (info.kind !== 2 /* UpdateOutputFileStamps */)
        projectsBuilt++;
    }
  }
  disableCache(state);
  return buildOrder;
}
function watchConfigFile(state, resolved, resolvedPath, parsed) {
  if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
    return;
  state.allWatchedConfigFiles.set(resolvedPath, watchFile(
    state,
    resolved,
    () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */),
    2e3 /* High */,
    parsed == null ? void 0 : parsed.watchOptions,
    WatchType.ConfigFile,
    resolved
  ));
}
function watchExtendedConfigFiles(state, resolvedPath, parsed) {
  updateSharedExtendedConfigFileWatcher(
    resolvedPath,
    parsed == null ? void 0 : parsed.options,
    state.allWatchedExtendedConfigFiles,
    (extendedConfigFileName, extendedConfigFilePath) => watchFile(
      state,
      extendedConfigFileName,
      () => {
        var _a;
        return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a.projects.forEach((projectConfigFilePath) => invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */));
      },
      2e3 /* High */,
      parsed == null ? void 0 : parsed.watchOptions,
      WatchType.ExtendedConfigFile
    ),
    (fileName) => toPath2(state, fileName)
  );
}
function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
  if (!state.watch)
    return;
  updateWatchingWildcardDirectories(
    getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath),
    new Map(Object.entries(parsed.wildcardDirectories)),
    (dir, flags) => state.watchDirectory(
      dir,
      (fileOrDirectory) => {
        var _a;
        if (isIgnoredFileFromWildCardWatching({
          watchedDirPath: toPath2(state, dir),
          fileOrDirectory,
          fileOrDirectoryPath: toPath2(state, fileOrDirectory),
          configFileName: resolved,
          currentDirectory: state.compilerHost.getCurrentDirectory(),
          options: parsed.options,
          program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a.fileNames),
          useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
          writeLog: (s) => state.writeLog(s),
          toPath: (fileName) => toPath2(state, fileName)
        }))
          return;
        invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* Partial */);
      },
      flags,
      parsed == null ? void 0 : parsed.watchOptions,
      WatchType.WildcardDirectory,
      resolved
    )
  );
}
function watchInputFiles(state, resolved, resolvedPath, parsed) {
  if (!state.watch)
    return;
  mutateMap(
    getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath),
    arrayToMap(parsed.fileNames, (fileName) => toPath2(state, fileName)),
    {
      createNewValue: (_path, input) => watchFile(
        state,
        input,
        () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* None */),
        250 /* Low */,
        parsed == null ? void 0 : parsed.watchOptions,
        WatchType.SourceFile,
        resolved
      ),
      onDeleteValue: closeFileWatcher
    }
  );
}
function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) {
  if (!state.watch || !state.lastCachedPackageJsonLookups)
    return;
  mutateMap(
    getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath),
    new Map(state.lastCachedPackageJsonLookups.get(resolvedPath)),
    {
      createNewValue: (path, _input) => watchFile(
        state,
        path,
        () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* None */),
        2e3 /* High */,
        parsed == null ? void 0 : parsed.watchOptions,
        WatchType.PackageJson,
        resolved
      ),
      onDeleteValue: closeFileWatcher
    }
  );
}
function startWatching(state, buildOrder) {
  if (!state.watchAllProjectsPending)
    return;
  mark("SolutionBuilder::beforeWatcherCreation");
  state.watchAllProjectsPending = false;
  for (const resolved of getBuildOrderFromAnyBuildOrder(buildOrder)) {
    const resolvedPath = toResolvedConfigFilePath(state, resolved);
    const cfg = parseConfigFile(state, resolved, resolvedPath);
    watchConfigFile(state, resolved, resolvedPath, cfg);
    watchExtendedConfigFiles(state, resolvedPath, cfg);
    if (cfg) {
      watchWildCardDirectories(state, resolved, resolvedPath, cfg);
      watchInputFiles(state, resolved, resolvedPath, cfg);
      watchPackageJsonFiles(state, resolved, resolvedPath, cfg);
    }
  }
  mark("SolutionBuilder::afterWatcherCreation");
  measure("SolutionBuilder::Watcher creation", "SolutionBuilder::beforeWatcherCreation", "SolutionBuilder::afterWatcherCreation");
}
function stopWatching(state) {
  clearMap(state.allWatchedConfigFiles, closeFileWatcher);
  clearMap(state.allWatchedExtendedConfigFiles, closeFileWatcherOf);
  clearMap(state.allWatchedWildcardDirectories, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcherOf));
  clearMap(state.allWatchedInputFiles, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcher));
  clearMap(state.allWatchedPackageJsonFiles, (watchedPacageJsonFiles) => clearMap(watchedPacageJsonFiles, closeFileWatcher));
}
function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
  const state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
  return {
    build: (project, cancellationToken, writeFile2, getCustomTransformers) => build(state, project, cancellationToken, writeFile2, getCustomTransformers),
    clean: (project) => clean(state, project),
    buildReferences: (project, cancellationToken, writeFile2, getCustomTransformers) => build(
      state,
      project,
      cancellationToken,
      writeFile2,
      getCustomTransformers,
      /*onlyReferences*/
      true
    ),
    cleanReferences: (project) => clean(
      state,
      project,
      /*onlyReferences*/
      true
    ),
    getNextInvalidatedProject: (cancellationToken) => {
      setupInitialBuild(state, cancellationToken);
      return getNextInvalidatedProject(
        state,
        getBuildOrder(state),
        /*reportQueue*/
        false
      );
    },
    getBuildOrder: () => getBuildOrder(state),
    getUpToDateStatusOfProject: (project) => {
      const configFileName = resolveProjectName(state, project);
      const configFilePath = toResolvedConfigFilePath(state, configFileName);
      return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
    },
    invalidateProject: (configFilePath, reloadLevel) => invalidateProject(state, configFilePath, reloadLevel || 0 /* None */),
    close: () => stopWatching(state)
  };
}
function relName(state, path) {
  return convertToRelativePath(path, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
}
function reportStatus(state, message, ...args) {
  state.host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args));
}
function reportWatchStatus(state, message, ...args) {
  var _a, _b;
  (_b = (_a = state.hostWithWatch).onWatchStatusChange) == null ? void 0 : _b.call(_a, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions);
}
function reportErrors({ host }, errors) {
  errors.forEach((err) => host.reportDiagnostic(err));
}
function reportAndStoreErrors(state, proj, errors) {
  reportErrors(state, errors);
  state.projectErrorsReported.set(proj, true);
  if (errors.length) {
    state.diagnostics.set(proj, errors);
  }
}
function reportParseConfigFileDiagnostic(state, proj) {
  reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
}
function reportErrorSummary(state, buildOrder) {
  if (!state.needsSummary)
    return;
  state.needsSummary = false;
  const canReportSummary = state.watch || !!state.host.reportErrorSummary;
  const { diagnostics } = state;
  let totalErrors = 0;
  let filesInError = [];
  if (isCircularBuildOrder(buildOrder)) {
    reportBuildQueue(state, buildOrder.buildOrder);
    reportErrors(state, buildOrder.circularDiagnostics);
    if (canReportSummary)
      totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics);
    if (canReportSummary)
      filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)];
  } else {
    buildOrder.forEach((project) => {
      const projectPath = toResolvedConfigFilePath(state, project);
      if (!state.projectErrorsReported.has(projectPath)) {
        reportErrors(state, diagnostics.get(projectPath) || emptyArray);
      }
    });
    if (canReportSummary)
      diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors));
    if (canReportSummary)
      diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]);
  }
  if (state.watch) {
    reportWatchStatus(state, getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
  } else if (state.host.reportErrorSummary) {
    state.host.reportErrorSummary(totalErrors, filesInError);
  }
}
function reportBuildQueue(state, buildQueue) {
  if (state.options.verbose) {
    reportStatus(state, Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map((s) => "\r\n    * " + relName(state, s)).join(""));
  }
}
function reportUpToDateStatus(state, configFileName, status) {
  switch (status.type) {
    case 6 /* OutOfDateWithSelf */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2,
        relName(state, configFileName),
        relName(state, status.outOfDateOutputFileName),
        relName(state, status.newerInputFileName)
      );
    case 7 /* OutOfDateWithUpstream */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2,
        relName(state, configFileName),
        relName(state, status.outOfDateOutputFileName),
        relName(state, status.newerProjectName)
      );
    case 4 /* OutputMissing */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist,
        relName(state, configFileName),
        relName(state, status.missingOutputFileName)
      );
    case 5 /* ErrorReadingFile */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1,
        relName(state, configFileName),
        relName(state, status.fileName)
      );
    case 8 /* OutOfDateBuildInfo */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted,
        relName(state, configFileName),
        relName(state, status.buildInfoFile)
      );
    case 9 /* OutOfDateOptions */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions,
        relName(state, configFileName),
        relName(state, status.buildInfoFile)
      );
    case 10 /* OutOfDateRoots */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more,
        relName(state, configFileName),
        relName(state, status.buildInfoFile),
        relName(state, status.inputFile)
      );
    case 1 /* UpToDate */:
      if (status.newestInputFileTime !== void 0) {
        return reportStatus(
          state,
          Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2,
          relName(state, configFileName),
          relName(state, status.newestInputFileName || ""),
          relName(state, status.oldestOutputFileName || "")
        );
      }
      break;
    case 3 /* OutOfDateWithPrepend */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed,
        relName(state, configFileName),
        relName(state, status.newerProjectName)
      );
    case 2 /* UpToDateWithUpstreamTypes */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies,
        relName(state, configFileName)
      );
    case 15 /* UpToDateWithInputFileText */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files,
        relName(state, configFileName)
      );
    case 11 /* UpstreamOutOfDate */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date,
        relName(state, configFileName),
        relName(state, status.upstreamProjectName)
      );
    case 12 /* UpstreamBlocked */:
      return reportStatus(
        state,
        status.upstreamProjectBlocked ? Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors,
        relName(state, configFileName),
        relName(state, status.upstreamProjectName)
      );
    case 0 /* Unbuildable */:
      return reportStatus(
        state,
        Diagnostics.Failed_to_parse_file_0_Colon_1,
        relName(state, configFileName),
        status.reason
      );
    case 14 /* TsVersionOutputOfDate */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2,
        relName(state, configFileName),
        status.version,
        version
      );
    case 17 /* ForceBuild */:
      return reportStatus(
        state,
        Diagnostics.Project_0_is_being_forcibly_rebuilt,
        relName(state, configFileName)
      );
    case 16 /* ContainerOnly */:
    case 13 /* ComputingUpstream */:
      break;
    default:
      assertType(status);
  }
}
function verboseReportProjectStatus(state, configFileName, status) {
  if (state.options.verbose) {
    reportUpToDateStatus(state, configFileName, status);
  }
}

// src/jsTyping/_namespaces/ts.JsTyping.ts
var ts_JsTyping_exports = {};
__export(ts_JsTyping_exports, {
  NameValidationResult: () => NameValidationResult,
  discoverTypings: () => discoverTypings,
  isTypingUpToDate: () => isTypingUpToDate,
  loadSafeList: () => loadSafeList,
  loadTypesMap: () => loadTypesMap,
  nodeCoreModuleList: () => nodeCoreModuleList,
  nodeCoreModules: () => nodeCoreModules,
  nonRelativeModuleNameForTypingCache: () => nonRelativeModuleNameForTypingCache,
  prefixedNodeCoreModuleList: () => prefixedNodeCoreModuleList,
  renderPackageNameValidationFailure: () => renderPackageNameValidationFailure,
  validatePackageName: () => validatePackageName
});

// src/jsTyping/jsTyping.ts
function isTypingUpToDate(cachedTyping, availableTypingVersions) {
  const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest"));
  return availableVersion.compareTo(cachedTyping.version) <= 0;
}
var unprefixedNodeCoreModuleList = [
  "assert",
  "assert/strict",
  "async_hooks",
  "buffer",
  "child_process",
  "cluster",
  "console",
  "constants",
  "crypto",
  "dgram",
  "diagnostics_channel",
  "dns",
  "dns/promises",
  "domain",
  "events",
  "fs",
  "fs/promises",
  "http",
  "https",
  "http2",
  "inspector",
  "module",
  "net",
  "os",
  "path",
  "perf_hooks",
  "process",
  "punycode",
  "querystring",
  "readline",
  "repl",
  "stream",
  "stream/promises",
  "string_decoder",
  "timers",
  "timers/promises",
  "tls",
  "trace_events",
  "tty",
  "url",
  "util",
  "util/types",
  "v8",
  "vm",
  "wasi",
  "worker_threads",
  "zlib"
];
var prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map((name) => `node:${name}`);
var nodeCoreModuleList = [...unprefixedNodeCoreModuleList, ...prefixedNodeCoreModuleList];
var nodeCoreModules = new Set(nodeCoreModuleList);
function nonRelativeModuleNameForTypingCache(moduleName) {
  return nodeCoreModules.has(moduleName) ? "node" : moduleName;
}
function loadSafeList(host, safeListPath) {
  const result = readConfigFile(safeListPath, (path) => host.readFile(path));
  return new Map(Object.entries(result.config));
}
function loadTypesMap(host, typesMapPath) {
  var _a;
  const result = readConfigFile(typesMapPath, (path) => host.readFile(path));
  if ((_a = result.config) == null ? void 0 : _a.simpleMap) {
    return new Map(Object.entries(result.config.simpleMap));
  }
  return void 0;
}
function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) {
  if (!typeAcquisition || !typeAcquisition.enable) {
    return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
  }
  const inferredTypings = /* @__PURE__ */ new Map();
  fileNames = mapDefined(fileNames, (fileName) => {
    const path = normalizePath(fileName);
    if (hasJSFileExtension(path)) {
      return path;
    }
  });
  const filesToWatch = [];
  if (typeAcquisition.include)
    addInferredTypings(typeAcquisition.include, "Explicitly included types");
  const exclude = typeAcquisition.exclude || [];
  if (!compilerOptions.types) {
    const possibleSearchDirs = new Set(fileNames.map(getDirectoryPath));
    possibleSearchDirs.add(projectRootPath);
    possibleSearchDirs.forEach((searchDir) => {
      getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch);
      getTypingNames(searchDir, "package.json", "node_modules", filesToWatch);
    });
  }
  if (!typeAcquisition.disableFilenameBasedTypeAcquisition) {
    getTypingNamesFromSourceFileNames(fileNames);
  }
  if (unresolvedImports) {
    const module2 = deduplicate(
      unresolvedImports.map(nonRelativeModuleNameForTypingCache),
      equateStringsCaseSensitive,
      compareStringsCaseSensitive
    );
    addInferredTypings(module2, "Inferred typings from unresolved imports");
  }
  packageNameToTypingLocation.forEach((typing, name) => {
    const registryEntry = typesRegistry.get(name);
    if (inferredTypings.has(name) && inferredTypings.get(name) === void 0 && registryEntry !== void 0 && isTypingUpToDate(typing, registryEntry)) {
      inferredTypings.set(name, typing.typingLocation);
    }
  });
  for (const excludeTypingName of exclude) {
    const didDelete = inferredTypings.delete(excludeTypingName);
    if (didDelete && log)
      log(`Typing for ${excludeTypingName} is in exclude list, will be ignored.`);
  }
  const newTypingNames = [];
  const cachedTypingPaths = [];
  inferredTypings.forEach((inferred, typing) => {
    if (inferred !== void 0) {
      cachedTypingPaths.push(inferred);
    } else {
      newTypingNames.push(typing);
    }
  });
  const result = { cachedTypingPaths, newTypingNames, filesToWatch };
  if (log)
    log(`Result: ${JSON.stringify(result)}`);
  return result;
  function addInferredTyping(typingName) {
    if (!inferredTypings.has(typingName)) {
      inferredTypings.set(typingName, void 0);
    }
  }
  function addInferredTypings(typingNames, message) {
    if (log)
      log(`${message}: ${JSON.stringify(typingNames)}`);
    forEach(typingNames, addInferredTyping);
  }
  function getTypingNames(projectRootPath2, manifestName, modulesDirName, filesToWatch2) {
    const manifestPath = combinePaths(projectRootPath2, manifestName);
    let manifest;
    let manifestTypingNames;
    if (host.fileExists(manifestPath)) {
      filesToWatch2.push(manifestPath);
      manifest = readConfigFile(manifestPath, (path) => host.readFile(path)).config;
      manifestTypingNames = flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], getOwnKeys);
      addInferredTypings(manifestTypingNames, `Typing names in '${manifestPath}' dependencies`);
    }
    const packagesFolderPath = combinePaths(projectRootPath2, modulesDirName);
    filesToWatch2.push(packagesFolderPath);
    if (!host.directoryExists(packagesFolderPath)) {
      return;
    }
    const packageNames = [];
    const dependencyManifestNames = manifestTypingNames ? manifestTypingNames.map((typingName) => combinePaths(packagesFolderPath, typingName, manifestName)) : host.readDirectory(
      packagesFolderPath,
      [".json" /* Json */],
      /*excludes*/
      void 0,
      /*includes*/
      void 0,
      /*depth*/
      3
    ).filter((manifestPath2) => {
      if (getBaseFileName(manifestPath2) !== manifestName) {
        return false;
      }
      const pathComponents2 = getPathComponents(normalizePath(manifestPath2));
      const isScoped = pathComponents2[pathComponents2.length - 3][0] === "@";
      return isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 4]) === modulesDirName || // `node_modules/@foo/bar`
      !isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 3]) === modulesDirName;
    });
    if (log)
      log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(dependencyManifestNames)}`);
    for (const manifestPath2 of dependencyManifestNames) {
      const normalizedFileName = normalizePath(manifestPath2);
      const result2 = readConfigFile(normalizedFileName, (path) => host.readFile(path));
      const manifest2 = result2.config;
      if (!manifest2.name) {
        continue;
      }
      const ownTypes = manifest2.types || manifest2.typings;
      if (ownTypes) {
        const absolutePath = getNormalizedAbsolutePath(ownTypes, getDirectoryPath(normalizedFileName));
        if (host.fileExists(absolutePath)) {
          if (log)
            log(`    Package '${manifest2.name}' provides its own types.`);
          inferredTypings.set(manifest2.name, absolutePath);
        } else {
          if (log)
            log(`    Package '${manifest2.name}' provides its own types but they are missing.`);
        }
      } else {
        packageNames.push(manifest2.name);
      }
    }
    addInferredTypings(packageNames, "    Found package names");
  }
  function getTypingNamesFromSourceFileNames(fileNames2) {
    const fromFileNames = mapDefined(fileNames2, (j) => {
      if (!hasJSFileExtension(j))
        return void 0;
      const inferredTypingName = removeFileExtension(toFileNameLowerCase(getBaseFileName(j)));
      const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName);
      return safeList.get(cleanedTypingName);
    });
    if (fromFileNames.length) {
      addInferredTypings(fromFileNames, "Inferred typings from file names");
    }
    const hasJsxFile = some(fileNames2, (f) => fileExtensionIs(f, ".jsx" /* Jsx */));
    if (hasJsxFile) {
      if (log)
        log(`Inferred 'react' typings due to presence of '.jsx' extension`);
      addInferredTyping("react");
    }
  }
}
var NameValidationResult = /* @__PURE__ */ ((NameValidationResult2) => {
  NameValidationResult2[NameValidationResult2["Ok"] = 0] = "Ok";
  NameValidationResult2[NameValidationResult2["EmptyName"] = 1] = "EmptyName";
  NameValidationResult2[NameValidationResult2["NameTooLong"] = 2] = "NameTooLong";
  NameValidationResult2[NameValidationResult2["NameStartsWithDot"] = 3] = "NameStartsWithDot";
  NameValidationResult2[NameValidationResult2["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
  NameValidationResult2[NameValidationResult2["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
  return NameValidationResult2;
})(NameValidationResult || {});
var maxPackageNameLength = 214;
function validatePackageName(packageName) {
  return validatePackageNameWorker(
    packageName,
    /*supportScopedPackage*/
    true
  );
}
function validatePackageNameWorker(packageName, supportScopedPackage) {
  if (!packageName) {
    return 1 /* EmptyName */;
  }
  if (packageName.length > maxPackageNameLength) {
    return 2 /* NameTooLong */;
  }
  if (packageName.charCodeAt(0) === 46 /* dot */) {
    return 3 /* NameStartsWithDot */;
  }
  if (packageName.charCodeAt(0) === 95 /* _ */) {
    return 4 /* NameStartsWithUnderscore */;
  }
  if (supportScopedPackage) {
    const matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
    if (matches) {
      const scopeResult = validatePackageNameWorker(
        matches[1],
        /*supportScopedPackage*/
        false
      );
      if (scopeResult !== 0 /* Ok */) {
        return { name: matches[1], isScopeName: true, result: scopeResult };
      }
      const packageResult = validatePackageNameWorker(
        matches[2],
        /*supportScopedPackage*/
        false
      );
      if (packageResult !== 0 /* Ok */) {
        return { name: matches[2], isScopeName: false, result: packageResult };
      }
      return 0 /* Ok */;
    }
  }
  if (encodeURIComponent(packageName) !== packageName) {
    return 5 /* NameContainsNonURISafeCharacters */;
  }
  return 0 /* Ok */;
}
function renderPackageNameValidationFailure(result, typing) {
  return typeof result === "object" ? renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) : renderPackageNameValidationFailureWorker(
    typing,
    result,
    typing,
    /*isScopeName*/
    false
  );
}
function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
  const kind = isScopeName ? "Scope" : "Package";
  switch (result) {
    case 1 /* EmptyName */:
      return `'${typing}':: ${kind} name '${name}' cannot be empty`;
    case 2 /* NameTooLong */:
      return `'${typing}':: ${kind} name '${name}' should be less than ${maxPackageNameLength} characters`;
    case 3 /* NameStartsWithDot */:
      return `'${typing}':: ${kind} name '${name}' cannot start with '.'`;
    case 4 /* NameStartsWithUnderscore */:
      return `'${typing}':: ${kind} name '${name}' cannot start with '_'`;
    case 5 /* NameContainsNonURISafeCharacters */:
      return `'${typing}':: ${kind} name '${name}' contains non URI safe characters`;
    case 0 /* Ok */:
      return Debug.fail();
    default:
      Debug.assertNever(result);
  }
}

// src/jsTyping/shared.ts
var ActionSet = "action::set";
var ActionInvalidate = "action::invalidate";
var ActionPackageInstalled = "action::packageInstalled";
var EventTypesRegistry = "event::typesRegistry";
var EventBeginInstallTypes = "event::beginInstallTypes";
var EventEndInstallTypes = "event::endInstallTypes";
var EventInitializationFailed = "event::initializationFailed";
var ActionWatchTypingLocations = "action::watchTypingLocations";
var Arguments;
((Arguments2) => {
  Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation";
  Arguments2.LogFile = "--logFile";
  Arguments2.EnableTelemetry = "--enableTelemetry";
  Arguments2.TypingSafeListLocation = "--typingSafeListLocation";
  Arguments2.TypesMapLocation = "--typesMapLocation";
  Arguments2.NpmLocation = "--npmLocation";
  Arguments2.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments || (Arguments = {}));
function hasArgument(argumentName) {
  return sys.args.indexOf(argumentName) >= 0;
}
function findArgument(argumentName) {
  const index = sys.args.indexOf(argumentName);
  return index >= 0 && index < sys.args.length - 1 ? sys.args[index + 1] : void 0;
}
function nowString() {
  const d = /* @__PURE__ */ new Date();
  return `${padLeft(d.getHours().toString(), 2, "0")}:${padLeft(d.getMinutes().toString(), 2, "0")}:${padLeft(d.getSeconds().toString(), 2, "0")}.${padLeft(d.getMilliseconds().toString(), 3, "0")}`;
}

// src/services/types.ts
var ScriptSnapshot;
((ScriptSnapshot2) => {
  class StringScriptSnapshot {
    constructor(text) {
      this.text = text;
    }
    getText(start2, end) {
      return start2 === 0 && end === this.text.length ? this.text : this.text.substring(start2, end);
    }
    getLength() {
      return this.text.length;
    }
    getChangeRange() {
      return void 0;
    }
  }
  function fromString(text) {
    return new StringScriptSnapshot(text);
  }
  ScriptSnapshot2.fromString = fromString;
})(ScriptSnapshot || (ScriptSnapshot = {}));
var PackageJsonDependencyGroup = /* @__PURE__ */ ((PackageJsonDependencyGroup2) => {
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["Dependencies"] = 1] = "Dependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["DevDependencies"] = 2] = "DevDependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["PeerDependencies"] = 4] = "PeerDependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["OptionalDependencies"] = 8] = "OptionalDependencies";
  PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["All"] = 15] = "All";
  return PackageJsonDependencyGroup2;
})(PackageJsonDependencyGroup || {});
var PackageJsonAutoImportPreference = /* @__PURE__ */ ((PackageJsonAutoImportPreference2) => {
  PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["Off"] = 0] = "Off";
  PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["On"] = 1] = "On";
  PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["Auto"] = 2] = "Auto";
  return PackageJsonAutoImportPreference2;
})(PackageJsonAutoImportPreference || {});
var LanguageServiceMode = /* @__PURE__ */ ((LanguageServiceMode2) => {
  LanguageServiceMode2[LanguageServiceMode2["Semantic"] = 0] = "Semantic";
  LanguageServiceMode2[LanguageServiceMode2["PartialSemantic"] = 1] = "PartialSemantic";
  LanguageServiceMode2[LanguageServiceMode2["Syntactic"] = 2] = "Syntactic";
  return LanguageServiceMode2;
})(LanguageServiceMode || {});
var emptyOptions = {};
var SemanticClassificationFormat = /* @__PURE__ */ ((SemanticClassificationFormat3) => {
  SemanticClassificationFormat3["Original"] = "original";
  SemanticClassificationFormat3["TwentyTwenty"] = "2020";
  return SemanticClassificationFormat3;
})(SemanticClassificationFormat || {});
var OrganizeImportsMode = /* @__PURE__ */ ((OrganizeImportsMode3) => {
  OrganizeImportsMode3["All"] = "All";
  OrganizeImportsMode3["SortAndCombine"] = "SortAndCombine";
  OrganizeImportsMode3["RemoveUnused"] = "RemoveUnused";
  return OrganizeImportsMode3;
})(OrganizeImportsMode || {});
var CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind4) => {
  CompletionTriggerKind4[CompletionTriggerKind4["Invoked"] = 1] = "Invoked";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions";
  return CompletionTriggerKind4;
})(CompletionTriggerKind || {});
var InlayHintKind = /* @__PURE__ */ ((InlayHintKind2) => {
  InlayHintKind2["Type"] = "Type";
  InlayHintKind2["Parameter"] = "Parameter";
  InlayHintKind2["Enum"] = "Enum";
  return InlayHintKind2;
})(InlayHintKind || {});
var HighlightSpanKind = /* @__PURE__ */ ((HighlightSpanKind2) => {
  HighlightSpanKind2["none"] = "none";
  HighlightSpanKind2["definition"] = "definition";
  HighlightSpanKind2["reference"] = "reference";
  HighlightSpanKind2["writtenReference"] = "writtenReference";
  return HighlightSpanKind2;
})(HighlightSpanKind || {});
var IndentStyle = /* @__PURE__ */ ((IndentStyle3) => {
  IndentStyle3[IndentStyle3["None"] = 0] = "None";
  IndentStyle3[IndentStyle3["Block"] = 1] = "Block";
  IndentStyle3[IndentStyle3["Smart"] = 2] = "Smart";
  return IndentStyle3;
})(IndentStyle || {});
var SemicolonPreference = /* @__PURE__ */ ((SemicolonPreference3) => {
  SemicolonPreference3["Ignore"] = "ignore";
  SemicolonPreference3["Insert"] = "insert";
  SemicolonPreference3["Remove"] = "remove";
  return SemicolonPreference3;
})(SemicolonPreference || {});
function getDefaultFormatCodeSettings(newLineCharacter) {
  return {
    indentSize: 4,
    tabSize: 4,
    newLineCharacter: newLineCharacter || "\n",
    convertTabsToSpaces: true,
    indentStyle: 2 /* Smart */,
    insertSpaceAfterConstructor: false,
    insertSpaceAfterCommaDelimiter: true,
    insertSpaceAfterSemicolonInForStatements: true,
    insertSpaceBeforeAndAfterBinaryOperators: true,
    insertSpaceAfterKeywordsInControlFlowStatements: true,
    insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
    insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
    insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
    insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
    insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
    insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
    insertSpaceBeforeFunctionParenthesis: false,
    placeOpenBraceOnNewLineForFunctions: false,
    placeOpenBraceOnNewLineForControlBlocks: false,
    semicolons: "ignore" /* Ignore */,
    trimTrailingWhitespace: true,
    indentSwitchCase: true
  };
}
var testFormatSettings = getDefaultFormatCodeSettings("\n");
var SymbolDisplayPartKind = /* @__PURE__ */ ((SymbolDisplayPartKind2) => {
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["aliasName"] = 0] = "aliasName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["className"] = 1] = "className";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["enumName"] = 2] = "enumName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["fieldName"] = 3] = "fieldName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["interfaceName"] = 4] = "interfaceName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["keyword"] = 5] = "keyword";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["lineBreak"] = 6] = "lineBreak";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["numericLiteral"] = 7] = "numericLiteral";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["stringLiteral"] = 8] = "stringLiteral";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["localName"] = 9] = "localName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["methodName"] = 10] = "methodName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["moduleName"] = 11] = "moduleName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["operator"] = 12] = "operator";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["parameterName"] = 13] = "parameterName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["propertyName"] = 14] = "propertyName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["punctuation"] = 15] = "punctuation";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["space"] = 16] = "space";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["text"] = 17] = "text";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["typeParameterName"] = 18] = "typeParameterName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["enumMemberName"] = 19] = "enumMemberName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["functionName"] = 20] = "functionName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["link"] = 22] = "link";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["linkName"] = 23] = "linkName";
  SymbolDisplayPartKind2[SymbolDisplayPartKind2["linkText"] = 24] = "linkText";
  return SymbolDisplayPartKind2;
})(SymbolDisplayPartKind || {});
var CompletionInfoFlags = /* @__PURE__ */ ((CompletionInfoFlags2) => {
  CompletionInfoFlags2[CompletionInfoFlags2["None"] = 0] = "None";
  CompletionInfoFlags2[CompletionInfoFlags2["MayIncludeAutoImports"] = 1] = "MayIncludeAutoImports";
  CompletionInfoFlags2[CompletionInfoFlags2["IsImportStatementCompletion"] = 2] = "IsImportStatementCompletion";
  CompletionInfoFlags2[CompletionInfoFlags2["IsContinuation"] = 4] = "IsContinuation";
  CompletionInfoFlags2[CompletionInfoFlags2["ResolvedModuleSpecifiers"] = 8] = "ResolvedModuleSpecifiers";
  CompletionInfoFlags2[CompletionInfoFlags2["ResolvedModuleSpecifiersBeyondLimit"] = 16] = "ResolvedModuleSpecifiersBeyondLimit";
  CompletionInfoFlags2[CompletionInfoFlags2["MayIncludeMethodSnippets"] = 32] = "MayIncludeMethodSnippets";
  return CompletionInfoFlags2;
})(CompletionInfoFlags || {});
var OutliningSpanKind = /* @__PURE__ */ ((OutliningSpanKind2) => {
  OutliningSpanKind2["Comment"] = "comment";
  OutliningSpanKind2["Region"] = "region";
  OutliningSpanKind2["Code"] = "code";
  OutliningSpanKind2["Imports"] = "imports";
  return OutliningSpanKind2;
})(OutliningSpanKind || {});
var OutputFileType = /* @__PURE__ */ ((OutputFileType2) => {
  OutputFileType2[OutputFileType2["JavaScript"] = 0] = "JavaScript";
  OutputFileType2[OutputFileType2["SourceMap"] = 1] = "SourceMap";
  OutputFileType2[OutputFileType2["Declaration"] = 2] = "Declaration";
  return OutputFileType2;
})(OutputFileType || {});
var EndOfLineState = /* @__PURE__ */ ((EndOfLineState3) => {
  EndOfLineState3[EndOfLineState3["None"] = 0] = "None";
  EndOfLineState3[EndOfLineState3["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia";
  EndOfLineState3[EndOfLineState3["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral";
  EndOfLineState3[EndOfLineState3["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral";
  EndOfLineState3[EndOfLineState3["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate";
  EndOfLineState3[EndOfLineState3["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail";
  EndOfLineState3[EndOfLineState3["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition";
  return EndOfLineState3;
})(EndOfLineState || {});
var TokenClass = /* @__PURE__ */ ((TokenClass2) => {
  TokenClass2[TokenClass2["Punctuation"] = 0] = "Punctuation";
  TokenClass2[TokenClass2["Keyword"] = 1] = "Keyword";
  TokenClass2[TokenClass2["Operator"] = 2] = "Operator";
  TokenClass2[TokenClass2["Comment"] = 3] = "Comment";
  TokenClass2[TokenClass2["Whitespace"] = 4] = "Whitespace";
  TokenClass2[TokenClass2["Identifier"] = 5] = "Identifier";
  TokenClass2[TokenClass2["NumberLiteral"] = 6] = "NumberLiteral";
  TokenClass2[TokenClass2["BigIntLiteral"] = 7] = "BigIntLiteral";
  TokenClass2[TokenClass2["StringLiteral"] = 8] = "StringLiteral";
  TokenClass2[TokenClass2["RegExpLiteral"] = 9] = "RegExpLiteral";
  return TokenClass2;
})(TokenClass || {});
var ScriptElementKind = /* @__PURE__ */ ((ScriptElementKind2) => {
  ScriptElementKind2["unknown"] = "";
  ScriptElementKind2["warning"] = "warning";
  ScriptElementKind2["keyword"] = "keyword";
  ScriptElementKind2["scriptElement"] = "script";
  ScriptElementKind2["moduleElement"] = "module";
  ScriptElementKind2["classElement"] = "class";
  ScriptElementKind2["localClassElement"] = "local class";
  ScriptElementKind2["interfaceElement"] = "interface";
  ScriptElementKind2["typeElement"] = "type";
  ScriptElementKind2["enumElement"] = "enum";
  ScriptElementKind2["enumMemberElement"] = "enum member";
  ScriptElementKind2["variableElement"] = "var";
  ScriptElementKind2["localVariableElement"] = "local var";
  ScriptElementKind2["functionElement"] = "function";
  ScriptElementKind2["localFunctionElement"] = "local function";
  ScriptElementKind2["memberFunctionElement"] = "method";
  ScriptElementKind2["memberGetAccessorElement"] = "getter";
  ScriptElementKind2["memberSetAccessorElement"] = "setter";
  ScriptElementKind2["memberVariableElement"] = "property";
  ScriptElementKind2["memberAccessorVariableElement"] = "accessor";
  ScriptElementKind2["constructorImplementationElement"] = "constructor";
  ScriptElementKind2["callSignatureElement"] = "call";
  ScriptElementKind2["indexSignatureElement"] = "index";
  ScriptElementKind2["constructSignatureElement"] = "construct";
  ScriptElementKind2["parameterElement"] = "parameter";
  ScriptElementKind2["typeParameterElement"] = "type parameter";
  ScriptElementKind2["primitiveType"] = "primitive type";
  ScriptElementKind2["label"] = "label";
  ScriptElementKind2["alias"] = "alias";
  ScriptElementKind2["constElement"] = "const";
  ScriptElementKind2["letElement"] = "let";
  ScriptElementKind2["directory"] = "directory";
  ScriptElementKind2["externalModuleName"] = "external module name";
  ScriptElementKind2["jsxAttribute"] = "JSX attribute";
  ScriptElementKind2["string"] = "string";
  ScriptElementKind2["link"] = "link";
  ScriptElementKind2["linkName"] = "link name";
  ScriptElementKind2["linkText"] = "link text";
  return ScriptElementKind2;
})(ScriptElementKind || {});
var ScriptElementKindModifier = /* @__PURE__ */ ((ScriptElementKindModifier2) => {
  ScriptElementKindModifier2["none"] = "";
  ScriptElementKindModifier2["publicMemberModifier"] = "public";
  ScriptElementKindModifier2["privateMemberModifier"] = "private";
  ScriptElementKindModifier2["protectedMemberModifier"] = "protected";
  ScriptElementKindModifier2["exportedModifier"] = "export";
  ScriptElementKindModifier2["ambientModifier"] = "declare";
  ScriptElementKindModifier2["staticModifier"] = "static";
  ScriptElementKindModifier2["abstractModifier"] = "abstract";
  ScriptElementKindModifier2["optionalModifier"] = "optional";
  ScriptElementKindModifier2["deprecatedModifier"] = "deprecated";
  ScriptElementKindModifier2["dtsModifier"] = ".d.ts";
  ScriptElementKindModifier2["tsModifier"] = ".ts";
  ScriptElementKindModifier2["tsxModifier"] = ".tsx";
  ScriptElementKindModifier2["jsModifier"] = ".js";
  ScriptElementKindModifier2["jsxModifier"] = ".jsx";
  ScriptElementKindModifier2["jsonModifier"] = ".json";
  ScriptElementKindModifier2["dmtsModifier"] = ".d.mts";
  ScriptElementKindModifier2["mtsModifier"] = ".mts";
  ScriptElementKindModifier2["mjsModifier"] = ".mjs";
  ScriptElementKindModifier2["dctsModifier"] = ".d.cts";
  ScriptElementKindModifier2["ctsModifier"] = ".cts";
  ScriptElementKindModifier2["cjsModifier"] = ".cjs";
  return ScriptElementKindModifier2;
})(ScriptElementKindModifier || {});
var ClassificationTypeNames = /* @__PURE__ */ ((ClassificationTypeNames2) => {
  ClassificationTypeNames2["comment"] = "comment";
  ClassificationTypeNames2["identifier"] = "identifier";
  ClassificationTypeNames2["keyword"] = "keyword";
  ClassificationTypeNames2["numericLiteral"] = "number";
  ClassificationTypeNames2["bigintLiteral"] = "bigint";
  ClassificationTypeNames2["operator"] = "operator";
  ClassificationTypeNames2["stringLiteral"] = "string";
  ClassificationTypeNames2["whiteSpace"] = "whitespace";
  ClassificationTypeNames2["text"] = "text";
  ClassificationTypeNames2["punctuation"] = "punctuation";
  ClassificationTypeNames2["className"] = "class name";
  ClassificationTypeNames2["enumName"] = "enum name";
  ClassificationTypeNames2["interfaceName"] = "interface name";
  ClassificationTypeNames2["moduleName"] = "module name";
  ClassificationTypeNames2["typeParameterName"] = "type parameter name";
  ClassificationTypeNames2["typeAliasName"] = "type alias name";
  ClassificationTypeNames2["parameterName"] = "parameter name";
  ClassificationTypeNames2["docCommentTagName"] = "doc comment tag name";
  ClassificationTypeNames2["jsxOpenTagName"] = "jsx open tag name";
  ClassificationTypeNames2["jsxCloseTagName"] = "jsx close tag name";
  ClassificationTypeNames2["jsxSelfClosingTagName"] = "jsx self closing tag name";
  ClassificationTypeNames2["jsxAttribute"] = "jsx attribute";
  ClassificationTypeNames2["jsxText"] = "jsx text";
  ClassificationTypeNames2["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value";
  return ClassificationTypeNames2;
})(ClassificationTypeNames || {});
var ClassificationType = /* @__PURE__ */ ((ClassificationType3) => {
  ClassificationType3[ClassificationType3["comment"] = 1] = "comment";
  ClassificationType3[ClassificationType3["identifier"] = 2] = "identifier";
  ClassificationType3[ClassificationType3["keyword"] = 3] = "keyword";
  ClassificationType3[ClassificationType3["numericLiteral"] = 4] = "numericLiteral";
  ClassificationType3[ClassificationType3["operator"] = 5] = "operator";
  ClassificationType3[ClassificationType3["stringLiteral"] = 6] = "stringLiteral";
  ClassificationType3[ClassificationType3["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
  ClassificationType3[ClassificationType3["whiteSpace"] = 8] = "whiteSpace";
  ClassificationType3[ClassificationType3["text"] = 9] = "text";
  ClassificationType3[ClassificationType3["punctuation"] = 10] = "punctuation";
  ClassificationType3[ClassificationType3["className"] = 11] = "className";
  ClassificationType3[ClassificationType3["enumName"] = 12] = "enumName";
  ClassificationType3[ClassificationType3["interfaceName"] = 13] = "interfaceName";
  ClassificationType3[ClassificationType3["moduleName"] = 14] = "moduleName";
  ClassificationType3[ClassificationType3["typeParameterName"] = 15] = "typeParameterName";
  ClassificationType3[ClassificationType3["typeAliasName"] = 16] = "typeAliasName";
  ClassificationType3[ClassificationType3["parameterName"] = 17] = "parameterName";
  ClassificationType3[ClassificationType3["docCommentTagName"] = 18] = "docCommentTagName";
  ClassificationType3[ClassificationType3["jsxOpenTagName"] = 19] = "jsxOpenTagName";
  ClassificationType3[ClassificationType3["jsxCloseTagName"] = 20] = "jsxCloseTagName";
  ClassificationType3[ClassificationType3["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
  ClassificationType3[ClassificationType3["jsxAttribute"] = 22] = "jsxAttribute";
  ClassificationType3[ClassificationType3["jsxText"] = 23] = "jsxText";
  ClassificationType3[ClassificationType3["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
  ClassificationType3[ClassificationType3["bigintLiteral"] = 25] = "bigintLiteral";
  return ClassificationType3;
})(ClassificationType || {});

// src/services/utilities.ts
var scanner = createScanner(
  99 /* Latest */,
  /*skipTrivia*/
  true
);
var SemanticMeaning = /* @__PURE__ */ ((SemanticMeaning3) => {
  SemanticMeaning3[SemanticMeaning3["None"] = 0] = "None";
  SemanticMeaning3[SemanticMeaning3["Value"] = 1] = "Value";
  SemanticMeaning3[SemanticMeaning3["Type"] = 2] = "Type";
  SemanticMeaning3[SemanticMeaning3["Namespace"] = 4] = "Namespace";
  SemanticMeaning3[SemanticMeaning3["All"] = 7] = "All";
  return SemanticMeaning3;
})(SemanticMeaning || {});
function getMeaningFromDeclaration(node) {
  switch (node.kind) {
    case 259 /* VariableDeclaration */:
      return isInJSFile(node) && getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */;
    case 168 /* Parameter */:
    case 207 /* BindingElement */:
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
    case 302 /* PropertyAssignment */:
    case 303 /* ShorthandPropertyAssignment */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 175 /* Constructor */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
    case 298 /* CatchClause */:
    case 290 /* JsxAttribute */:
      return 1 /* Value */;
    case 167 /* TypeParameter */:
    case 263 /* InterfaceDeclaration */:
    case 264 /* TypeAliasDeclaration */:
    case 186 /* TypeLiteral */:
      return 2 /* Type */;
    case 352 /* JSDocTypedefTag */:
      return node.name === void 0 ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
    case 305 /* EnumMember */:
    case 262 /* ClassDeclaration */:
      return 1 /* Value */ | 2 /* Type */;
    case 266 /* ModuleDeclaration */:
      if (isAmbientModule(node)) {
        return 4 /* Namespace */ | 1 /* Value */;
      } else if (getModuleInstanceState(node) === 1 /* Instantiated */) {
        return 4 /* Namespace */ | 1 /* Value */;
      } else {
        return 4 /* Namespace */;
      }
    case 265 /* EnumDeclaration */:
    case 274 /* NamedImports */:
    case 275 /* ImportSpecifier */:
    case 270 /* ImportEqualsDeclaration */:
    case 271 /* ImportDeclaration */:
    case 276 /* ExportAssignment */:
    case 277 /* ExportDeclaration */:
      return 7 /* All */;
    case 311 /* SourceFile */:
      return 4 /* Namespace */ | 1 /* Value */;
  }
  return 7 /* All */;
}
function getMeaningFromLocation(node) {
  node = getAdjustedReferenceLocation(node);
  const parent2 = node.parent;
  if (node.kind === 311 /* SourceFile */) {
    return 1 /* Value */;
  } else if (isExportAssignment(parent2) || isExportSpecifier(parent2) || isExternalModuleReference(parent2) || isImportSpecifier(parent2) || isImportClause(parent2) || isImportEqualsDeclaration(parent2) && node === parent2.name) {
    return 7 /* All */;
  } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
    return getMeaningFromRightHandSideOfImportEquals(node);
  } else if (isDeclarationName(node)) {
    return getMeaningFromDeclaration(parent2);
  } else if (isEntityName(node) && findAncestor(node, or(isJSDocNameReference, isJSDocLinkLike, isJSDocMemberName))) {
    return 7 /* All */;
  } else if (isTypeReference(node)) {
    return 2 /* Type */;
  } else if (isNamespaceReference(node)) {
    return 4 /* Namespace */;
  } else if (isTypeParameterDeclaration(parent2)) {
    Debug.assert(isJSDocTemplateTag(parent2.parent));
    return 2 /* Type */;
  } else if (isLiteralTypeNode(parent2)) {
    return 2 /* Type */ | 1 /* Value */;
  } else {
    return 1 /* Value */;
  }
}
function getMeaningFromRightHandSideOfImportEquals(node) {
  const name = node.kind === 165 /* QualifiedName */ ? node : isQualifiedName(node.parent) && node.parent.right === node ? node.parent : void 0;
  return name && name.parent.kind === 270 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */;
}
function isInRightSideOfInternalImportEqualsDeclaration(node) {
  while (node.parent.kind === 165 /* QualifiedName */) {
    node = node.parent;
  }
  return isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
}
function isNamespaceReference(node) {
  return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
}
function isQualifiedNameNamespaceReference(node) {
  let root = node;
  let isLastClause = true;
  if (root.parent.kind === 165 /* QualifiedName */) {
    while (root.parent && root.parent.kind === 165 /* QualifiedName */) {
      root = root.parent;
    }
    isLastClause = root.right === node;
  }
  return root.parent.kind === 182 /* TypeReference */ && !isLastClause;
}
function isPropertyAccessNamespaceReference(node) {
  let root = node;
  let isLastClause = true;
  if (root.parent.kind === 210 /* PropertyAccessExpression */) {
    while (root.parent && root.parent.kind === 210 /* PropertyAccessExpression */) {
      root = root.parent;
    }
    isLastClause = root.name === node;
  }
  if (!isLastClause && root.parent.kind === 232 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 297 /* HeritageClause */) {
    const decl = root.parent.parent.parent;
    return decl.kind === 262 /* ClassDeclaration */ && root.parent.parent.token === 119 /* ImplementsKeyword */ || decl.kind === 263 /* InterfaceDeclaration */ && root.parent.parent.token === 96 /* ExtendsKeyword */;
  }
  return false;
}
function isTypeReference(node) {
  if (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
    node = node.parent;
  }
  switch (node.kind) {
    case 110 /* ThisKeyword */:
      return !isExpressionNode(node);
    case 196 /* ThisType */:
      return true;
  }
  switch (node.parent.kind) {
    case 182 /* TypeReference */:
      return true;
    case 204 /* ImportType */:
      return !node.parent.isTypeOf;
    case 232 /* ExpressionWithTypeArguments */:
      return isPartOfTypeNode(node.parent);
  }
  return false;
}
function isCallExpressionTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isNewExpressionTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isCallOrNewExpressionTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isTaggedTemplateTag(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions);
}
function isDecoratorTarget(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
function isJsxOpeningLikeElementTagName(node, includeElementAccess = false, skipPastOuterExpressions = false) {
  return isCalleeWorker(node, isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions);
}
function selectExpressionOfCallOrNewExpressionOrDecorator(node) {
  return node.expression;
}
function selectTagOfTaggedTemplateExpression(node) {
  return node.tag;
}
function selectTagNameOfJsxOpeningLikeElement(node) {
  return node.tagName;
}
function isCalleeWorker(node, pred, calleeSelector, includeElementAccess, skipPastOuterExpressions) {
  let target = includeElementAccess ? climbPastPropertyOrElementAccess(node) : climbPastPropertyAccess(node);
  if (skipPastOuterExpressions) {
    target = skipOuterExpressions(target);
  }
  return !!target && !!target.parent && pred(target.parent) && calleeSelector(target.parent) === target;
}
function climbPastPropertyAccess(node) {
  return isRightSideOfPropertyAccess(node) ? node.parent : node;
}
function climbPastPropertyOrElementAccess(node) {
  return isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node) ? node.parent : node;
}
function getTargetLabel(referenceNode, labelName) {
  while (referenceNode) {
    if (referenceNode.kind === 255 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) {
      return referenceNode.label;
    }
    referenceNode = referenceNode.parent;
  }
  return void 0;
}
function hasPropertyAccessExpressionWithName(node, funcName) {
  if (!isPropertyAccessExpression(node.expression)) {
    return false;
  }
  return node.expression.name.text === funcName;
}
function isJumpStatementTarget(node) {
  var _a;
  return isIdentifier(node) && ((_a = tryCast(node.parent, isBreakOrContinueStatement)) == null ? void 0 : _a.label) === node;
}
function isLabelOfLabeledStatement(node) {
  var _a;
  return isIdentifier(node) && ((_a = tryCast(node.parent, isLabeledStatement)) == null ? void 0 : _a.label) === node;
}
function isLabelName(node) {
  return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
function isTagName(node) {
  var _a;
  return ((_a = tryCast(node.parent, isJSDocTag)) == null ? void 0 : _a.tagName) === node;
}
function isRightSideOfQualifiedName(node) {
  var _a;
  return ((_a = tryCast(node.parent, isQualifiedName)) == null ? void 0 : _a.right) === node;
}
function isRightSideOfPropertyAccess(node) {
  var _a;
  return ((_a = tryCast(node.parent, isPropertyAccessExpression)) == null ? void 0 : _a.name) === node;
}
function isArgumentExpressionOfElementAccess(node) {
  var _a;
  return ((_a = tryCast(node.parent, isElementAccessExpression)) == null ? void 0 : _a.argumentExpression) === node;
}
function isNameOfModuleDeclaration(node) {
  var _a;
  return ((_a = tryCast(node.parent, isModuleDeclaration)) == null ? void 0 : _a.name) === node;
}
function isNameOfFunctionDeclaration(node) {
  var _a;
  return isIdentifier(node) && ((_a = tryCast(node.parent, isFunctionLike)) == null ? void 0 : _a.name) === node;
}
function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
  switch (node.parent.kind) {
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
    case 302 /* PropertyAssignment */:
    case 305 /* EnumMember */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 266 /* ModuleDeclaration */:
      return getNameOfDeclaration(node.parent) === node;
    case 211 /* ElementAccessExpression */:
      return node.parent.argumentExpression === node;
    case 166 /* ComputedPropertyName */:
      return true;
    case 200 /* LiteralType */:
      return node.parent.parent.kind === 198 /* IndexedAccessType */;
    default:
      return false;
  }
}
function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
  return isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
}
function getContainerNode(node) {
  if (isJSDocTypeAlias(node)) {
    node = node.parent.parent;
  }
  while (true) {
    node = node.parent;
    if (!node) {
      return void 0;
    }
    switch (node.kind) {
      case 311 /* SourceFile */:
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
      case 262 /* ClassDeclaration */:
      case 263 /* InterfaceDeclaration */:
      case 265 /* EnumDeclaration */:
      case 266 /* ModuleDeclaration */:
        return node;
    }
  }
}
function getNodeKind(node) {
  switch (node.kind) {
    case 311 /* SourceFile */:
      return isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
    case 266 /* ModuleDeclaration */:
      return "module" /* moduleElement */;
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
      return "class" /* classElement */;
    case 263 /* InterfaceDeclaration */:
      return "interface" /* interfaceElement */;
    case 264 /* TypeAliasDeclaration */:
    case 344 /* JSDocCallbackTag */:
    case 352 /* JSDocTypedefTag */:
      return "type" /* typeElement */;
    case 265 /* EnumDeclaration */:
      return "enum" /* enumElement */;
    case 259 /* VariableDeclaration */:
      return getKindOfVariableDeclaration(node);
    case 207 /* BindingElement */:
      return getKindOfVariableDeclaration(getRootDeclaration(node));
    case 218 /* ArrowFunction */:
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
      return "function" /* functionElement */;
    case 176 /* GetAccessor */:
      return "getter" /* memberGetAccessorElement */;
    case 177 /* SetAccessor */:
      return "setter" /* memberSetAccessorElement */;
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
      return "method" /* memberFunctionElement */;
    case 302 /* PropertyAssignment */:
      const { initializer } = node;
      return isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
    case 303 /* ShorthandPropertyAssignment */:
    case 304 /* SpreadAssignment */:
      return "property" /* memberVariableElement */;
    case 180 /* IndexSignature */:
      return "index" /* indexSignatureElement */;
    case 179 /* ConstructSignature */:
      return "construct" /* constructSignatureElement */;
    case 178 /* CallSignature */:
      return "call" /* callSignatureElement */;
    case 175 /* Constructor */:
    case 174 /* ClassStaticBlockDeclaration */:
      return "constructor" /* constructorImplementationElement */;
    case 167 /* TypeParameter */:
      return "type parameter" /* typeParameterElement */;
    case 305 /* EnumMember */:
      return "enum member" /* enumMemberElement */;
    case 168 /* Parameter */:
      return hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */;
    case 270 /* ImportEqualsDeclaration */:
    case 275 /* ImportSpecifier */:
    case 280 /* ExportSpecifier */:
    case 273 /* NamespaceImport */:
    case 279 /* NamespaceExport */:
      return "alias" /* alias */;
    case 225 /* BinaryExpression */:
      const kind = getAssignmentDeclarationKind(node);
      const { right } = node;
      switch (kind) {
        case 7 /* ObjectDefinePropertyValue */:
        case 8 /* ObjectDefinePropertyExports */:
        case 9 /* ObjectDefinePrototypeProperty */:
        case 0 /* None */:
          return "" /* unknown */;
        case 1 /* ExportsProperty */:
        case 2 /* ModuleExports */:
          const rightKind = getNodeKind(right);
          return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind;
        case 3 /* PrototypeProperty */:
          return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
        case 4 /* ThisProperty */:
          return "property" /* memberVariableElement */;
        case 5 /* Property */:
          return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
        case 6 /* Prototype */:
          return "local class" /* localClassElement */;
        default: {
          assertType(kind);
          return "" /* unknown */;
        }
      }
    case 80 /* Identifier */:
      return isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */;
    case 276 /* ExportAssignment */:
      const scriptKind = getNodeKind(node.expression);
      return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind;
    default:
      return "" /* unknown */;
  }
  function getKindOfVariableDeclaration(v) {
    return isVarConst(v) ? "const" /* constElement */ : isLet(v) ? "let" /* letElement */ : "var" /* variableElement */;
  }
}
function isThis(node) {
  switch (node.kind) {
    case 110 /* ThisKeyword */:
      return true;
    case 80 /* Identifier */:
      return identifierIsThisKeyword(node) && node.parent.kind === 168 /* Parameter */;
    default:
      return false;
  }
}
var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
function getLineStartPositionForPosition(position, sourceFile) {
  const lineStarts = getLineStarts(sourceFile);
  const line = sourceFile.getLineAndCharacterOfPosition(position).line;
  return lineStarts[line];
}
function rangeContainsRange(r1, r2) {
  return startEndContainsRange(r1.pos, r1.end, r2);
}
function rangeContainsRangeExclusive(r1, r2) {
  return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
}
function rangeContainsPosition(r, pos) {
  return r.pos <= pos && pos <= r.end;
}
function rangeContainsPositionExclusive(r, pos) {
  return r.pos < pos && pos < r.end;
}
function startEndContainsRange(start2, end, range) {
  return start2 <= range.pos && end >= range.end;
}
function rangeContainsStartEnd(range, start2, end) {
  return range.pos <= start2 && range.end >= end;
}
function rangeOverlapsWithStartEnd(r1, start2, end) {
  return startEndOverlapsWithStartEnd(r1.pos, r1.end, start2, end);
}
function nodeOverlapsWithStartEnd(node, sourceFile, start2, end) {
  return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start2, end);
}
function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
  const start3 = Math.max(start1, start2);
  const end = Math.min(end1, end2);
  return start3 < end;
}
function positionBelongsToNode(candidate, position, sourceFile) {
  Debug.assert(candidate.pos <= position);
  return position < candidate.end || !isCompletedNode(candidate, sourceFile);
}
function isCompletedNode(n, sourceFile) {
  if (n === void 0 || nodeIsMissing(n)) {
    return false;
  }
  switch (n.kind) {
    case 262 /* ClassDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 265 /* EnumDeclaration */:
    case 209 /* ObjectLiteralExpression */:
    case 205 /* ObjectBindingPattern */:
    case 186 /* TypeLiteral */:
    case 240 /* Block */:
    case 267 /* ModuleBlock */:
    case 268 /* CaseBlock */:
    case 274 /* NamedImports */:
    case 278 /* NamedExports */:
      return nodeEndsWith(n, 20 /* CloseBraceToken */, sourceFile);
    case 298 /* CatchClause */:
      return isCompletedNode(n.block, sourceFile);
    case 213 /* NewExpression */:
      if (!n.arguments) {
        return true;
      }
    case 212 /* CallExpression */:
    case 216 /* ParenthesizedExpression */:
    case 195 /* ParenthesizedType */:
      return nodeEndsWith(n, 22 /* CloseParenToken */, sourceFile);
    case 183 /* FunctionType */:
    case 184 /* ConstructorType */:
      return isCompletedNode(n.type, sourceFile);
    case 175 /* Constructor */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 179 /* ConstructSignature */:
    case 178 /* CallSignature */:
    case 218 /* ArrowFunction */:
      if (n.body) {
        return isCompletedNode(n.body, sourceFile);
      }
      if (n.type) {
        return isCompletedNode(n.type, sourceFile);
      }
      return hasChildOfKind(n, 22 /* CloseParenToken */, sourceFile);
    case 266 /* ModuleDeclaration */:
      return !!n.body && isCompletedNode(n.body, sourceFile);
    case 244 /* IfStatement */:
      if (n.elseStatement) {
        return isCompletedNode(n.elseStatement, sourceFile);
      }
      return isCompletedNode(n.thenStatement, sourceFile);
    case 243 /* ExpressionStatement */:
      return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 27 /* SemicolonToken */, sourceFile);
    case 208 /* ArrayLiteralExpression */:
    case 206 /* ArrayBindingPattern */:
    case 211 /* ElementAccessExpression */:
    case 166 /* ComputedPropertyName */:
    case 188 /* TupleType */:
      return nodeEndsWith(n, 24 /* CloseBracketToken */, sourceFile);
    case 180 /* IndexSignature */:
      if (n.type) {
        return isCompletedNode(n.type, sourceFile);
      }
      return hasChildOfKind(n, 24 /* CloseBracketToken */, sourceFile);
    case 295 /* CaseClause */:
    case 296 /* DefaultClause */:
      return false;
    case 247 /* ForStatement */:
    case 248 /* ForInStatement */:
    case 249 /* ForOfStatement */:
    case 246 /* WhileStatement */:
      return isCompletedNode(n.statement, sourceFile);
    case 245 /* DoStatement */:
      return hasChildOfKind(n, 117 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 22 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile);
    case 185 /* TypeQuery */:
      return isCompletedNode(n.exprName, sourceFile);
    case 220 /* TypeOfExpression */:
    case 219 /* DeleteExpression */:
    case 221 /* VoidExpression */:
    case 228 /* YieldExpression */:
    case 229 /* SpreadElement */:
      const unaryWordExpression = n;
      return isCompletedNode(unaryWordExpression.expression, sourceFile);
    case 214 /* TaggedTemplateExpression */:
      return isCompletedNode(n.template, sourceFile);
    case 227 /* TemplateExpression */:
      const lastSpan = lastOrUndefined(n.templateSpans);
      return isCompletedNode(lastSpan, sourceFile);
    case 238 /* TemplateSpan */:
      return nodeIsPresent(n.literal);
    case 277 /* ExportDeclaration */:
    case 271 /* ImportDeclaration */:
      return nodeIsPresent(n.moduleSpecifier);
    case 223 /* PrefixUnaryExpression */:
      return isCompletedNode(n.operand, sourceFile);
    case 225 /* BinaryExpression */:
      return isCompletedNode(n.right, sourceFile);
    case 226 /* ConditionalExpression */:
      return isCompletedNode(n.whenFalse, sourceFile);
    default:
      return true;
  }
}
function nodeEndsWith(n, expectedLastToken, sourceFile) {
  const children = n.getChildren(sourceFile);
  if (children.length) {
    const lastChild = last(children);
    if (lastChild.kind === expectedLastToken) {
      return true;
    } else if (lastChild.kind === 27 /* SemicolonToken */ && children.length !== 1) {
      return children[children.length - 2].kind === expectedLastToken;
    }
  }
  return false;
}
function findListItemInfo(node) {
  const list = findContainingList(node);
  if (!list) {
    return void 0;
  }
  const children = list.getChildren();
  const listItemIndex = indexOfNode(children, node);
  return {
    listItemIndex,
    list
  };
}
function hasChildOfKind(n, kind, sourceFile) {
  return !!findChildOfKind(n, kind, sourceFile);
}
function findChildOfKind(n, kind, sourceFile) {
  return find(n.getChildren(sourceFile), (c) => c.kind === kind);
}
function findContainingList(node) {
  const syntaxList = find(node.parent.getChildren(), (c) => isSyntaxList(c) && rangeContainsRange(c, node));
  Debug.assert(!syntaxList || contains(syntaxList.getChildren(), node));
  return syntaxList;
}
function isDefaultModifier2(node) {
  return node.kind === 90 /* DefaultKeyword */;
}
function isClassKeyword(node) {
  return node.kind === 86 /* ClassKeyword */;
}
function isFunctionKeyword(node) {
  return node.kind === 100 /* FunctionKeyword */;
}
function getAdjustedLocationForClass(node) {
  if (isNamedDeclaration(node)) {
    return node.name;
  }
  if (isClassDeclaration(node)) {
    const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier2);
    if (defaultModifier)
      return defaultModifier;
  }
  if (isClassExpression(node)) {
    const classKeyword = find(node.getChildren(), isClassKeyword);
    if (classKeyword)
      return classKeyword;
  }
}
function getAdjustedLocationForFunction(node) {
  if (isNamedDeclaration(node)) {
    return node.name;
  }
  if (isFunctionDeclaration(node)) {
    const defaultModifier = find(node.modifiers, isDefaultModifier2);
    if (defaultModifier)
      return defaultModifier;
  }
  if (isFunctionExpression(node)) {
    const functionKeyword = find(node.getChildren(), isFunctionKeyword);
    if (functionKeyword)
      return functionKeyword;
  }
}
function getAncestorTypeNode(node) {
  let lastTypeNode;
  findAncestor(node, (a) => {
    if (isTypeNode(a)) {
      lastTypeNode = a;
    }
    return !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent);
  });
  return lastTypeNode;
}
function getContextualTypeFromParentOrAncestorTypeNode(node, checker) {
  if (node.flags & (8388608 /* JSDoc */ & ~262144 /* JavaScriptFile */))
    return void 0;
  const contextualType = getContextualTypeFromParent(node, checker);
  if (contextualType)
    return contextualType;
  const ancestorTypeNode = getAncestorTypeNode(node);
  return ancestorTypeNode && checker.getTypeAtLocation(ancestorTypeNode);
}
function getAdjustedLocationForDeclaration(node, forRename) {
  if (!forRename) {
    switch (node.kind) {
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
        return getAdjustedLocationForClass(node);
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
        return getAdjustedLocationForFunction(node);
      case 175 /* Constructor */:
        return node;
    }
  }
  if (isNamedDeclaration(node)) {
    return node.name;
  }
}
function getAdjustedLocationForImportDeclaration(node, forRename) {
  if (node.importClause) {
    if (node.importClause.name && node.importClause.namedBindings) {
      return;
    }
    if (node.importClause.name) {
      return node.importClause.name;
    }
    if (node.importClause.namedBindings) {
      if (isNamedImports(node.importClause.namedBindings)) {
        const onlyBinding = singleOrUndefined(node.importClause.namedBindings.elements);
        if (!onlyBinding) {
          return;
        }
        return onlyBinding.name;
      } else if (isNamespaceImport(node.importClause.namedBindings)) {
        return node.importClause.namedBindings.name;
      }
    }
  }
  if (!forRename) {
    return node.moduleSpecifier;
  }
}
function getAdjustedLocationForExportDeclaration(node, forRename) {
  if (node.exportClause) {
    if (isNamedExports(node.exportClause)) {
      const onlyBinding = singleOrUndefined(node.exportClause.elements);
      if (!onlyBinding) {
        return;
      }
      return node.exportClause.elements[0].name;
    } else if (isNamespaceExport(node.exportClause)) {
      return node.exportClause.name;
    }
  }
  if (!forRename) {
    return node.moduleSpecifier;
  }
}
function getAdjustedLocationForHeritageClause(node) {
  if (node.types.length === 1) {
    return node.types[0].expression;
  }
}
function getAdjustedLocation(node, forRename) {
  const { parent: parent2 } = node;
  if (isModifier(node) && (forRename || node.kind !== 90 /* DefaultKeyword */) ? canHaveModifiers(parent2) && contains(parent2.modifiers, node) : node.kind === 86 /* ClassKeyword */ ? isClassDeclaration(parent2) || isClassExpression(node) : node.kind === 100 /* FunctionKeyword */ ? isFunctionDeclaration(parent2) || isFunctionExpression(node) : node.kind === 120 /* InterfaceKeyword */ ? isInterfaceDeclaration(parent2) : node.kind === 94 /* EnumKeyword */ ? isEnumDeclaration(parent2) : node.kind === 156 /* TypeKeyword */ ? isTypeAliasDeclaration(parent2) : node.kind === 145 /* NamespaceKeyword */ || node.kind === 144 /* ModuleKeyword */ ? isModuleDeclaration(parent2) : node.kind === 102 /* ImportKeyword */ ? isImportEqualsDeclaration(parent2) : node.kind === 139 /* GetKeyword */ ? isGetAccessorDeclaration(parent2) : node.kind === 153 /* SetKeyword */ && isSetAccessorDeclaration(parent2)) {
    const location = getAdjustedLocationForDeclaration(parent2, forRename);
    if (location) {
      return location;
    }
  }
  if ((node.kind === 115 /* VarKeyword */ || node.kind === 87 /* ConstKeyword */ || node.kind === 121 /* LetKeyword */) && isVariableDeclarationList(parent2) && parent2.declarations.length === 1) {
    const decl = parent2.declarations[0];
    if (isIdentifier(decl.name)) {
      return decl.name;
    }
  }
  if (node.kind === 156 /* TypeKeyword */) {
    if (isImportClause(parent2) && parent2.isTypeOnly) {
      const location = getAdjustedLocationForImportDeclaration(parent2.parent, forRename);
      if (location) {
        return location;
      }
    }
    if (isExportDeclaration(parent2) && parent2.isTypeOnly) {
      const location = getAdjustedLocationForExportDeclaration(parent2, forRename);
      if (location) {
        return location;
      }
    }
  }
  if (node.kind === 130 /* AsKeyword */) {
    if (isImportSpecifier(parent2) && parent2.propertyName || isExportSpecifier(parent2) && parent2.propertyName || isNamespaceImport(parent2) || isNamespaceExport(parent2)) {
      return parent2.name;
    }
    if (isExportDeclaration(parent2) && parent2.exportClause && isNamespaceExport(parent2.exportClause)) {
      return parent2.exportClause.name;
    }
  }
  if (node.kind === 102 /* ImportKeyword */ && isImportDeclaration(parent2)) {
    const location = getAdjustedLocationForImportDeclaration(parent2, forRename);
    if (location) {
      return location;
    }
  }
  if (node.kind === 95 /* ExportKeyword */) {
    if (isExportDeclaration(parent2)) {
      const location = getAdjustedLocationForExportDeclaration(parent2, forRename);
      if (location) {
        return location;
      }
    }
    if (isExportAssignment(parent2)) {
      return skipOuterExpressions(parent2.expression);
    }
  }
  if (node.kind === 149 /* RequireKeyword */ && isExternalModuleReference(parent2)) {
    return parent2.expression;
  }
  if (node.kind === 160 /* FromKeyword */ && (isImportDeclaration(parent2) || isExportDeclaration(parent2)) && parent2.moduleSpecifier) {
    return parent2.moduleSpecifier;
  }
  if ((node.kind === 96 /* ExtendsKeyword */ || node.kind === 119 /* ImplementsKeyword */) && isHeritageClause(parent2) && parent2.token === node.kind) {
    const location = getAdjustedLocationForHeritageClause(parent2);
    if (location) {
      return location;
    }
  }
  if (node.kind === 96 /* ExtendsKeyword */) {
    if (isTypeParameterDeclaration(parent2) && parent2.constraint && isTypeReferenceNode(parent2.constraint)) {
      return parent2.constraint.typeName;
    }
    if (isConditionalTypeNode(parent2) && isTypeReferenceNode(parent2.extendsType)) {
      return parent2.extendsType.typeName;
    }
  }
  if (node.kind === 140 /* InferKeyword */ && isInferTypeNode(parent2)) {
    return parent2.typeParameter.name;
  }
  if (node.kind === 103 /* InKeyword */ && isTypeParameterDeclaration(parent2) && isMappedTypeNode(parent2.parent)) {
    return parent2.name;
  }
  if (node.kind === 143 /* KeyOfKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 143 /* KeyOfKeyword */ && isTypeReferenceNode(parent2.type)) {
    return parent2.type.typeName;
  }
  if (node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(parent2) && parent2.operator === 148 /* ReadonlyKeyword */ && isArrayTypeNode(parent2.type) && isTypeReferenceNode(parent2.type.elementType)) {
    return parent2.type.elementType.typeName;
  }
  if (!forRename) {
    if (node.kind === 105 /* NewKeyword */ && isNewExpression(parent2) || node.kind === 116 /* VoidKeyword */ && isVoidExpression(parent2) || node.kind === 114 /* TypeOfKeyword */ && isTypeOfExpression(parent2) || node.kind === 135 /* AwaitKeyword */ && isAwaitExpression(parent2) || node.kind === 127 /* YieldKeyword */ && isYieldExpression(parent2) || node.kind === 91 /* DeleteKeyword */ && isDeleteExpression(parent2)) {
      if (parent2.expression) {
        return skipOuterExpressions(parent2.expression);
      }
    }
    if ((node.kind === 103 /* InKeyword */ || node.kind === 104 /* InstanceOfKeyword */) && isBinaryExpression(parent2) && parent2.operatorToken === node) {
      return skipOuterExpressions(parent2.right);
    }
    if (node.kind === 130 /* AsKeyword */ && isAsExpression(parent2) && isTypeReferenceNode(parent2.type)) {
      return parent2.type.typeName;
    }
    if (node.kind === 103 /* InKeyword */ && isForInStatement(parent2) || node.kind === 164 /* OfKeyword */ && isForOfStatement(parent2)) {
      return skipOuterExpressions(parent2.expression);
    }
  }
  return node;
}
function getAdjustedReferenceLocation(node) {
  return getAdjustedLocation(
    node,
    /*forRename*/
    false
  );
}
function getAdjustedRenameLocation(node) {
  return getAdjustedLocation(
    node,
    /*forRename*/
    true
  );
}
function getTouchingPropertyName(sourceFile, position) {
  return getTouchingToken(sourceFile, position, (n) => isPropertyNameLiteral(n) || isKeyword(n.kind) || isPrivateIdentifier(n));
}
function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) {
  return getTokenAtPositionWorker(
    sourceFile,
    position,
    /*allowPositionInLeadingTrivia*/
    false,
    includePrecedingTokenAtEndPosition,
    /*includeEndPosition*/
    false
  );
}
function getTokenAtPosition(sourceFile, position) {
  return getTokenAtPositionWorker(
    sourceFile,
    position,
    /*allowPositionInLeadingTrivia*/
    true,
    /*includePrecedingTokenAtEndPosition*/
    void 0,
    /*includeEndPosition*/
    false
  );
}
function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) {
  let current = sourceFile;
  let foundToken;
  outer:
    while (true) {
      const children = current.getChildren(sourceFile);
      const i = binarySearchKey(children, position, (_, i2) => i2, (middle, _) => {
        const end = children[middle].getEnd();
        if (end < position) {
          return -1 /* LessThan */;
        }
        const start2 = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(
          sourceFile,
          /*includeJsDocComment*/
          true
        );
        if (start2 > position) {
          return 1 /* GreaterThan */;
        }
        if (nodeContainsPosition(children[middle], start2, end)) {
          if (children[middle - 1]) {
            if (nodeContainsPosition(children[middle - 1])) {
              return 1 /* GreaterThan */;
            }
          }
          return 0 /* EqualTo */;
        }
        if (includePrecedingTokenAtEndPosition && start2 === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) {
          return 1 /* GreaterThan */;
        }
        return -1 /* LessThan */;
      });
      if (foundToken) {
        return foundToken;
      }
      if (i >= 0 && children[i]) {
        current = children[i];
        continue outer;
      }
      return current;
    }
  function nodeContainsPosition(node, start2, end) {
    end ?? (end = node.getEnd());
    if (end < position) {
      return false;
    }
    start2 ?? (start2 = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(
      sourceFile,
      /*includeJsDocComment*/
      true
    ));
    if (start2 > position) {
      return false;
    }
    if (position < end || position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition)) {
      return true;
    } else if (includePrecedingTokenAtEndPosition && end === position) {
      const previousToken = findPrecedingToken(position, sourceFile, node);
      if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) {
        foundToken = previousToken;
        return true;
      }
    }
    return false;
  }
}
function findFirstNonJsxWhitespaceToken(sourceFile, position) {
  let tokenAtPosition = getTokenAtPosition(sourceFile, position);
  while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) {
    const nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile);
    if (!nextToken)
      return;
    tokenAtPosition = nextToken;
  }
  return tokenAtPosition;
}
function findTokenOnLeftOfPosition(file, position) {
  const tokenAtPosition = getTokenAtPosition(file, position);
  if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
    return tokenAtPosition;
  }
  return findPrecedingToken(position, file);
}
function findNextToken(previousToken, parent2, sourceFile) {
  return find2(parent2);
  function find2(n) {
    if (isToken(n) && n.pos === previousToken.end) {
      return n;
    }
    return firstDefined(n.getChildren(sourceFile), (child) => {
      const shouldDiveInChildNode = (
        // previous token is enclosed somewhere in the child
        child.pos <= previousToken.pos && child.end > previousToken.end || // previous token ends exactly at the beginning of child
        child.pos === previousToken.end
      );
      return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find2(child) : void 0;
    });
  }
}
function findPrecedingToken(position, sourceFile, startNode2, excludeJsdoc) {
  const result = find2(startNode2 || sourceFile);
  Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
  return result;
  function find2(n) {
    if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
      return n;
    }
    const children = n.getChildren(sourceFile);
    const i = binarySearchKey(children, position, (_, i2) => i2, (middle, _) => {
      if (position < children[middle].end) {
        if (!children[middle - 1] || position >= children[middle - 1].end) {
          return 0 /* EqualTo */;
        }
        return 1 /* GreaterThan */;
      }
      return -1 /* LessThan */;
    });
    if (i >= 0 && children[i]) {
      const child = children[i];
      if (position < child.end) {
        const start2 = child.getStart(
          sourceFile,
          /*includeJsDoc*/
          !excludeJsdoc
        );
        const lookInPreviousChild = start2 >= position || // cursor in the leading trivia
        !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child);
        if (lookInPreviousChild) {
          const candidate2 = findRightmostChildNodeWithTokens(
            children,
            /*exclusiveStartPosition*/
            i,
            sourceFile,
            n.kind
          );
          if (candidate2) {
            if (!excludeJsdoc && isJSDocCommentContainingNode(candidate2) && candidate2.getChildren(sourceFile).length) {
              return find2(candidate2);
            }
            return findRightmostToken(candidate2, sourceFile);
          }
          return void 0;
        } else {
          return find2(child);
        }
      }
    }
    Debug.assert(startNode2 !== void 0 || n.kind === 311 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || isJSDocCommentContainingNode(n));
    const candidate = findRightmostChildNodeWithTokens(
      children,
      /*exclusiveStartPosition*/
      children.length,
      sourceFile,
      n.kind
    );
    return candidate && findRightmostToken(candidate, sourceFile);
  }
}
function isNonWhitespaceToken(n) {
  return isToken(n) && !isWhiteSpaceOnlyJsxText(n);
}
function findRightmostToken(n, sourceFile) {
  if (isNonWhitespaceToken(n)) {
    return n;
  }
  const children = n.getChildren(sourceFile);
  if (children.length === 0) {
    return n;
  }
  const candidate = findRightmostChildNodeWithTokens(
    children,
    /*exclusiveStartPosition*/
    children.length,
    sourceFile,
    n.kind
  );
  return candidate && findRightmostToken(candidate, sourceFile);
}
function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile, parentKind) {
  for (let i = exclusiveStartPosition - 1; i >= 0; i--) {
    const child = children[i];
    if (isWhiteSpaceOnlyJsxText(child)) {
      if (i === 0 && (parentKind === 12 /* JsxText */ || parentKind === 284 /* JsxSelfClosingElement */)) {
        Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
      }
    } else if (nodeHasTokens(children[i], sourceFile)) {
      return children[i];
    }
  }
}
function isInString(sourceFile, position, previousToken = findPrecedingToken(position, sourceFile)) {
  if (previousToken && isStringTextContainingNode(previousToken)) {
    const start2 = previousToken.getStart(sourceFile);
    const end = previousToken.getEnd();
    if (start2 < position && position < end) {
      return true;
    }
    if (position === end) {
      return !!previousToken.isUnterminated;
    }
  }
  return false;
}
function isInsideJsxElementOrAttribute(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  if (!token) {
    return false;
  }
  if (token.kind === 12 /* JsxText */) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 12 /* JsxText */) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 293 /* JsxExpression */) {
    return true;
  }
  if (token && token.kind === 20 /* CloseBraceToken */ && token.parent.kind === 293 /* JsxExpression */) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && token.parent.kind === 286 /* JsxClosingElement */) {
    return true;
  }
  return false;
}
function isWhiteSpaceOnlyJsxText(node) {
  return isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}
function isInJSXText(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  if (isJsxText(token)) {
    return true;
  }
  if (token.kind === 19 /* OpenBraceToken */ && isJsxExpression(token.parent) && isJsxElement(token.parent.parent)) {
    return true;
  }
  if (token.kind === 30 /* LessThanToken */ && isJsxOpeningLikeElement(token.parent) && isJsxElement(token.parent.parent)) {
    return true;
  }
  return false;
}
function isInsideJsxElement(sourceFile, position) {
  function isInsideJsxElementTraversal(node) {
    while (node) {
      if (node.kind >= 284 /* JsxSelfClosingElement */ && node.kind <= 293 /* JsxExpression */ || node.kind === 12 /* JsxText */ || node.kind === 30 /* LessThanToken */ || node.kind === 32 /* GreaterThanToken */ || node.kind === 80 /* Identifier */ || node.kind === 20 /* CloseBraceToken */ || node.kind === 19 /* OpenBraceToken */ || node.kind === 44 /* SlashToken */) {
        node = node.parent;
      } else if (node.kind === 283 /* JsxElement */) {
        if (position > node.getStart(sourceFile))
          return true;
        node = node.parent;
      } else {
        return false;
      }
    }
    return false;
  }
  return isInsideJsxElementTraversal(getTokenAtPosition(sourceFile, position));
}
function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
  const closeTokenText = tokenToString(token.kind);
  const matchingTokenText = tokenToString(matchingTokenKind);
  const tokenFullStart = token.getFullStart();
  const bestGuessIndex = sourceFile.text.lastIndexOf(matchingTokenText, tokenFullStart);
  if (bestGuessIndex === -1) {
    return void 0;
  }
  if (sourceFile.text.lastIndexOf(closeTokenText, tokenFullStart - 1) < bestGuessIndex) {
    const nodeAtGuess = findPrecedingToken(bestGuessIndex + 1, sourceFile);
    if (nodeAtGuess && nodeAtGuess.kind === matchingTokenKind) {
      return nodeAtGuess;
    }
  }
  const tokenKind = token.kind;
  let remainingMatchingTokens = 0;
  while (true) {
    const preceding = findPrecedingToken(token.getFullStart(), sourceFile);
    if (!preceding) {
      return void 0;
    }
    token = preceding;
    if (token.kind === matchingTokenKind) {
      if (remainingMatchingTokens === 0) {
        return token;
      }
      remainingMatchingTokens--;
    } else if (token.kind === tokenKind) {
      remainingMatchingTokens++;
    }
  }
}
function removeOptionality(type, isOptionalExpression, isOptionalChain2) {
  return isOptionalExpression ? type.getNonNullableType() : isOptionalChain2 ? type.getNonOptionalType() : type;
}
function isPossiblyTypeArgumentPosition(token, sourceFile, checker) {
  const info = getPossibleTypeArgumentsInfo(token, sourceFile);
  return info !== void 0 && (isPartOfTypeNode(info.called) || getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || isPossiblyTypeArgumentPosition(info.called, sourceFile, checker));
}
function getPossibleGenericSignatures(called, typeArgumentCount, checker) {
  let type = checker.getTypeAtLocation(called);
  if (isOptionalChain(called.parent)) {
    type = removeOptionality(
      type,
      isOptionalChainRoot(called.parent),
      /*isOptionalChain*/
      true
    );
  }
  const signatures = isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures();
  return signatures.filter((candidate) => !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount);
}
function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
  if (sourceFile.text.lastIndexOf("<", tokenIn ? tokenIn.pos : sourceFile.text.length) === -1) {
    return void 0;
  }
  let token = tokenIn;
  let remainingLessThanTokens = 0;
  let nTypeArguments = 0;
  while (token) {
    switch (token.kind) {
      case 30 /* LessThanToken */:
        token = findPrecedingToken(token.getFullStart(), sourceFile);
        if (token && token.kind === 29 /* QuestionDotToken */) {
          token = findPrecedingToken(token.getFullStart(), sourceFile);
        }
        if (!token || !isIdentifier(token))
          return void 0;
        if (!remainingLessThanTokens) {
          return isDeclarationName(token) ? void 0 : { called: token, nTypeArguments };
        }
        remainingLessThanTokens--;
        break;
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
        remainingLessThanTokens = 3;
        break;
      case 49 /* GreaterThanGreaterThanToken */:
        remainingLessThanTokens = 2;
        break;
      case 32 /* GreaterThanToken */:
        remainingLessThanTokens++;
        break;
      case 20 /* CloseBraceToken */:
        token = findPrecedingMatchingToken(token, 19 /* OpenBraceToken */, sourceFile);
        if (!token)
          return void 0;
        break;
      case 22 /* CloseParenToken */:
        token = findPrecedingMatchingToken(token, 21 /* OpenParenToken */, sourceFile);
        if (!token)
          return void 0;
        break;
      case 24 /* CloseBracketToken */:
        token = findPrecedingMatchingToken(token, 23 /* OpenBracketToken */, sourceFile);
        if (!token)
          return void 0;
        break;
      case 28 /* CommaToken */:
        nTypeArguments++;
        break;
      case 39 /* EqualsGreaterThanToken */:
      case 80 /* Identifier */:
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 114 /* TypeOfKeyword */:
      case 96 /* ExtendsKeyword */:
      case 143 /* KeyOfKeyword */:
      case 25 /* DotToken */:
      case 52 /* BarToken */:
      case 58 /* QuestionToken */:
      case 59 /* ColonToken */:
        break;
      default:
        if (isTypeNode(token)) {
          break;
        }
        return void 0;
    }
    token = findPrecedingToken(token.getFullStart(), sourceFile);
  }
  return void 0;
}
function isInComment(sourceFile, position, tokenAtPosition) {
  return ts_formatting_exports.getRangeOfEnclosingComment(
    sourceFile,
    position,
    /*precedingToken*/
    void 0,
    tokenAtPosition
  );
}
function hasDocComment(sourceFile, position) {
  const token = getTokenAtPosition(sourceFile, position);
  return !!findAncestor(token, isJSDoc);
}
function nodeHasTokens(n, sourceFile) {
  return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node, excludeFlags = 0 /* None */) {
  const result = [];
  const flags = isDeclaration(node) ? getCombinedNodeFlagsAlwaysIncludeJSDoc(node) & ~excludeFlags : 0 /* None */;
  if (flags & 8 /* Private */)
    result.push("private" /* privateMemberModifier */);
  if (flags & 16 /* Protected */)
    result.push("protected" /* protectedMemberModifier */);
  if (flags & 4 /* Public */)
    result.push("public" /* publicMemberModifier */);
  if (flags & 32 /* Static */ || isClassStaticBlockDeclaration(node))
    result.push("static" /* staticModifier */);
  if (flags & 256 /* Abstract */)
    result.push("abstract" /* abstractModifier */);
  if (flags & 1 /* Export */)
    result.push("export" /* exportedModifier */);
  if (flags & 8192 /* Deprecated */)
    result.push("deprecated" /* deprecatedModifier */);
  if (node.flags & 16777216 /* Ambient */)
    result.push("declare" /* ambientModifier */);
  if (node.kind === 276 /* ExportAssignment */)
    result.push("export" /* exportedModifier */);
  return result.length > 0 ? result.join(",") : "" /* none */;
}
function getTypeArgumentOrTypeParameterList(node) {
  if (node.kind === 182 /* TypeReference */ || node.kind === 212 /* CallExpression */) {
    return node.typeArguments;
  }
  if (isFunctionLike(node) || node.kind === 262 /* ClassDeclaration */ || node.kind === 263 /* InterfaceDeclaration */) {
    return node.typeParameters;
  }
  return void 0;
}
function isComment(kind) {
  return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
}
function isStringOrRegularExpressionOrTemplateLiteral(kind) {
  if (kind === 11 /* StringLiteral */ || kind === 14 /* RegularExpressionLiteral */ || isTemplateLiteralKind(kind)) {
    return true;
  }
  return false;
}
function areIntersectedTypesAvoidingStringReduction(checker, t1, t2) {
  return !!(t1.flags & 4 /* String */) && checker.isEmptyAnonymousObjectType(t2);
}
function isStringAndEmptyAnonymousObjectIntersection(type) {
  if (!type.isIntersection()) {
    return false;
  }
  const { types, checker } = type;
  return types.length === 2 && (areIntersectedTypesAvoidingStringReduction(checker, types[0], types[1]) || areIntersectedTypesAvoidingStringReduction(checker, types[1], types[0]));
}
function isInsideTemplateLiteral(node, position, sourceFile) {
  return isTemplateLiteralKind(node.kind) && (node.getStart(sourceFile) < position && position < node.end) || !!node.isUnterminated && position === node.end;
}
function isAccessibilityModifier(kind) {
  switch (kind) {
    case 125 /* PublicKeyword */:
    case 123 /* PrivateKeyword */:
    case 124 /* ProtectedKeyword */:
      return true;
  }
  return false;
}
function cloneCompilerOptions(options) {
  const result = clone(options);
  setConfigFileInOptions(result, options && options.configFile);
  return result;
}
function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
  if (node.kind === 208 /* ArrayLiteralExpression */ || node.kind === 209 /* ObjectLiteralExpression */) {
    if (node.parent.kind === 225 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */) {
      return true;
    }
    if (node.parent.kind === 249 /* ForOfStatement */ && node.parent.initializer === node) {
      return true;
    }
    if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 302 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
      return true;
    }
  }
  return false;
}
function isInReferenceComment(sourceFile, position) {
  return isInReferenceCommentWorker(
    sourceFile,
    position,
    /*shouldBeReference*/
    true
  );
}
function isInNonReferenceComment(sourceFile, position) {
  return isInReferenceCommentWorker(
    sourceFile,
    position,
    /*shouldBeReference*/
    false
  );
}
function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
  const range = isInComment(
    sourceFile,
    position,
    /*tokenAtPosition*/
    void 0
  );
  return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
}
function getReplacementSpanForContextToken(contextToken) {
  if (!contextToken)
    return void 0;
  switch (contextToken.kind) {
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
      return createTextSpanFromStringLiteralLikeContent(contextToken);
    default:
      return createTextSpanFromNode(contextToken);
  }
}
function createTextSpanFromNode(node, sourceFile, endNode2) {
  return createTextSpanFromBounds(node.getStart(sourceFile), (endNode2 || node).getEnd());
}
function createTextSpanFromStringLiteralLikeContent(node) {
  if (node.isUnterminated)
    return void 0;
  return createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1);
}
function createTextRangeFromNode(node, sourceFile) {
  return createRange(node.getStart(sourceFile), node.end);
}
function createTextSpanFromRange(range) {
  return createTextSpanFromBounds(range.pos, range.end);
}
function createTextRangeFromSpan(span) {
  return createRange(span.start, span.start + span.length);
}
function createTextChangeFromStartLength(start2, length2, newText) {
  return createTextChange(createTextSpan(start2, length2), newText);
}
function createTextChange(span, newText) {
  return { span, newText };
}
var typeKeywords = [
  133 /* AnyKeyword */,
  131 /* AssertsKeyword */,
  162 /* BigIntKeyword */,
  136 /* BooleanKeyword */,
  97 /* FalseKeyword */,
  140 /* InferKeyword */,
  143 /* KeyOfKeyword */,
  146 /* NeverKeyword */,
  106 /* NullKeyword */,
  150 /* NumberKeyword */,
  151 /* ObjectKeyword */,
  148 /* ReadonlyKeyword */,
  154 /* StringKeyword */,
  155 /* SymbolKeyword */,
  114 /* TypeOfKeyword */,
  112 /* TrueKeyword */,
  116 /* VoidKeyword */,
  157 /* UndefinedKeyword */,
  158 /* UniqueKeyword */,
  159 /* UnknownKeyword */
];
function isTypeKeyword(kind) {
  return contains(typeKeywords, kind);
}
function isTypeKeywordToken(node) {
  return node.kind === 156 /* TypeKeyword */;
}
function isTypeKeywordTokenOrIdentifier(node) {
  return isTypeKeywordToken(node) || isIdentifier(node) && node.text === "type";
}
function isExternalModuleSymbol(moduleSymbol) {
  return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
}
function nodeSeenTracker() {
  const seen = [];
  return (node) => {
    const id = getNodeId(node);
    return !seen[id] && (seen[id] = true);
  };
}
function getSnapshotText(snap) {
  return snap.getText(0, snap.getLength());
}
function repeatString(str, count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += str;
  }
  return result;
}
function skipConstraint(type) {
  return type.isTypeParameter() ? type.getConstraint() || type : type;
}
function getNameFromPropertyName(name) {
  return name.kind === 166 /* ComputedPropertyName */ ? isStringOrNumericLiteralLike(name.expression) ? name.expression.text : void 0 : isPrivateIdentifier(name) ? idText(name) : getTextOfIdentifierOrLiteral(name);
}
function programContainsModules(program) {
  return program.getSourceFiles().some((s) => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator));
}
function programContainsEsModules(program) {
  return program.getSourceFiles().some((s) => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator);
}
function compilerOptionsIndicateEsModules(compilerOptions) {
  return !!compilerOptions.module || getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit;
}
function createModuleSpecifierResolutionHost(program, host) {
  return {
    fileExists: (fileName) => program.fileExists(fileName),
    getCurrentDirectory: () => host.getCurrentDirectory(),
    readFile: maybeBind(host, host.readFile),
    useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames),
    getSymlinkCache: maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache,
    getModuleSpecifierCache: maybeBind(host, host.getModuleSpecifierCache),
    getPackageJsonInfoCache: () => {
      var _a;
      return (_a = program.getModuleResolutionCache()) == null ? void 0 : _a.getPackageJsonInfoCache();
    },
    getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation),
    redirectTargetsMap: program.redirectTargetsMap,
    getProjectReferenceRedirect: (fileName) => program.getProjectReferenceRedirect(fileName),
    isSourceOfProjectReferenceRedirect: (fileName) => program.isSourceOfProjectReferenceRedirect(fileName),
    getNearestAncestorDirectoryWithPackageJson: maybeBind(host, host.getNearestAncestorDirectoryWithPackageJson),
    getFileIncludeReasons: () => program.getFileIncludeReasons()
  };
}
function getModuleSpecifierResolverHost(program, host) {
  return {
    ...createModuleSpecifierResolutionHost(program, host),
    getCommonSourceDirectory: () => program.getCommonSourceDirectory()
  };
}
function moduleResolutionUsesNodeModules(moduleResolution) {
  return moduleResolution === 2 /* Node10 */ || moduleResolution >= 3 /* Node16 */ && moduleResolution <= 99 /* NodeNext */ || moduleResolution === 100 /* Bundler */;
}
function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) {
  return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : void 0;
}
function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) {
  return factory.createImportDeclaration(
    /*modifiers*/
    void 0,
    defaultImport || namedImports ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : void 0) : void 0,
    typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier,
    /*assertClause*/
    void 0
  );
}
function makeStringLiteral(text, quotePreference) {
  return factory.createStringLiteral(text, quotePreference === 0 /* Single */);
}
var QuotePreference = /* @__PURE__ */ ((QuotePreference7) => {
  QuotePreference7[QuotePreference7["Single"] = 0] = "Single";
  QuotePreference7[QuotePreference7["Double"] = 1] = "Double";
  return QuotePreference7;
})(QuotePreference || {});
function quotePreferenceFromString(str, sourceFile) {
  return isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
}
function getQuotePreference(sourceFile, preferences) {
  if (preferences.quotePreference && preferences.quotePreference !== "auto") {
    return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
  } else {
    const firstModuleSpecifier = sourceFile.imports && find(sourceFile.imports, (n) => isStringLiteral(n) && !nodeIsSynthesized(n.parent));
    return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
  }
}
function getQuoteFromPreference(qp) {
  switch (qp) {
    case 0 /* Single */:
      return "'";
    case 1 /* Double */:
      return '"';
    default:
      return Debug.assertNever(qp);
  }
}
function symbolNameNoDefault(symbol) {
  const escaped = symbolEscapedNameNoDefault(symbol);
  return escaped === void 0 ? void 0 : unescapeLeadingUnderscores(escaped);
}
function symbolEscapedNameNoDefault(symbol) {
  if (symbol.escapedName !== "default" /* Default */) {
    return symbol.escapedName;
  }
  return firstDefined(symbol.declarations, (decl) => {
    const name = getNameOfDeclaration(decl);
    return name && name.kind === 80 /* Identifier */ ? name.escapedText : void 0;
  });
}
function isModuleSpecifierLike(node) {
  return isStringLiteralLike(node) && (isExternalModuleReference(node.parent) || isImportDeclaration(node.parent) || isRequireCall(
    node.parent,
    /*requireStringLiteralLikeArgument*/
    false
  ) && node.parent.arguments[0] === node || isImportCall(node.parent) && node.parent.arguments[0] === node);
}
function isObjectBindingElementWithoutPropertyName(bindingElement) {
  return isBindingElement(bindingElement) && isObjectBindingPattern(bindingElement.parent) && isIdentifier(bindingElement.name) && !bindingElement.propertyName;
}
function getPropertySymbolFromBindingElement(checker, bindingElement) {
  const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
  return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
}
function getParentNodeInSpan(node, file, span) {
  if (!node)
    return void 0;
  while (node.parent) {
    if (isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) {
      return node;
    }
    node = node.parent;
  }
}
function spanContainsNode(span, node, file) {
  return textSpanContainsPosition(span, node.getStart(file)) && node.getEnd() <= textSpanEnd(span);
}
function findModifier(node, kind) {
  return canHaveModifiers(node) ? find(node.modifiers, (m) => m.kind === kind) : void 0;
}
function insertImports(changes, sourceFile, imports, blankLineBetween, preferences) {
  const decl = isArray(imports) ? imports[0] : imports;
  const importKindPredicate = decl.kind === 242 /* VariableStatement */ ? isRequireVariableStatement : isAnyImportSyntax;
  const existingImportStatements = filter(sourceFile.statements, importKindPredicate);
  let sortKind = isArray(imports) ? ts_OrganizeImports_exports.detectImportDeclarationSorting(imports, preferences) : 3 /* Both */;
  const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */);
  const sortedNewImports = isArray(imports) ? stableSort(imports, (a, b) => ts_OrganizeImports_exports.compareImportsOrRequireStatements(a, b, comparer)) : [imports];
  if (!existingImportStatements.length) {
    changes.insertNodesAtTopOfFile(sourceFile, sortedNewImports, blankLineBetween);
  } else if (existingImportStatements && (sortKind = ts_OrganizeImports_exports.detectImportDeclarationSorting(existingImportStatements, preferences))) {
    const comparer2 = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */);
    for (const newImport of sortedNewImports) {
      const insertionIndex = ts_OrganizeImports_exports.getImportDeclarationInsertionIndex(existingImportStatements, newImport, comparer2);
      if (insertionIndex === 0) {
        const options = existingImportStatements[0] === sourceFile.statements[0] ? { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude } : {};
        changes.insertNodeBefore(
          sourceFile,
          existingImportStatements[0],
          newImport,
          /*blankLineBetween*/
          false,
          options
        );
      } else {
        const prevImport = existingImportStatements[insertionIndex - 1];
        changes.insertNodeAfter(sourceFile, prevImport, newImport);
      }
    }
  } else {
    const lastExistingImport = lastOrUndefined(existingImportStatements);
    if (lastExistingImport) {
      changes.insertNodesAfter(sourceFile, lastExistingImport, sortedNewImports);
    } else {
      changes.insertNodesAtTopOfFile(sourceFile, sortedNewImports, blankLineBetween);
    }
  }
}
function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) {
  Debug.assert(importClause.isTypeOnly);
  return cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken);
}
function textSpansEqual(a, b) {
  return !!a && !!b && a.start === b.start && a.length === b.length;
}
function documentSpansEqual(a, b) {
  return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan);
}
function forEachUnique(array, callback) {
  if (array) {
    for (let i = 0; i < array.length; i++) {
      if (array.indexOf(array[i]) === i) {
        const result = callback(array[i], i);
        if (result) {
          return result;
        }
      }
    }
  }
  return void 0;
}
function isTextWhiteSpaceLike(text, startPos, endPos) {
  for (let i = startPos; i < endPos; i++) {
    if (!isWhiteSpaceLike(text.charCodeAt(i))) {
      return false;
    }
  }
  return true;
}
function getMappedLocation(location, sourceMapper, fileExists) {
  const mapsTo = sourceMapper.tryGetSourcePosition(location);
  return mapsTo && (!fileExists || fileExists(normalizePath(mapsTo.fileName)) ? mapsTo : void 0);
}
function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) {
  const { fileName, textSpan } = documentSpan;
  const newPosition = getMappedLocation({ fileName, pos: textSpan.start }, sourceMapper, fileExists);
  if (!newPosition)
    return void 0;
  const newEndPosition = getMappedLocation({ fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists);
  const newLength = newEndPosition ? newEndPosition.pos - newPosition.pos : textSpan.length;
  return {
    fileName: newPosition.fileName,
    textSpan: {
      start: newPosition.pos,
      length: newLength
    },
    originalFileName: documentSpan.fileName,
    originalTextSpan: documentSpan.textSpan,
    contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists),
    originalContextSpan: documentSpan.contextSpan
  };
}
function getMappedContextSpan(documentSpan, sourceMapper, fileExists) {
  const contextSpanStart = documentSpan.contextSpan && getMappedLocation(
    { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start },
    sourceMapper,
    fileExists
  );
  const contextSpanEnd = documentSpan.contextSpan && getMappedLocation(
    { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length },
    sourceMapper,
    fileExists
  );
  return contextSpanStart && contextSpanEnd ? { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : void 0;
}
function isFirstDeclarationOfSymbolParameter(symbol) {
  const declaration = symbol.declarations ? firstOrUndefined(symbol.declarations) : void 0;
  return !!findAncestor(declaration, (n) => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit");
}
var displayPartWriter = getDisplayPartWriter();
function getDisplayPartWriter() {
  const absoluteMaximumLength = defaultMaximumTruncationLength * 10;
  let displayParts;
  let lineStart;
  let indent3;
  let length2;
  resetWriter();
  const unknownWrite = (text) => writeKind(text, 17 /* text */);
  return {
    displayParts: () => {
      const finalText = displayParts.length && displayParts[displayParts.length - 1].text;
      if (length2 > absoluteMaximumLength && finalText && finalText !== "...") {
        if (!isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) {
          displayParts.push(displayPart(" ", 16 /* space */));
        }
        displayParts.push(displayPart("...", 15 /* punctuation */));
      }
      return displayParts;
    },
    writeKeyword: (text) => writeKind(text, 5 /* keyword */),
    writeOperator: (text) => writeKind(text, 12 /* operator */),
    writePunctuation: (text) => writeKind(text, 15 /* punctuation */),
    writeTrailingSemicolon: (text) => writeKind(text, 15 /* punctuation */),
    writeSpace: (text) => writeKind(text, 16 /* space */),
    writeStringLiteral: (text) => writeKind(text, 8 /* stringLiteral */),
    writeParameter: (text) => writeKind(text, 13 /* parameterName */),
    writeProperty: (text) => writeKind(text, 14 /* propertyName */),
    writeLiteral: (text) => writeKind(text, 8 /* stringLiteral */),
    writeSymbol,
    writeLine,
    write: unknownWrite,
    writeComment: unknownWrite,
    getText: () => "",
    getTextPos: () => 0,
    getColumn: () => 0,
    getLine: () => 0,
    isAtStartOfLine: () => false,
    hasTrailingWhitespace: () => false,
    hasTrailingComment: () => false,
    rawWrite: notImplemented,
    getIndent: () => indent3,
    increaseIndent: () => {
      indent3++;
    },
    decreaseIndent: () => {
      indent3--;
    },
    clear: resetWriter
  };
  function writeIndent() {
    if (length2 > absoluteMaximumLength)
      return;
    if (lineStart) {
      const indentString = getIndentString(indent3);
      if (indentString) {
        length2 += indentString.length;
        displayParts.push(displayPart(indentString, 16 /* space */));
      }
      lineStart = false;
    }
  }
  function writeKind(text, kind) {
    if (length2 > absoluteMaximumLength)
      return;
    writeIndent();
    length2 += text.length;
    displayParts.push(displayPart(text, kind));
  }
  function writeSymbol(text, symbol) {
    if (length2 > absoluteMaximumLength)
      return;
    writeIndent();
    length2 += text.length;
    displayParts.push(symbolPart(text, symbol));
  }
  function writeLine() {
    if (length2 > absoluteMaximumLength)
      return;
    length2 += 1;
    displayParts.push(lineBreakPart());
    lineStart = true;
  }
  function resetWriter() {
    displayParts = [];
    lineStart = true;
    indent3 = 0;
    length2 = 0;
  }
}
function symbolPart(text, symbol) {
  return displayPart(text, displayPartKind(symbol));
  function displayPartKind(symbol2) {
    const flags = symbol2.flags;
    if (flags & 3 /* Variable */) {
      return isFirstDeclarationOfSymbolParameter(symbol2) ? 13 /* parameterName */ : 9 /* localName */;
    }
    if (flags & 4 /* Property */)
      return 14 /* propertyName */;
    if (flags & 32768 /* GetAccessor */)
      return 14 /* propertyName */;
    if (flags & 65536 /* SetAccessor */)
      return 14 /* propertyName */;
    if (flags & 8 /* EnumMember */)
      return 19 /* enumMemberName */;
    if (flags & 16 /* Function */)
      return 20 /* functionName */;
    if (flags & 32 /* Class */)
      return 1 /* className */;
    if (flags & 64 /* Interface */)
      return 4 /* interfaceName */;
    if (flags & 384 /* Enum */)
      return 2 /* enumName */;
    if (flags & 1536 /* Module */)
      return 11 /* moduleName */;
    if (flags & 8192 /* Method */)
      return 10 /* methodName */;
    if (flags & 262144 /* TypeParameter */)
      return 18 /* typeParameterName */;
    if (flags & 524288 /* TypeAlias */)
      return 0 /* aliasName */;
    if (flags & 2097152 /* Alias */)
      return 0 /* aliasName */;
    return 17 /* text */;
  }
}
function displayPart(text, kind) {
  return { text, kind: SymbolDisplayPartKind[kind] };
}
function spacePart() {
  return displayPart(" ", 16 /* space */);
}
function keywordPart(kind) {
  return displayPart(tokenToString(kind), 5 /* keyword */);
}
function punctuationPart(kind) {
  return displayPart(tokenToString(kind), 15 /* punctuation */);
}
function operatorPart(kind) {
  return displayPart(tokenToString(kind), 12 /* operator */);
}
function parameterNamePart(text) {
  return displayPart(text, 13 /* parameterName */);
}
function propertyNamePart(text) {
  return displayPart(text, 14 /* propertyName */);
}
function textOrKeywordPart(text) {
  const kind = stringToToken(text);
  return kind === void 0 ? textPart(text) : keywordPart(kind);
}
function textPart(text) {
  return displayPart(text, 17 /* text */);
}
function typeAliasNamePart(text) {
  return displayPart(text, 0 /* aliasName */);
}
function typeParameterNamePart(text) {
  return displayPart(text, 18 /* typeParameterName */);
}
function linkTextPart(text) {
  return displayPart(text, 24 /* linkText */);
}
function linkNamePart(text, target) {
  return {
    text,
    kind: SymbolDisplayPartKind[23 /* linkName */],
    target: {
      fileName: getSourceFileOfNode(target).fileName,
      textSpan: createTextSpanFromNode(target)
    }
  };
}
function linkPart(text) {
  return displayPart(text, 22 /* link */);
}
function buildLinkParts(link, checker) {
  var _a;
  const prefix = isJSDocLink(link) ? "link" : isJSDocLinkCode(link) ? "linkcode" : "linkplain";
  const parts = [linkPart(`{@${prefix} `)];
  if (!link.name) {
    if (link.text) {
      parts.push(linkTextPart(link.text));
    }
  } else {
    const symbol = checker == null ? void 0 : checker.getSymbolAtLocation(link.name);
    const suffix = findLinkNameEnd(link.text);
    const name = getTextOfNode(link.name) + link.text.slice(0, suffix);
    const text = skipSeparatorFromLinkText(link.text.slice(suffix));
    const decl = (symbol == null ? void 0 : symbol.valueDeclaration) || ((_a = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a[0]);
    if (decl) {
      parts.push(linkNamePart(name, decl));
      if (text)
        parts.push(linkTextPart(text));
    } else {
      parts.push(linkTextPart(name + (suffix ? "" : " ") + text));
    }
  }
  parts.push(linkPart("}"));
  return parts;
}
function skipSeparatorFromLinkText(text) {
  let pos = 0;
  if (text.charCodeAt(pos++) === 124 /* bar */) {
    while (pos < text.length && text.charCodeAt(pos) === 32 /* space */)
      pos++;
    return text.slice(pos);
  }
  return text;
}
function findLinkNameEnd(text) {
  let pos = text.indexOf("://");
  if (pos === 0) {
    while (pos < text.length && text.charCodeAt(pos) !== 124 /* bar */)
      pos++;
    return pos;
  }
  if (text.indexOf("()") === 0)
    return 2;
  if (text.charAt(0) === "<") {
    let brackets2 = 0;
    let i = 0;
    while (i < text.length) {
      if (text[i] === "<")
        brackets2++;
      if (text[i] === ">")
        brackets2--;
      i++;
      if (!brackets2)
        return i;
    }
  }
  return 0;
}
var lineFeed2 = "\n";
function getNewLineOrDefaultFromHost(host, formatSettings) {
  var _a;
  return (formatSettings == null ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) == null ? void 0 : _a.call(host)) || lineFeed2;
}
function lineBreakPart() {
  return displayPart("\n", 6 /* lineBreak */);
}
function mapToDisplayParts(writeDisplayParts) {
  try {
    writeDisplayParts(displayPartWriter);
    return displayPartWriter.displayParts();
  } finally {
    displayPartWriter.clear();
  }
}
function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags = 0 /* None */) {
  return mapToDisplayParts((writer) => {
    typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer);
  });
}
function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags = 0 /* None */) {
  return mapToDisplayParts((writer) => {
    typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer);
  });
}
function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags = 0 /* None */) {
  flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */;
  return mapToDisplayParts((writer) => {
    typechecker.writeSignature(
      signature,
      enclosingDeclaration,
      flags,
      /*kind*/
      void 0,
      writer
    );
  });
}
function nodeToDisplayParts(node, enclosingDeclaration) {
  const file = enclosingDeclaration.getSourceFile();
  return mapToDisplayParts((writer) => {
    const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon();
    printer.writeNode(4 /* Unspecified */, node, file, writer);
  });
}
function isImportOrExportSpecifierName(location) {
  return !!location.parent && isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
}
function getScriptKind(fileName, host) {
  return ensureScriptKind(fileName, host.getScriptKind && host.getScriptKind(fileName));
}
function getSymbolTarget(symbol, checker) {
  let next = symbol;
  while (isAliasSymbol(next) || isTransientSymbol(next) && next.links.target) {
    if (isTransientSymbol(next) && next.links.target) {
      next = next.links.target;
    } else {
      next = skipAlias(next, checker);
    }
  }
  return next;
}
function isAliasSymbol(symbol) {
  return (symbol.flags & 2097152 /* Alias */) !== 0;
}
function getUniqueSymbolId(symbol, checker) {
  return getSymbolId(skipAlias(symbol, checker));
}
function getFirstNonSpaceCharacterPosition(text, position) {
  while (isWhiteSpaceLike(text.charCodeAt(position))) {
    position += 1;
  }
  return position;
}
function getPrecedingNonSpaceCharacterPosition(text, position) {
  while (position > -1 && isWhiteSpaceSingleLine(text.charCodeAt(position))) {
    position -= 1;
  }
  return position + 1;
}
function getSynthesizedDeepClone(node, includeTrivia = true) {
  const clone2 = node && getSynthesizedDeepCloneWorker(node);
  if (clone2 && !includeTrivia)
    suppressLeadingAndTrailingTrivia(clone2);
  return clone2;
}
function getSynthesizedDeepCloneWithReplacements(node, includeTrivia, replaceNode) {
  let clone2 = replaceNode(node);
  if (clone2) {
    setOriginalNode(clone2, node);
  } else {
    clone2 = getSynthesizedDeepCloneWorker(node, replaceNode);
  }
  if (clone2 && !includeTrivia)
    suppressLeadingAndTrailingTrivia(clone2);
  return clone2;
}
function getSynthesizedDeepCloneWorker(node, replaceNode) {
  const nodeClone = replaceNode ? (n) => getSynthesizedDeepCloneWithReplacements(
    n,
    /*includeTrivia*/
    true,
    replaceNode
  ) : getSynthesizedDeepClone;
  const nodesClone = replaceNode ? (ns) => ns && getSynthesizedDeepClonesWithReplacements(
    ns,
    /*includeTrivia*/
    true,
    replaceNode
  ) : (ns) => ns && getSynthesizedDeepClones(ns);
  const visited = visitEachChild(node, nodeClone, nullTransformationContext, nodesClone, nodeClone);
  if (visited === node) {
    const clone2 = isStringLiteral(node) ? setOriginalNode(factory.createStringLiteralFromNode(node), node) : isNumericLiteral(node) ? setOriginalNode(factory.createNumericLiteral(node.text, node.numericLiteralFlags), node) : factory.cloneNode(node);
    return setTextRange(clone2, node);
  }
  visited.parent = void 0;
  return visited;
}
function getSynthesizedDeepClones(nodes, includeTrivia = true) {
  if (nodes) {
    const cloned = factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma);
    setTextRange(cloned, nodes);
    return cloned;
  }
  return nodes;
}
function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) {
  return factory.createNodeArray(nodes.map((n) => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma);
}
function suppressLeadingAndTrailingTrivia(node) {
  suppressLeadingTrivia(node);
  suppressTrailingTrivia(node);
}
function suppressLeadingTrivia(node) {
  addEmitFlagsRecursively(node, 1024 /* NoLeadingComments */, getFirstChild);
}
function suppressTrailingTrivia(node) {
  addEmitFlagsRecursively(node, 2048 /* NoTrailingComments */, getLastChild);
}
function copyComments(sourceNode, targetNode) {
  const sourceFile = sourceNode.getSourceFile();
  const text = sourceFile.text;
  if (hasLeadingLineBreak(sourceNode, text)) {
    copyLeadingComments(sourceNode, targetNode, sourceFile);
  } else {
    copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
  }
  copyTrailingComments(sourceNode, targetNode, sourceFile);
}
function hasLeadingLineBreak(node, text) {
  const start2 = node.getFullStart();
  const end = node.getStart();
  for (let i = start2; i < end; i++) {
    if (text.charCodeAt(i) === 10 /* lineFeed */)
      return true;
  }
  return false;
}
function addEmitFlagsRecursively(node, flag, getChild) {
  addEmitFlags(node, flag);
  const child = getChild(node);
  if (child)
    addEmitFlagsRecursively(child, flag, getChild);
}
function getFirstChild(node) {
  return node.forEachChild((child) => child);
}
function getUniqueName(baseName, sourceFile) {
  let nameText = baseName;
  for (let i = 1; !isFileLevelUniqueName(sourceFile, nameText); i++) {
    nameText = `${baseName}_${i}`;
  }
  return nameText;
}
function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
  let delta = 0;
  let lastPos = -1;
  for (const { fileName, textChanges: textChanges2 } of edits) {
    Debug.assert(fileName === renameFilename);
    for (const change of textChanges2) {
      const { span, newText } = change;
      const index = indexInTextChange(newText, escapeString(name));
      if (index !== -1) {
        lastPos = span.start + delta + index;
        if (!preferLastLocation) {
          return lastPos;
        }
      }
      delta += newText.length - span.length;
    }
  }
  Debug.assert(preferLastLocation);
  Debug.assert(lastPos >= 0);
  return lastPos;
}
function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment));
}
function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticTrailingComment));
}
function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
  forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment));
}
function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
  return (pos, end, kind, htnl) => {
    if (kind === 3 /* MultiLineCommentTrivia */) {
      pos += 2;
      end -= 2;
    } else {
      pos += 2;
    }
    cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== void 0 ? hasTrailingNewLine : htnl);
  };
}
function indexInTextChange(change, name) {
  if (startsWith(change, name))
    return 0;
  let idx = change.indexOf(" " + name);
  if (idx === -1)
    idx = change.indexOf("." + name);
  if (idx === -1)
    idx = change.indexOf('"' + name);
  return idx === -1 ? -1 : idx + 1;
}
function needsParentheses(expression) {
  return isBinaryExpression(expression) && expression.operatorToken.kind === 28 /* CommaToken */ || isObjectLiteralExpression(expression) || isAsExpression(expression) && isObjectLiteralExpression(expression.expression);
}
function getContextualTypeFromParent(node, checker, contextFlags) {
  const parent2 = walkUpParenthesizedExpressions(node.parent);
  switch (parent2.kind) {
    case 213 /* NewExpression */:
      return checker.getContextualType(parent2, contextFlags);
    case 225 /* BinaryExpression */: {
      const { left, operatorToken, right } = parent2;
      return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node, contextFlags);
    }
    case 295 /* CaseClause */:
      return getSwitchedType(parent2, checker);
    default:
      return checker.getContextualType(node, contextFlags);
  }
}
function quote(sourceFile, preferences, text) {
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const quoted = JSON.stringify(text);
  return quotePreference === 0 /* Single */ ? `'${stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"')}'` : quoted;
}
function isEqualityOperatorKind(kind) {
  switch (kind) {
    case 37 /* EqualsEqualsEqualsToken */:
    case 35 /* EqualsEqualsToken */:
    case 38 /* ExclamationEqualsEqualsToken */:
    case 36 /* ExclamationEqualsToken */:
      return true;
    default:
      return false;
  }
}
function isStringLiteralOrTemplate(node) {
  switch (node.kind) {
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 227 /* TemplateExpression */:
    case 214 /* TaggedTemplateExpression */:
      return true;
    default:
      return false;
  }
}
function hasIndexSignature(type) {
  return !!type.getStringIndexType() || !!type.getNumberIndexType();
}
function getSwitchedType(caseClause, checker) {
  return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
var ANONYMOUS = "anonymous function";
function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
  const checker = program.getTypeChecker();
  let typeIsAccessible = true;
  const notAccessible = () => typeIsAccessible = false;
  const res = checker.typeToTypeNode(type, enclosingScope, 1 /* NoTruncation */, {
    trackSymbol: (symbol, declaration, meaning) => {
      typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(
        symbol,
        declaration,
        meaning,
        /*shouldComputeAliasToMarkVisible*/
        false
      ).accessibility === 0 /* Accessible */;
      return !typeIsAccessible;
    },
    reportInaccessibleThisError: notAccessible,
    reportPrivateInBaseOfClassExpression: notAccessible,
    reportInaccessibleUniqueSymbolError: notAccessible,
    moduleResolverHost: getModuleSpecifierResolverHost(program, host)
  });
  return typeIsAccessible ? res : void 0;
}
function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) {
  return kind === 178 /* CallSignature */ || kind === 179 /* ConstructSignature */ || kind === 180 /* IndexSignature */ || kind === 170 /* PropertySignature */ || kind === 172 /* MethodSignature */;
}
function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) {
  return kind === 261 /* FunctionDeclaration */ || kind === 175 /* Constructor */ || kind === 173 /* MethodDeclaration */ || kind === 176 /* GetAccessor */ || kind === 177 /* SetAccessor */;
}
function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) {
  return kind === 266 /* ModuleDeclaration */;
}
function syntaxRequiresTrailingSemicolonOrASI(kind) {
  return kind === 242 /* VariableStatement */ || kind === 243 /* ExpressionStatement */ || kind === 245 /* DoStatement */ || kind === 250 /* ContinueStatement */ || kind === 251 /* BreakStatement */ || kind === 252 /* ReturnStatement */ || kind === 256 /* ThrowStatement */ || kind === 258 /* DebuggerStatement */ || kind === 171 /* PropertyDeclaration */ || kind === 264 /* TypeAliasDeclaration */ || kind === 271 /* ImportDeclaration */ || kind === 270 /* ImportEqualsDeclaration */ || kind === 277 /* ExportDeclaration */ || kind === 269 /* NamespaceExportDeclaration */ || kind === 276 /* ExportAssignment */;
}
var syntaxMayBeASICandidate = or(
  syntaxRequiresTrailingCommaOrSemicolonOrASI,
  syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI,
  syntaxRequiresTrailingModuleBlockOrSemicolonOrASI,
  syntaxRequiresTrailingSemicolonOrASI
);
function nodeIsASICandidate(node, sourceFile) {
  const lastToken = node.getLastToken(sourceFile);
  if (lastToken && lastToken.kind === 27 /* SemicolonToken */) {
    return false;
  }
  if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
    if (lastToken && lastToken.kind === 28 /* CommaToken */) {
      return false;
    }
  } else if (syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(node.kind)) {
    const lastChild = last(node.getChildren(sourceFile));
    if (lastChild && isModuleBlock(lastChild)) {
      return false;
    }
  } else if (syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(node.kind)) {
    const lastChild = last(node.getChildren(sourceFile));
    if (lastChild && isFunctionBlock(lastChild)) {
      return false;
    }
  } else if (!syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
    return false;
  }
  if (node.kind === 245 /* DoStatement */) {
    return true;
  }
  const topNode = findAncestor(node, (ancestor) => !ancestor.parent);
  const nextToken = findNextToken(node, topNode, sourceFile);
  if (!nextToken || nextToken.kind === 20 /* CloseBraceToken */) {
    return true;
  }
  const startLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
  const endLine = sourceFile.getLineAndCharacterOfPosition(nextToken.getStart(sourceFile)).line;
  return startLine !== endLine;
}
function positionIsASICandidate(pos, context, sourceFile) {
  const contextAncestor = findAncestor(context, (ancestor) => {
    if (ancestor.end !== pos) {
      return "quit";
    }
    return syntaxMayBeASICandidate(ancestor.kind);
  });
  return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile);
}
function probablyUsesSemicolons(sourceFile) {
  let withSemicolon = 0;
  let withoutSemicolon = 0;
  const nStatementsToObserve = 5;
  forEachChild(sourceFile, function visit(node) {
    if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
      const lastToken = node.getLastToken(sourceFile);
      if ((lastToken == null ? void 0 : lastToken.kind) === 27 /* SemicolonToken */) {
        withSemicolon++;
      } else {
        withoutSemicolon++;
      }
    } else if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
      const lastToken = node.getLastToken(sourceFile);
      if ((lastToken == null ? void 0 : lastToken.kind) === 27 /* SemicolonToken */) {
        withSemicolon++;
      } else if (lastToken && lastToken.kind !== 28 /* CommaToken */) {
        const lastTokenLine = getLineAndCharacterOfPosition(sourceFile, lastToken.getStart(sourceFile)).line;
        const nextTokenLine = getLineAndCharacterOfPosition(sourceFile, getSpanOfTokenAtPosition(sourceFile, lastToken.end).start).line;
        if (lastTokenLine !== nextTokenLine) {
          withoutSemicolon++;
        }
      }
    }
    if (withSemicolon + withoutSemicolon >= nStatementsToObserve) {
      return true;
    }
    return forEachChild(node, visit);
  });
  if (withSemicolon === 0 && withoutSemicolon <= 1) {
    return true;
  }
  return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve;
}
function tryGetDirectories(host, directoryName) {
  return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || [];
}
function tryReadDirectory(host, path, extensions, exclude, include) {
  return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray;
}
function tryFileExists(host, path) {
  return tryIOAndConsumeErrors(host, host.fileExists, path);
}
function tryDirectoryExists(host, path) {
  return tryAndIgnoreErrors(() => directoryProbablyExists(path, host)) || false;
}
function tryAndIgnoreErrors(cb) {
  try {
    return cb();
  } catch {
    return void 0;
  }
}
function tryIOAndConsumeErrors(host, toApply, ...args) {
  return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args));
}
function findPackageJsons(startDirectory, host, stopDirectory) {
  const paths = [];
  forEachAncestorDirectory(startDirectory, (ancestor) => {
    if (ancestor === stopDirectory) {
      return true;
    }
    const currentConfigPath = combinePaths(ancestor, "package.json");
    if (tryFileExists(host, currentConfigPath)) {
      paths.push(currentConfigPath);
    }
  });
  return paths;
}
function findPackageJson(directory, host) {
  let packageJson;
  forEachAncestorDirectory(directory, (ancestor) => {
    if (ancestor === "node_modules")
      return true;
    packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json");
    if (packageJson) {
      return true;
    }
  });
  return packageJson;
}
function getPackageJsonsVisibleToFile(fileName, host) {
  if (!host.fileExists) {
    return [];
  }
  const packageJsons = [];
  forEachAncestorDirectory(getDirectoryPath(fileName), (ancestor) => {
    const packageJsonFileName = combinePaths(ancestor, "package.json");
    if (host.fileExists(packageJsonFileName)) {
      const info = createPackageJsonInfo(packageJsonFileName, host);
      if (info) {
        packageJsons.push(info);
      }
    }
  });
  return packageJsons;
}
function createPackageJsonInfo(fileName, host) {
  if (!host.readFile) {
    return void 0;
  }
  const dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
  const stringContent = host.readFile(fileName) || "";
  const content = tryParseJson(stringContent);
  const info = {};
  if (content) {
    for (const key of dependencyKeys) {
      const dependencies = content[key];
      if (!dependencies) {
        continue;
      }
      const dependencyMap = /* @__PURE__ */ new Map();
      for (const packageName in dependencies) {
        dependencyMap.set(packageName, dependencies[packageName]);
      }
      info[key] = dependencyMap;
    }
  }
  const dependencyGroups = [
    [1 /* Dependencies */, info.dependencies],
    [2 /* DevDependencies */, info.devDependencies],
    [8 /* OptionalDependencies */, info.optionalDependencies],
    [4 /* PeerDependencies */, info.peerDependencies]
  ];
  return {
    ...info,
    parseable: !!content,
    fileName,
    get,
    has(dependencyName, inGroups) {
      return !!get(dependencyName, inGroups);
    }
  };
  function get(dependencyName, inGroups = 15 /* All */) {
    for (const [group2, deps] of dependencyGroups) {
      if (deps && inGroups & group2) {
        const dep = deps.get(dependencyName);
        if (dep !== void 0) {
          return dep;
        }
      }
    }
  }
}
function createPackageJsonImportFilter(fromFile, preferences, host) {
  const packageJsons = (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter((p) => p.parseable);
  let usesNodeCoreModules;
  let ambientModuleCache;
  let sourceFileCache;
  return {
    allowsImportingAmbientModule,
    allowsImportingSourceFile,
    allowsImportingSpecifier
  };
  function moduleSpecifierIsCoveredByPackageJson(specifier) {
    const packageName = getNodeModuleRootSpecifier(specifier);
    for (const packageJson of packageJsons) {
      if (packageJson.has(packageName) || packageJson.has(getTypesPackageName(packageName))) {
        return true;
      }
    }
    return false;
  }
  function allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) {
    if (!packageJsons.length || !moduleSymbol.valueDeclaration) {
      return true;
    }
    if (!ambientModuleCache) {
      ambientModuleCache = /* @__PURE__ */ new Map();
    } else {
      const cached = ambientModuleCache.get(moduleSymbol);
      if (cached !== void 0) {
        return cached;
      }
    }
    const declaredModuleSpecifier = stripQuotes(moduleSymbol.getName());
    if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) {
      ambientModuleCache.set(moduleSymbol, true);
      return true;
    }
    const declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
    const declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost);
    if (typeof declaringNodeModuleName === "undefined") {
      ambientModuleCache.set(moduleSymbol, true);
      return true;
    }
    const result = moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
    ambientModuleCache.set(moduleSymbol, result);
    return result;
  }
  function allowsImportingSourceFile(sourceFile, moduleSpecifierResolutionHost) {
    if (!packageJsons.length) {
      return true;
    }
    if (!sourceFileCache) {
      sourceFileCache = /* @__PURE__ */ new Map();
    } else {
      const cached = sourceFileCache.get(sourceFile);
      if (cached !== void 0) {
        return cached;
      }
    }
    const moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost);
    if (!moduleSpecifier) {
      sourceFileCache.set(sourceFile, true);
      return true;
    }
    const result = moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
    sourceFileCache.set(sourceFile, result);
    return result;
  }
  function allowsImportingSpecifier(moduleSpecifier) {
    if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) {
      return true;
    }
    if (pathIsRelative(moduleSpecifier) || isRootedDiskPath(moduleSpecifier)) {
      return true;
    }
    return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
  }
  function isAllowedCoreNodeModulesImport(moduleSpecifier) {
    if (isSourceFileJS(fromFile) && ts_JsTyping_exports.nodeCoreModules.has(moduleSpecifier)) {
      if (usesNodeCoreModules === void 0) {
        usesNodeCoreModules = consumesNodeCoreModules(fromFile);
      }
      if (usesNodeCoreModules) {
        return true;
      }
    }
    return false;
  }
  function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) {
    if (!stringContains(importedFileName, "node_modules")) {
      return void 0;
    }
    const specifier = ts_moduleSpecifiers_exports.getNodeModulesPackageName(
      host.getCompilationSettings(),
      fromFile,
      importedFileName,
      moduleSpecifierResolutionHost,
      preferences
    );
    if (!specifier) {
      return void 0;
    }
    if (!pathIsRelative(specifier) && !isRootedDiskPath(specifier)) {
      return getNodeModuleRootSpecifier(specifier);
    }
  }
  function getNodeModuleRootSpecifier(fullSpecifier) {
    const components = getPathComponents(getPackageNameFromTypesPackageName(fullSpecifier)).slice(1);
    if (startsWith(components[0], "@")) {
      return `${components[0]}/${components[1]}`;
    }
    return components[0];
  }
}
function tryParseJson(text) {
  try {
    return JSON.parse(text);
  } catch {
    return void 0;
  }
}
function consumesNodeCoreModules(sourceFile) {
  return some(sourceFile.imports, ({ text }) => ts_JsTyping_exports.nodeCoreModules.has(text));
}
function isInsideNodeModules(fileOrDirectory) {
  return contains(getPathComponents(fileOrDirectory), "node_modules");
}
function isDiagnosticWithLocation(diagnostic) {
  return diagnostic.file !== void 0 && diagnostic.start !== void 0 && diagnostic.length !== void 0;
}
function findDiagnosticForNode(node, sortedFileDiagnostics) {
  const span = createTextSpanFromNode(node);
  const index = binarySearchKey(sortedFileDiagnostics, span, identity, compareTextSpans);
  if (index >= 0) {
    const diagnostic = sortedFileDiagnostics[index];
    Debug.assertEqual(diagnostic.file, node.getSourceFile(), "Diagnostics proided to 'findDiagnosticForNode' must be from a single SourceFile");
    return cast(diagnostic, isDiagnosticWithLocation);
  }
}
function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) {
  var _a;
  let index = binarySearchKey(sortedFileDiagnostics, span.start, (diag2) => diag2.start, compareValues);
  if (index < 0) {
    index = ~index;
  }
  while (((_a = sortedFileDiagnostics[index - 1]) == null ? void 0 : _a.start) === span.start) {
    index--;
  }
  const result = [];
  const end = textSpanEnd(span);
  while (true) {
    const diagnostic = tryCast(sortedFileDiagnostics[index], isDiagnosticWithLocation);
    if (!diagnostic || diagnostic.start > end) {
      break;
    }
    if (textSpanContainsTextSpan(span, diagnostic)) {
      result.push(diagnostic);
    }
    index++;
  }
  return result;
}
function getRefactorContextSpan({ startPosition, endPosition }) {
  return createTextSpanFromBounds(startPosition, endPosition === void 0 ? startPosition : endPosition);
}
function getFixableErrorSpanExpression(sourceFile, span) {
  const token = getTokenAtPosition(sourceFile, span.start);
  const expression = findAncestor(token, (node) => {
    if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) {
      return "quit";
    }
    return isExpression(node) && textSpansEqual(span, createTextSpanFromNode(node, sourceFile));
  });
  return expression;
}
function mapOneOrMany(valueOrArray, f, resultSelector = identity) {
  return valueOrArray ? isArray(valueOrArray) ? resultSelector(map(valueOrArray, f)) : f(valueOrArray, 0) : void 0;
}
function firstOrOnly(valueOrArray) {
  return isArray(valueOrArray) ? first(valueOrArray) : valueOrArray;
}
function getNamesForExportedSymbol(symbol, scriptTarget) {
  if (needsNameFromDeclaration(symbol)) {
    const fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol);
    if (fromDeclaration)
      return fromDeclaration;
    const fileNameCase = ts_codefix_exports.moduleSymbolToValidIdentifier(
      getSymbolParentOrFail(symbol),
      scriptTarget,
      /*forceCapitalize*/
      false
    );
    const capitalized = ts_codefix_exports.moduleSymbolToValidIdentifier(
      getSymbolParentOrFail(symbol),
      scriptTarget,
      /*forceCapitalize*/
      true
    );
    if (fileNameCase === capitalized)
      return fileNameCase;
    return [fileNameCase, capitalized];
  }
  return symbol.name;
}
function getNameForExportedSymbol(symbol, scriptTarget, preferCapitalized) {
  if (needsNameFromDeclaration(symbol)) {
    return getDefaultLikeExportNameFromDeclaration(symbol) || ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized);
  }
  return symbol.name;
}
function needsNameFromDeclaration(symbol) {
  return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */);
}
function getDefaultLikeExportNameFromDeclaration(symbol) {
  return firstDefined(
    symbol.declarations,
    (d) => {
      var _a, _b;
      return isExportAssignment(d) ? (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text : (_b = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _b.text;
    }
  );
}
function getSymbolParentOrFail(symbol) {
  var _a;
  return Debug.checkDefined(
    symbol.parent,
    `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. Declarations: ${(_a = symbol.declarations) == null ? void 0 : _a.map((d) => {
      const kind = Debug.formatSyntaxKind(d.kind);
      const inJS = isInJSFile(d);
      const { expression } = d;
      return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : "");
    }).join(", ")}.`
  );
}
function stringContainsAt(haystack, needle, startIndex) {
  const needleLength = needle.length;
  if (needleLength + startIndex > haystack.length) {
    return false;
  }
  for (let i = 0; i < needleLength; i++) {
    if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex))
      return false;
  }
  return true;
}
function startsWithUnderscore(name) {
  return name.charCodeAt(0) === 95 /* _ */;
}
function isGlobalDeclaration(declaration) {
  return !isNonGlobalDeclaration(declaration);
}
function isNonGlobalDeclaration(declaration) {
  const sourceFile = declaration.getSourceFile();
  if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) {
    return false;
  }
  return isInJSFile(declaration) || !findAncestor(declaration, (d) => isModuleDeclaration(d) && isGlobalScopeAugmentation(d));
}
function isDeprecatedDeclaration(decl) {
  return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 8192 /* Deprecated */);
}
function shouldUseUriStyleNodeCoreModules(file, program) {
  const decisionFromFile = firstDefined(file.imports, (node) => {
    if (ts_JsTyping_exports.nodeCoreModules.has(node.text)) {
      return startsWith(node.text, "node:");
    }
  });
  return decisionFromFile ?? program.usesUriStyleNodeCoreModules;
}
function getNewLineKind(newLineCharacter) {
  return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
}
function diagnosticToString(diag2) {
  return isArray(diag2) ? formatStringFromArgs(getLocaleSpecificMessage(diag2[0]), diag2.slice(1)) : getLocaleSpecificMessage(diag2);
}
function getFormatCodeSettingsForWriting({ options }, sourceFile) {
  const shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === "ignore" /* Ignore */;
  const shouldRemoveSemicolons = options.semicolons === "remove" /* Remove */ || shouldAutoDetectSemicolonPreference && !probablyUsesSemicolons(sourceFile);
  return {
    ...options,
    semicolons: shouldRemoveSemicolons ? "remove" /* Remove */ : "ignore" /* Ignore */
  };
}
function jsxModeNeedsExplicitImport(jsx) {
  return jsx === 2 /* React */ || jsx === 3 /* ReactNative */;
}
function isSourceFileFromLibrary(program, node) {
  return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node);
}
function newCaseClauseTracker(checker, clauses) {
  const existingStrings = /* @__PURE__ */ new Set();
  const existingNumbers = /* @__PURE__ */ new Set();
  const existingBigInts = /* @__PURE__ */ new Set();
  for (const clause of clauses) {
    if (!isDefaultClause(clause)) {
      const expression = skipParentheses(clause.expression);
      if (isLiteralExpression(expression)) {
        switch (expression.kind) {
          case 15 /* NoSubstitutionTemplateLiteral */:
          case 11 /* StringLiteral */:
            existingStrings.add(expression.text);
            break;
          case 9 /* NumericLiteral */:
            existingNumbers.add(parseInt(expression.text));
            break;
          case 10 /* BigIntLiteral */:
            const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text);
            if (parsedBigInt) {
              existingBigInts.add(pseudoBigIntToString(parsedBigInt));
            }
            break;
        }
      } else {
        const symbol = checker.getSymbolAtLocation(clause.expression);
        if (symbol && symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
          const enumValue = checker.getConstantValue(symbol.valueDeclaration);
          if (enumValue !== void 0) {
            addValue(enumValue);
          }
        }
      }
    }
  }
  return {
    addValue,
    hasValue
  };
  function addValue(value) {
    switch (typeof value) {
      case "string":
        existingStrings.add(value);
        break;
      case "number":
        existingNumbers.add(value);
    }
  }
  function hasValue(value) {
    switch (typeof value) {
      case "string":
        return existingStrings.has(value);
      case "number":
        return existingNumbers.has(value);
      case "object":
        return existingBigInts.has(pseudoBigIntToString(value));
    }
  }
}
function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) {
  var _a;
  const fileName = typeof file === "string" ? file : file.fileName;
  if (!hasJSFileExtension(fileName)) {
    return false;
  }
  const compilerOptions = program.getCompilerOptions();
  const moduleKind = getEmitModuleKind(compilerOptions);
  const impliedNodeFormat = typeof file === "string" ? getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) : file.impliedNodeFormat;
  if (impliedNodeFormat === 99 /* ESNext */) {
    return false;
  }
  if (impliedNodeFormat === 1 /* CommonJS */) {
    return true;
  }
  if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) {
    return true;
  }
  if (compilerOptions.verbatimModuleSyntax && emitModuleKindIsNonNodeESM(moduleKind)) {
    return false;
  }
  if (typeof file === "object") {
    if (file.commonJsModuleIndicator) {
      return true;
    }
    if (file.externalModuleIndicator) {
      return false;
    }
  }
  return preferRequire;
}

// src/services/exportInfoMap.ts
var ImportKind = /* @__PURE__ */ ((ImportKind2) => {
  ImportKind2[ImportKind2["Named"] = 0] = "Named";
  ImportKind2[ImportKind2["Default"] = 1] = "Default";
  ImportKind2[ImportKind2["Namespace"] = 2] = "Namespace";
  ImportKind2[ImportKind2["CommonJS"] = 3] = "CommonJS";
  return ImportKind2;
})(ImportKind || {});
var ExportKind = /* @__PURE__ */ ((ExportKind3) => {
  ExportKind3[ExportKind3["Named"] = 0] = "Named";
  ExportKind3[ExportKind3["Default"] = 1] = "Default";
  ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals";
  ExportKind3[ExportKind3["UMD"] = 3] = "UMD";
  return ExportKind3;
})(ExportKind || {});
function createCacheableExportInfoMap(host) {
  let exportInfoId = 1;
  const exportInfo = createMultiMap();
  const symbols = /* @__PURE__ */ new Map();
  const packages = /* @__PURE__ */ new Map();
  let usableByFileName;
  const cache = {
    isUsableByFile: (importingFile) => importingFile === usableByFileName,
    isEmpty: () => !exportInfo.size,
    clear: () => {
      exportInfo.clear();
      symbols.clear();
      usableByFileName = void 0;
    },
    add: (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, checker) => {
      if (importingFile !== usableByFileName) {
        cache.clear();
        usableByFileName = importingFile;
      }
      let packageName;
      if (moduleFile) {
        const nodeModulesPathParts = getNodeModulePathParts(moduleFile.fileName);
        if (nodeModulesPathParts) {
          const { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex } = nodeModulesPathParts;
          packageName = unmangleScopedPackageName(getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex)));
          if (startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) {
            const prevDeepestNodeModulesPath = packages.get(packageName);
            const nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex + 1);
            if (prevDeepestNodeModulesPath) {
              const prevDeepestNodeModulesIndex = prevDeepestNodeModulesPath.indexOf(nodeModulesPathPart);
              if (topLevelNodeModulesIndex > prevDeepestNodeModulesIndex) {
                packages.set(packageName, nodeModulesPath);
              }
            } else {
              packages.set(packageName, nodeModulesPath);
            }
          }
        }
      }
      const isDefault = exportKind === 1 /* Default */;
      const namedSymbol = isDefault && getLocalSymbolForExportDefault(symbol) || symbol;
      const names = exportKind === 0 /* Named */ || isExternalModuleSymbol(namedSymbol) ? unescapeLeadingUnderscores(symbolTableKey) : getNamesForExportedSymbol(
        namedSymbol,
        /*scriptTarget*/
        void 0
      );
      const symbolName2 = typeof names === "string" ? names : names[0];
      const capitalizedSymbolName = typeof names === "string" ? void 0 : names[1];
      const moduleName = stripQuotes(moduleSymbol.name);
      const id = exportInfoId++;
      const target = skipAlias(symbol, checker);
      const storedSymbol = symbol.flags & 33554432 /* Transient */ ? void 0 : symbol;
      const storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? void 0 : moduleSymbol;
      if (!storedSymbol || !storedModuleSymbol)
        symbols.set(id, [symbol, moduleSymbol]);
      exportInfo.add(key(symbolName2, symbol, isExternalModuleNameRelative(moduleName) ? void 0 : moduleName, checker), {
        id,
        symbolTableKey,
        symbolName: symbolName2,
        capitalizedSymbolName,
        moduleName,
        moduleFile,
        moduleFileName: moduleFile == null ? void 0 : moduleFile.fileName,
        packageName,
        exportKind,
        targetFlags: target.flags,
        isFromPackageJson,
        symbol: storedSymbol,
        moduleSymbol: storedModuleSymbol
      });
    },
    get: (importingFile, key2) => {
      if (importingFile !== usableByFileName)
        return;
      const result = exportInfo.get(key2);
      return result == null ? void 0 : result.map(rehydrateCachedInfo);
    },
    search: (importingFile, preferCapitalized, matches, action) => {
      if (importingFile !== usableByFileName)
        return;
      return forEachEntry(exportInfo, (info, key2) => {
        const { symbolName: symbolName2, ambientModuleName } = parseKey(key2);
        const name = preferCapitalized && info[0].capitalizedSymbolName || symbolName2;
        if (matches(name, info[0].targetFlags)) {
          const rehydrated = info.map(rehydrateCachedInfo);
          const filtered = rehydrated.filter((r, i) => isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName));
          if (filtered.length) {
            const res = action(filtered, name, !!ambientModuleName, key2);
            if (res !== void 0)
              return res;
          }
        }
      });
    },
    releaseSymbols: () => {
      symbols.clear();
    },
    onFileChanged: (oldSourceFile, newSourceFile, typeAcquisitionEnabled) => {
      if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) {
        return false;
      }
      if (usableByFileName && usableByFileName !== newSourceFile.path || // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node.
      // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list.
      typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || // Module agumentation and ambient module changes can add or remove exports available to be auto-imported.
      // Changes elsewhere in the file can change the *type* of an export in a module augmentation,
      // but type info is gathered in getCompletionEntryDetails, which doesn't use the cache.
      !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) {
        cache.clear();
        return true;
      }
      usableByFileName = newSourceFile.path;
      return false;
    }
  };
  if (Debug.isDebugging) {
    Object.defineProperty(cache, "__cache", { get: () => exportInfo });
  }
  return cache;
  function rehydrateCachedInfo(info) {
    if (info.symbol && info.moduleSymbol)
      return info;
    const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = info;
    const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray;
    if (cachedSymbol && cachedModuleSymbol) {
      return {
        symbol: cachedSymbol,
        moduleSymbol: cachedModuleSymbol,
        moduleFileName,
        exportKind,
        targetFlags,
        isFromPackageJson
      };
    }
    const checker = (isFromPackageJson ? host.getPackageJsonAutoImportProvider() : host.getCurrentProgram()).getTypeChecker();
    const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName));
    const symbol = info.symbol || cachedSymbol || Debug.checkDefined(
      exportKind === 2 /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol),
      `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`
    );
    symbols.set(id, [symbol, moduleSymbol]);
    return {
      symbol,
      moduleSymbol,
      moduleFileName,
      exportKind,
      targetFlags,
      isFromPackageJson
    };
  }
  function key(importedName, symbol, ambientModuleName, checker) {
    const moduleKey = ambientModuleName || "";
    return `${importedName}|${getSymbolId(skipAlias(symbol, checker))}|${moduleKey}`;
  }
  function parseKey(key2) {
    const symbolName2 = key2.substring(0, key2.indexOf("|"));
    const moduleKey = key2.substring(key2.lastIndexOf("|") + 1);
    const ambientModuleName = moduleKey === "" ? void 0 : moduleKey;
    return { symbolName: symbolName2, ambientModuleName };
  }
  function fileIsGlobalOnly(file) {
    return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames;
  }
  function ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) {
    if (!arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) {
      return false;
    }
    let oldFileStatementIndex = -1;
    let newFileStatementIndex = -1;
    for (const ambientModuleName of newSourceFile.ambientModuleNames) {
      const isMatchingModuleDeclaration = (node) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName;
      oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1);
      newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1);
      if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) {
        return false;
      }
    }
    return true;
  }
  function isNotShadowedByDeeperNodeModulesPackage(info, packageName) {
    if (!packageName || !info.moduleFileName)
      return true;
    const typingsCacheLocation = host.getGlobalTypingsCacheLocation();
    if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation))
      return true;
    const packageDeepestNodeModulesPath = packages.get(packageName);
    return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath);
  }
}
function isImportableFile(program, from, to, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) {
  var _a;
  if (from === to)
    return false;
  const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(from.path, to.path, preferences, {});
  if ((cachedResult == null ? void 0 : cachedResult.isBlockedByPackageJsonDependencies) !== void 0) {
    return !cachedResult.isBlockedByPackageJsonDependencies;
  }
  const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost);
  const globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(moduleSpecifierResolutionHost);
  const hasImportablePath = !!ts_moduleSpecifiers_exports.forEachFileNameOfModule(
    from.fileName,
    to.fileName,
    moduleSpecifierResolutionHost,
    /*preferSymlinks*/
    false,
    (toPath3) => {
      const toFile = program.getSourceFile(toPath3);
      return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath3, getCanonicalFileName, globalTypingsCache);
    }
  );
  if (packageJsonFilter) {
    const isAutoImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost);
    moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(from.path, to.path, preferences, {}, !isAutoImportable);
    return isAutoImportable;
  }
  return hasImportablePath;
}
function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePath) {
  const toNodeModules = forEachAncestorDirectory(toPath3, (ancestor) => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0);
  const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules));
  return toNodeModulesParent === void 0 || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || !!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent);
}
function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) {
  var _a, _b;
  const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host);
  const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec) => {
    const pattern = getPatternFromSpec(spec, "", "exclude");
    return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames) : void 0;
  });
  forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file) => cb(
    module2,
    file,
    program,
    /*isFromPackageJson*/
    false
  ));
  const autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host));
  if (autoImportProvider) {
    const start2 = timestamp();
    const checker = program.getTypeChecker();
    forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, (module2, file) => {
      if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName(
        module2.name,
        /*location*/
        void 0,
        1536 /* Module */,
        /*excludeGlobals*/
        false
      )) {
        cb(
          module2,
          file,
          autoImportProvider,
          /*isFromPackageJson*/
          true
        );
      }
    });
    (_b = host.log) == null ? void 0 : _b.call(host, `forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start2}`);
  }
}
function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) {
  var _a;
  const isExcluded = excludePatterns && ((fileName) => excludePatterns.some((p) => p.test(fileName)));
  for (const ambient of checker.getAmbientModules()) {
    if (!stringContains(ambient.name, "*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d) => isExcluded(d.getSourceFile().fileName))))) {
      cb(
        ambient,
        /*sourceFile*/
        void 0
      );
    }
  }
  for (const sourceFile of allSourceFiles) {
    if (isExternalOrCommonJsModule(sourceFile) && !(isExcluded == null ? void 0 : isExcluded(sourceFile.fileName))) {
      cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
    }
  }
}
function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) {
  var _a, _b, _c, _d, _e;
  const start2 = timestamp();
  (_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host);
  const cache = ((_b = host.getCachedExportInfoMap) == null ? void 0 : _b.call(host)) || createCacheableExportInfoMap({
    getCurrentProgram: () => program,
    getPackageJsonAutoImportProvider: () => {
      var _a2;
      return (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host);
    },
    getGlobalTypingsCacheLocation: () => {
      var _a2;
      return (_a2 = host.getGlobalTypingsCacheLocation) == null ? void 0 : _a2.call(host);
    }
  });
  if (cache.isUsableByFile(importingFile.path)) {
    (_c = host.log) == null ? void 0 : _c.call(host, "getExportInfoMap: cache hit");
    return cache;
  }
  (_d = host.log) == null ? void 0 : _d.call(host, "getExportInfoMap: cache miss or empty; calculating new results");
  const compilerOptions = program.getCompilerOptions();
  let moduleCount = 0;
  try {
    forEachExternalModuleToImportFrom(
      program,
      host,
      preferences,
      /*useAutoImportProvider*/
      true,
      (moduleSymbol, moduleFile, program2, isFromPackageJson) => {
        if (++moduleCount % 100 === 0)
          cancellationToken == null ? void 0 : cancellationToken.throwIfCancellationRequested();
        const seenExports = /* @__PURE__ */ new Map();
        const checker = program2.getTypeChecker();
        const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions);
        if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) {
          cache.add(
            importingFile.path,
            defaultInfo.symbol,
            defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */,
            moduleSymbol,
            moduleFile,
            defaultInfo.exportKind,
            isFromPackageJson,
            checker
          );
        }
        checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => {
          if (exported !== (defaultInfo == null ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) {
            cache.add(
              importingFile.path,
              exported,
              key,
              moduleSymbol,
              moduleFile,
              0 /* Named */,
              isFromPackageJson,
              checker
            );
          }
        });
      }
    );
  } catch (err) {
    cache.clear();
    throw err;
  }
  (_e = host.log) == null ? void 0 : _e.call(host, `getExportInfoMap: done in ${timestamp() - start2} ms`);
  return cache;
}
function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) {
  const exported = getDefaultLikeExportWorker(moduleSymbol, checker);
  if (!exported)
    return void 0;
  const { symbol, exportKind } = exported;
  const info = getDefaultExportInfoWorker(symbol, checker, compilerOptions);
  return info && { symbol, exportKind, ...info };
}
function isImportableSymbol(symbol, checker) {
  return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol);
}
function getDefaultLikeExportWorker(moduleSymbol, checker) {
  const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
  if (exportEquals !== moduleSymbol)
    return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ };
  const defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
  if (defaultExport)
    return { symbol: defaultExport, exportKind: 1 /* Default */ };
}
function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) {
  const localSymbol = getLocalSymbolForExportDefault(defaultExport);
  if (localSymbol)
    return { resolvedSymbol: localSymbol, name: localSymbol.name };
  const name = getNameForExportDefault(defaultExport);
  if (name !== void 0)
    return { resolvedSymbol: defaultExport, name };
  if (defaultExport.flags & 2097152 /* Alias */) {
    const aliased = checker.getImmediateAliasedSymbol(defaultExport);
    if (aliased && aliased.parent) {
      return getDefaultExportInfoWorker(aliased, checker, compilerOptions);
    }
  }
  if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) {
    return { resolvedSymbol: defaultExport, name: defaultExport.getName() };
  }
  return { resolvedSymbol: defaultExport, name: getNameForExportedSymbol(defaultExport, compilerOptions.target) };
}
function getNameForExportDefault(symbol) {
  return symbol.declarations && firstDefined(symbol.declarations, (declaration) => {
    var _a;
    if (isExportAssignment(declaration)) {
      return (_a = tryCast(skipOuterExpressions(declaration.expression), isIdentifier)) == null ? void 0 : _a.text;
    } else if (isExportSpecifier(declaration)) {
      Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export");
      return declaration.propertyName && declaration.propertyName.text;
    }
  });
}

// src/services/classifier.ts
function createClassifier() {
  const scanner2 = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    false
  );
  function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
    return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
  }
  function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
    let token = 0 /* Unknown */;
    let lastNonTriviaToken = 0 /* Unknown */;
    const templateStack = [];
    const { prefix, pushTemplate } = getPrefixFromLexState(lexState);
    text = prefix + text;
    const offset = prefix.length;
    if (pushTemplate) {
      templateStack.push(16 /* TemplateHead */);
    }
    scanner2.setText(text);
    let endOfLineState = 0 /* None */;
    const spans = [];
    let angleBracketStack = 0;
    do {
      token = scanner2.scan();
      if (!isTrivia(token)) {
        handleToken();
        lastNonTriviaToken = token;
      }
      const end = scanner2.getTokenEnd();
      pushEncodedClassification(scanner2.getTokenStart(), end, offset, classFromKind(token), spans);
      if (end >= text.length) {
        const end2 = getNewEndOfLineState(scanner2, token, lastOrUndefined(templateStack));
        if (end2 !== void 0) {
          endOfLineState = end2;
        }
      }
    } while (token !== 1 /* EndOfFileToken */);
    function handleToken() {
      switch (token) {
        case 44 /* SlashToken */:
        case 69 /* SlashEqualsToken */:
          if (!noRegexTable[lastNonTriviaToken] && scanner2.reScanSlashToken() === 14 /* RegularExpressionLiteral */) {
            token = 14 /* RegularExpressionLiteral */;
          }
          break;
        case 30 /* LessThanToken */:
          if (lastNonTriviaToken === 80 /* Identifier */) {
            angleBracketStack++;
          }
          break;
        case 32 /* GreaterThanToken */:
          if (angleBracketStack > 0) {
            angleBracketStack--;
          }
          break;
        case 133 /* AnyKeyword */:
        case 154 /* StringKeyword */:
        case 150 /* NumberKeyword */:
        case 136 /* BooleanKeyword */:
        case 155 /* SymbolKeyword */:
          if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
            token = 80 /* Identifier */;
          }
          break;
        case 16 /* TemplateHead */:
          templateStack.push(token);
          break;
        case 19 /* OpenBraceToken */:
          if (templateStack.length > 0) {
            templateStack.push(token);
          }
          break;
        case 20 /* CloseBraceToken */:
          if (templateStack.length > 0) {
            const lastTemplateStackToken = lastOrUndefined(templateStack);
            if (lastTemplateStackToken === 16 /* TemplateHead */) {
              token = scanner2.reScanTemplateToken(
                /*isTaggedTemplate*/
                false
              );
              if (token === 18 /* TemplateTail */) {
                templateStack.pop();
              } else {
                Debug.assertEqual(token, 17 /* TemplateMiddle */, "Should have been a template middle.");
              }
            } else {
              Debug.assertEqual(lastTemplateStackToken, 19 /* OpenBraceToken */, "Should have been an open brace");
              templateStack.pop();
            }
          }
          break;
        default:
          if (!isKeyword(token)) {
            break;
          }
          if (lastNonTriviaToken === 25 /* DotToken */) {
            token = 80 /* Identifier */;
          } else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
            token = 80 /* Identifier */;
          }
      }
    }
    return { endOfLineState, spans };
  }
  return { getClassificationsForLine, getEncodedLexicalClassifications };
}
var noRegexTable = arrayToNumericMap([
  80 /* Identifier */,
  11 /* StringLiteral */,
  9 /* NumericLiteral */,
  10 /* BigIntLiteral */,
  14 /* RegularExpressionLiteral */,
  110 /* ThisKeyword */,
  46 /* PlusPlusToken */,
  47 /* MinusMinusToken */,
  22 /* CloseParenToken */,
  24 /* CloseBracketToken */,
  20 /* CloseBraceToken */,
  112 /* TrueKeyword */,
  97 /* FalseKeyword */
], (token) => token, () => true);
function getNewEndOfLineState(scanner2, token, lastOnTemplateStack) {
  switch (token) {
    case 11 /* StringLiteral */: {
      if (!scanner2.isUnterminated())
        return void 0;
      const tokenText = scanner2.getTokenText();
      const lastCharIndex = tokenText.length - 1;
      let numBackslashes = 0;
      while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) {
        numBackslashes++;
      }
      if ((numBackslashes & 1) === 0)
        return void 0;
      return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */;
    }
    case 3 /* MultiLineCommentTrivia */:
      return scanner2.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : void 0;
    default:
      if (isTemplateLiteralKind(token)) {
        if (!scanner2.isUnterminated()) {
          return void 0;
        }
        switch (token) {
          case 18 /* TemplateTail */:
            return 5 /* InTemplateMiddleOrTail */;
          case 15 /* NoSubstitutionTemplateLiteral */:
            return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
          default:
            return Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
        }
      }
      return lastOnTemplateStack === 16 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : void 0;
  }
}
function pushEncodedClassification(start2, end, offset, classification, result) {
  if (classification === 8 /* whiteSpace */) {
    return;
  }
  if (start2 === 0 && offset > 0) {
    start2 += offset;
  }
  const length2 = end - start2;
  if (length2 > 0) {
    result.push(start2 - offset, length2, classification);
  }
}
function convertClassificationsToResult(classifications, text) {
  const entries = [];
  const dense = classifications.spans;
  let lastEnd = 0;
  for (let i = 0; i < dense.length; i += 3) {
    const start2 = dense[i];
    const length2 = dense[i + 1];
    const type = dense[i + 2];
    if (lastEnd >= 0) {
      const whitespaceLength2 = start2 - lastEnd;
      if (whitespaceLength2 > 0) {
        entries.push({ length: whitespaceLength2, classification: 4 /* Whitespace */ });
      }
    }
    entries.push({ length: length2, classification: convertClassification(type) });
    lastEnd = start2 + length2;
  }
  const whitespaceLength = text.length - lastEnd;
  if (whitespaceLength > 0) {
    entries.push({ length: whitespaceLength, classification: 4 /* Whitespace */ });
  }
  return { entries, finalLexState: classifications.endOfLineState };
}
function convertClassification(type) {
  switch (type) {
    case 1 /* comment */:
      return 3 /* Comment */;
    case 3 /* keyword */:
      return 1 /* Keyword */;
    case 4 /* numericLiteral */:
      return 6 /* NumberLiteral */;
    case 25 /* bigintLiteral */:
      return 7 /* BigIntLiteral */;
    case 5 /* operator */:
      return 2 /* Operator */;
    case 6 /* stringLiteral */:
      return 8 /* StringLiteral */;
    case 8 /* whiteSpace */:
      return 4 /* Whitespace */;
    case 10 /* punctuation */:
      return 0 /* Punctuation */;
    case 2 /* identifier */:
    case 11 /* className */:
    case 12 /* enumName */:
    case 13 /* interfaceName */:
    case 14 /* moduleName */:
    case 15 /* typeParameterName */:
    case 16 /* typeAliasName */:
    case 9 /* text */:
    case 17 /* parameterName */:
      return 5 /* Identifier */;
    default:
      return void 0;
  }
}
function canFollow(keyword1, keyword2) {
  if (!isAccessibilityModifier(keyword1)) {
    return true;
  }
  switch (keyword2) {
    case 139 /* GetKeyword */:
    case 153 /* SetKeyword */:
    case 137 /* ConstructorKeyword */:
    case 126 /* StaticKeyword */:
    case 129 /* AccessorKeyword */:
      return true;
    default:
      return false;
  }
}
function getPrefixFromLexState(lexState) {
  switch (lexState) {
    case 3 /* InDoubleQuoteStringLiteral */:
      return { prefix: '"\\\n' };
    case 2 /* InSingleQuoteStringLiteral */:
      return { prefix: "'\\\n" };
    case 1 /* InMultiLineCommentTrivia */:
      return { prefix: "/*\n" };
    case 4 /* InTemplateHeadOrNoSubstitutionTemplate */:
      return { prefix: "`\n" };
    case 5 /* InTemplateMiddleOrTail */:
      return { prefix: "}\n", pushTemplate: true };
    case 6 /* InTemplateSubstitutionPosition */:
      return { prefix: "", pushTemplate: true };
    case 0 /* None */:
      return { prefix: "" };
    default:
      return Debug.assertNever(lexState);
  }
}
function isBinaryExpressionOperatorToken(token) {
  switch (token) {
    case 42 /* AsteriskToken */:
    case 44 /* SlashToken */:
    case 45 /* PercentToken */:
    case 40 /* PlusToken */:
    case 41 /* MinusToken */:
    case 48 /* LessThanLessThanToken */:
    case 49 /* GreaterThanGreaterThanToken */:
    case 50 /* GreaterThanGreaterThanGreaterThanToken */:
    case 30 /* LessThanToken */:
    case 32 /* GreaterThanToken */:
    case 33 /* LessThanEqualsToken */:
    case 34 /* GreaterThanEqualsToken */:
    case 104 /* InstanceOfKeyword */:
    case 103 /* InKeyword */:
    case 130 /* AsKeyword */:
    case 152 /* SatisfiesKeyword */:
    case 35 /* EqualsEqualsToken */:
    case 36 /* ExclamationEqualsToken */:
    case 37 /* EqualsEqualsEqualsToken */:
    case 38 /* ExclamationEqualsEqualsToken */:
    case 51 /* AmpersandToken */:
    case 53 /* CaretToken */:
    case 52 /* BarToken */:
    case 56 /* AmpersandAmpersandToken */:
    case 57 /* BarBarToken */:
    case 75 /* BarEqualsToken */:
    case 74 /* AmpersandEqualsToken */:
    case 79 /* CaretEqualsToken */:
    case 71 /* LessThanLessThanEqualsToken */:
    case 72 /* GreaterThanGreaterThanEqualsToken */:
    case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
    case 65 /* PlusEqualsToken */:
    case 66 /* MinusEqualsToken */:
    case 67 /* AsteriskEqualsToken */:
    case 69 /* SlashEqualsToken */:
    case 70 /* PercentEqualsToken */:
    case 64 /* EqualsToken */:
    case 28 /* CommaToken */:
    case 61 /* QuestionQuestionToken */:
    case 76 /* BarBarEqualsToken */:
    case 77 /* AmpersandAmpersandEqualsToken */:
    case 78 /* QuestionQuestionEqualsToken */:
      return true;
    default:
      return false;
  }
}
function isPrefixUnaryExpressionOperatorToken(token) {
  switch (token) {
    case 40 /* PlusToken */:
    case 41 /* MinusToken */:
    case 55 /* TildeToken */:
    case 54 /* ExclamationToken */:
    case 46 /* PlusPlusToken */:
    case 47 /* MinusMinusToken */:
      return true;
    default:
      return false;
  }
}
function classFromKind(token) {
  if (isKeyword(token)) {
    return 3 /* keyword */;
  } else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
    return 5 /* operator */;
  } else if (token >= 19 /* FirstPunctuation */ && token <= 79 /* LastPunctuation */) {
    return 10 /* punctuation */;
  }
  switch (token) {
    case 9 /* NumericLiteral */:
      return 4 /* numericLiteral */;
    case 10 /* BigIntLiteral */:
      return 25 /* bigintLiteral */;
    case 11 /* StringLiteral */:
      return 6 /* stringLiteral */;
    case 14 /* RegularExpressionLiteral */:
      return 7 /* regularExpressionLiteral */;
    case 7 /* ConflictMarkerTrivia */:
    case 3 /* MultiLineCommentTrivia */:
    case 2 /* SingleLineCommentTrivia */:
      return 1 /* comment */;
    case 5 /* WhitespaceTrivia */:
    case 4 /* NewLineTrivia */:
      return 8 /* whiteSpace */;
    case 80 /* Identifier */:
    default:
      if (isTemplateLiteralKind(token)) {
        return 6 /* stringLiteral */;
      }
      return 2 /* identifier */;
  }
}
function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
  return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
}
function checkForClassificationCancellation(cancellationToken, kind) {
  switch (kind) {
    case 266 /* ModuleDeclaration */:
    case 262 /* ClassDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 261 /* FunctionDeclaration */:
    case 230 /* ClassExpression */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
      cancellationToken.throwIfCancellationRequested();
  }
}
function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
  const spans = [];
  sourceFile.forEachChild(function cb(node) {
    if (!node || !textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
      return;
    }
    checkForClassificationCancellation(cancellationToken, node.kind);
    if (isIdentifier(node) && !nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
      const symbol = typeChecker.getSymbolAtLocation(node);
      const type = symbol && classifySymbol(symbol, getMeaningFromLocation(node), typeChecker);
      if (type) {
        pushClassification(node.getStart(sourceFile), node.getEnd(), type);
      }
    }
    node.forEachChild(cb);
  });
  return { spans, endOfLineState: 0 /* None */ };
  function pushClassification(start2, end, type) {
    const length2 = end - start2;
    Debug.assert(length2 > 0, `Classification had non-positive length of ${length2}`);
    spans.push(start2);
    spans.push(length2);
    spans.push(type);
  }
}
function classifySymbol(symbol, meaningAtPosition, checker) {
  const flags = symbol.getFlags();
  if ((flags & 2885600 /* Classifiable */) === 0 /* None */) {
    return void 0;
  } else if (flags & 32 /* Class */) {
    return 11 /* className */;
  } else if (flags & 384 /* Enum */) {
    return 12 /* enumName */;
  } else if (flags & 524288 /* TypeAlias */) {
    return 16 /* typeAliasName */;
  } else if (flags & 1536 /* Module */) {
    return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : void 0;
  } else if (flags & 2097152 /* Alias */) {
    return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
  } else if (meaningAtPosition & 2 /* Type */) {
    return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : void 0;
  } else {
    return void 0;
  }
}
function hasValueSideModule(symbol) {
  return some(symbol.declarations, (declaration) => isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === 1 /* Instantiated */);
}
function getClassificationTypeName(type) {
  switch (type) {
    case 1 /* comment */:
      return "comment" /* comment */;
    case 2 /* identifier */:
      return "identifier" /* identifier */;
    case 3 /* keyword */:
      return "keyword" /* keyword */;
    case 4 /* numericLiteral */:
      return "number" /* numericLiteral */;
    case 25 /* bigintLiteral */:
      return "bigint" /* bigintLiteral */;
    case 5 /* operator */:
      return "operator" /* operator */;
    case 6 /* stringLiteral */:
      return "string" /* stringLiteral */;
    case 8 /* whiteSpace */:
      return "whitespace" /* whiteSpace */;
    case 9 /* text */:
      return "text" /* text */;
    case 10 /* punctuation */:
      return "punctuation" /* punctuation */;
    case 11 /* className */:
      return "class name" /* className */;
    case 12 /* enumName */:
      return "enum name" /* enumName */;
    case 13 /* interfaceName */:
      return "interface name" /* interfaceName */;
    case 14 /* moduleName */:
      return "module name" /* moduleName */;
    case 15 /* typeParameterName */:
      return "type parameter name" /* typeParameterName */;
    case 16 /* typeAliasName */:
      return "type alias name" /* typeAliasName */;
    case 17 /* parameterName */:
      return "parameter name" /* parameterName */;
    case 18 /* docCommentTagName */:
      return "doc comment tag name" /* docCommentTagName */;
    case 19 /* jsxOpenTagName */:
      return "jsx open tag name" /* jsxOpenTagName */;
    case 20 /* jsxCloseTagName */:
      return "jsx close tag name" /* jsxCloseTagName */;
    case 21 /* jsxSelfClosingTagName */:
      return "jsx self closing tag name" /* jsxSelfClosingTagName */;
    case 22 /* jsxAttribute */:
      return "jsx attribute" /* jsxAttribute */;
    case 23 /* jsxText */:
      return "jsx text" /* jsxText */;
    case 24 /* jsxAttributeStringLiteralValue */:
      return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */;
    default:
      return void 0;
  }
}
function convertClassificationsToSpans(classifications) {
  Debug.assert(classifications.spans.length % 3 === 0);
  const dense = classifications.spans;
  const result = [];
  for (let i = 0; i < dense.length; i += 3) {
    result.push({
      textSpan: createTextSpan(dense[i], dense[i + 1]),
      classificationType: getClassificationTypeName(dense[i + 2])
    });
  }
  return result;
}
function getSyntacticClassifications(cancellationToken, sourceFile, span) {
  return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
}
function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
  const spanStart = span.start;
  const spanLength = span.length;
  const triviaScanner = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    false,
    sourceFile.languageVariant,
    sourceFile.text
  );
  const mergeConflictScanner = createScanner(
    99 /* Latest */,
    /*skipTrivia*/
    false,
    sourceFile.languageVariant,
    sourceFile.text
  );
  const result = [];
  processElement(sourceFile);
  return { spans: result, endOfLineState: 0 /* None */ };
  function pushClassification(start2, length2, type) {
    result.push(start2);
    result.push(length2);
    result.push(type);
  }
  function classifyLeadingTriviaAndGetTokenStart(token) {
    triviaScanner.resetTokenState(token.pos);
    while (true) {
      const start2 = triviaScanner.getTokenEnd();
      if (!couldStartTrivia(sourceFile.text, start2)) {
        return start2;
      }
      const kind = triviaScanner.scan();
      const end = triviaScanner.getTokenEnd();
      const width = end - start2;
      if (!isTrivia(kind)) {
        return start2;
      }
      switch (kind) {
        case 4 /* NewLineTrivia */:
        case 5 /* WhitespaceTrivia */:
          continue;
        case 2 /* SingleLineCommentTrivia */:
        case 3 /* MultiLineCommentTrivia */:
          classifyComment(token, kind, start2, width);
          triviaScanner.resetTokenState(end);
          continue;
        case 7 /* ConflictMarkerTrivia */:
          const text = sourceFile.text;
          const ch = text.charCodeAt(start2);
          if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
            pushClassification(start2, width, 1 /* comment */);
            continue;
          }
          Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
          classifyDisabledMergeCode(text, start2, end);
          break;
        case 6 /* ShebangTrivia */:
          break;
        default:
          Debug.assertNever(kind);
      }
    }
  }
  function classifyComment(token, kind, start2, width) {
    if (kind === 3 /* MultiLineCommentTrivia */) {
      const docCommentAndDiagnostics = parseIsolatedJSDocComment(sourceFile.text, start2, width);
      if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
        setParent(docCommentAndDiagnostics.jsDoc, token);
        classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
        return;
      }
    } else if (kind === 2 /* SingleLineCommentTrivia */) {
      if (tryClassifyTripleSlashComment(start2, width)) {
        return;
      }
    }
    pushCommentRange(start2, width);
  }
  function pushCommentRange(start2, width) {
    pushClassification(start2, width, 1 /* comment */);
  }
  function classifyJSDocComment(docComment) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    let pos = docComment.pos;
    if (docComment.tags) {
      for (const tag of docComment.tags) {
        if (tag.pos !== pos) {
          pushCommentRange(pos, tag.pos - pos);
        }
        pushClassification(tag.pos, 1, 10 /* punctuation */);
        pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */);
        pos = tag.tagName.end;
        let commentStart = tag.tagName.end;
        switch (tag.kind) {
          case 347 /* JSDocParameterTag */:
            const param = tag;
            processJSDocParameterTag(param);
            commentStart = param.isNameFirst && ((_a = param.typeExpression) == null ? void 0 : _a.end) || param.name.end;
            break;
          case 354 /* JSDocPropertyTag */:
            const prop = tag;
            commentStart = prop.isNameFirst && ((_b = prop.typeExpression) == null ? void 0 : _b.end) || prop.name.end;
            break;
          case 351 /* JSDocTemplateTag */:
            processJSDocTemplateTag(tag);
            pos = tag.end;
            commentStart = tag.typeParameters.end;
            break;
          case 352 /* JSDocTypedefTag */:
            const type = tag;
            commentStart = ((_c = type.typeExpression) == null ? void 0 : _c.kind) === 315 /* JSDocTypeExpression */ && ((_d = type.fullName) == null ? void 0 : _d.end) || ((_e = type.typeExpression) == null ? void 0 : _e.end) || commentStart;
            break;
          case 344 /* JSDocCallbackTag */:
            commentStart = tag.typeExpression.end;
            break;
          case 350 /* JSDocTypeTag */:
            processElement(tag.typeExpression);
            pos = tag.end;
            commentStart = tag.typeExpression.end;
            break;
          case 349 /* JSDocThisTag */:
          case 346 /* JSDocEnumTag */:
            commentStart = tag.typeExpression.end;
            break;
          case 348 /* JSDocReturnTag */:
            processElement(tag.typeExpression);
            pos = tag.end;
            commentStart = ((_f = tag.typeExpression) == null ? void 0 : _f.end) || commentStart;
            break;
          case 353 /* JSDocSeeTag */:
            commentStart = ((_g = tag.name) == null ? void 0 : _g.end) || commentStart;
            break;
          case 334 /* JSDocAugmentsTag */:
          case 335 /* JSDocImplementsTag */:
            commentStart = tag.class.end;
            break;
          case 355 /* JSDocThrowsTag */:
            processElement(tag.typeExpression);
            pos = tag.end;
            commentStart = ((_h = tag.typeExpression) == null ? void 0 : _h.end) || commentStart;
            break;
        }
        if (typeof tag.comment === "object") {
          pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos);
        } else if (typeof tag.comment === "string") {
          pushCommentRange(commentStart, tag.end - commentStart);
        }
      }
    }
    if (pos !== docComment.end) {
      pushCommentRange(pos, docComment.end - pos);
    }
    return;
    function processJSDocParameterTag(tag) {
      if (tag.isNameFirst) {
        pushCommentRange(pos, tag.name.pos - pos);
        pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
        pos = tag.name.end;
      }
      if (tag.typeExpression) {
        pushCommentRange(pos, tag.typeExpression.pos - pos);
        processElement(tag.typeExpression);
        pos = tag.typeExpression.end;
      }
      if (!tag.isNameFirst) {
        pushCommentRange(pos, tag.name.pos - pos);
        pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
        pos = tag.name.end;
      }
    }
  }
  function tryClassifyTripleSlashComment(start2, width) {
    const tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im;
    const attributeRegex = /(\s)(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img;
    const text = sourceFile.text.substr(start2, width);
    const match = tripleSlashXMLCommentRegEx.exec(text);
    if (!match) {
      return false;
    }
    if (!match[3] || !(match[3] in commentPragmas)) {
      return false;
    }
    let pos = start2;
    pushCommentRange(pos, match[1].length);
    pos += match[1].length;
    pushClassification(pos, match[2].length, 10 /* punctuation */);
    pos += match[2].length;
    pushClassification(pos, match[3].length, 21 /* jsxSelfClosingTagName */);
    pos += match[3].length;
    const attrText = match[4];
    let attrPos = pos;
    while (true) {
      const attrMatch = attributeRegex.exec(attrText);
      if (!attrMatch) {
        break;
      }
      const newAttrPos = pos + attrMatch.index + attrMatch[1].length;
      if (newAttrPos > attrPos) {
        pushCommentRange(attrPos, newAttrPos - attrPos);
        attrPos = newAttrPos;
      }
      pushClassification(attrPos, attrMatch[2].length, 22 /* jsxAttribute */);
      attrPos += attrMatch[2].length;
      if (attrMatch[3].length) {
        pushCommentRange(attrPos, attrMatch[3].length);
        attrPos += attrMatch[3].length;
      }
      pushClassification(attrPos, attrMatch[4].length, 5 /* operator */);
      attrPos += attrMatch[4].length;
      if (attrMatch[5].length) {
        pushCommentRange(attrPos, attrMatch[5].length);
        attrPos += attrMatch[5].length;
      }
      pushClassification(attrPos, attrMatch[6].length, 24 /* jsxAttributeStringLiteralValue */);
      attrPos += attrMatch[6].length;
    }
    pos += match[4].length;
    if (pos > attrPos) {
      pushCommentRange(attrPos, pos - attrPos);
    }
    if (match[5]) {
      pushClassification(pos, match[5].length, 10 /* punctuation */);
      pos += match[5].length;
    }
    const end = start2 + width;
    if (pos < end) {
      pushCommentRange(pos, end - pos);
    }
    return true;
  }
  function processJSDocTemplateTag(tag) {
    for (const child of tag.getChildren()) {
      processElement(child);
    }
  }
  function classifyDisabledMergeCode(text, start2, end) {
    let i;
    for (i = start2; i < end; i++) {
      if (isLineBreak(text.charCodeAt(i))) {
        break;
      }
    }
    pushClassification(start2, i - start2, 1 /* comment */);
    mergeConflictScanner.resetTokenState(i);
    while (mergeConflictScanner.getTokenEnd() < end) {
      classifyDisabledCodeToken();
    }
  }
  function classifyDisabledCodeToken() {
    const start2 = mergeConflictScanner.getTokenEnd();
    const tokenKind = mergeConflictScanner.scan();
    const end = mergeConflictScanner.getTokenEnd();
    const type = classifyTokenType(tokenKind);
    if (type) {
      pushClassification(start2, end - start2, type);
    }
  }
  function tryClassifyNode(node) {
    if (isJSDoc(node)) {
      return true;
    }
    if (nodeIsMissing(node)) {
      return true;
    }
    const classifiedElementName = tryClassifyJsxElementName(node);
    if (!isToken(node) && node.kind !== 12 /* JsxText */ && classifiedElementName === void 0) {
      return false;
    }
    const tokenStart = node.kind === 12 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
    const tokenWidth = node.end - tokenStart;
    Debug.assert(tokenWidth >= 0);
    if (tokenWidth > 0) {
      const type = classifiedElementName || classifyTokenType(node.kind, node);
      if (type) {
        pushClassification(tokenStart, tokenWidth, type);
      }
    }
    return true;
  }
  function tryClassifyJsxElementName(token) {
    switch (token.parent && token.parent.kind) {
      case 285 /* JsxOpeningElement */:
        if (token.parent.tagName === token) {
          return 19 /* jsxOpenTagName */;
        }
        break;
      case 286 /* JsxClosingElement */:
        if (token.parent.tagName === token) {
          return 20 /* jsxCloseTagName */;
        }
        break;
      case 284 /* JsxSelfClosingElement */:
        if (token.parent.tagName === token) {
          return 21 /* jsxSelfClosingTagName */;
        }
        break;
      case 290 /* JsxAttribute */:
        if (token.parent.name === token) {
          return 22 /* jsxAttribute */;
        }
        break;
    }
    return void 0;
  }
  function classifyTokenType(tokenKind, token) {
    if (isKeyword(tokenKind)) {
      return 3 /* keyword */;
    }
    if (tokenKind === 30 /* LessThanToken */ || tokenKind === 32 /* GreaterThanToken */) {
      if (token && getTypeArgumentOrTypeParameterList(token.parent)) {
        return 10 /* punctuation */;
      }
    }
    if (isPunctuation(tokenKind)) {
      if (token) {
        const parent2 = token.parent;
        if (tokenKind === 64 /* EqualsToken */) {
          if (parent2.kind === 259 /* VariableDeclaration */ || parent2.kind === 171 /* PropertyDeclaration */ || parent2.kind === 168 /* Parameter */ || parent2.kind === 290 /* JsxAttribute */) {
            return 5 /* operator */;
          }
        }
        if (parent2.kind === 225 /* BinaryExpression */ || parent2.kind === 223 /* PrefixUnaryExpression */ || parent2.kind === 224 /* PostfixUnaryExpression */ || parent2.kind === 226 /* ConditionalExpression */) {
          return 5 /* operator */;
        }
      }
      return 10 /* punctuation */;
    } else if (tokenKind === 9 /* NumericLiteral */) {
      return 4 /* numericLiteral */;
    } else if (tokenKind === 10 /* BigIntLiteral */) {
      return 25 /* bigintLiteral */;
    } else if (tokenKind === 11 /* StringLiteral */) {
      return token && token.parent.kind === 290 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
    } else if (tokenKind === 14 /* RegularExpressionLiteral */) {
      return 6 /* stringLiteral */;
    } else if (isTemplateLiteralKind(tokenKind)) {
      return 6 /* stringLiteral */;
    } else if (tokenKind === 12 /* JsxText */) {
      return 23 /* jsxText */;
    } else if (tokenKind === 80 /* Identifier */) {
      if (token) {
        switch (token.parent.kind) {
          case 262 /* ClassDeclaration */:
            if (token.parent.name === token) {
              return 11 /* className */;
            }
            return;
          case 167 /* TypeParameter */:
            if (token.parent.name === token) {
              return 15 /* typeParameterName */;
            }
            return;
          case 263 /* InterfaceDeclaration */:
            if (token.parent.name === token) {
              return 13 /* interfaceName */;
            }
            return;
          case 265 /* EnumDeclaration */:
            if (token.parent.name === token) {
              return 12 /* enumName */;
            }
            return;
          case 266 /* ModuleDeclaration */:
            if (token.parent.name === token) {
              return 14 /* moduleName */;
            }
            return;
          case 168 /* Parameter */:
            if (token.parent.name === token) {
              return isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
            }
            return;
        }
        if (isConstTypeReference(token.parent)) {
          return 3 /* keyword */;
        }
      }
      return 2 /* identifier */;
    }
  }
  function processElement(element) {
    if (!element) {
      return;
    }
    if (decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
      checkForClassificationCancellation(cancellationToken, element.kind);
      for (const child of element.getChildren(sourceFile)) {
        if (!tryClassifyNode(child)) {
          processElement(child);
        }
      }
    }
  }
}

// src/services/documentHighlights.ts
var DocumentHighlights;
((DocumentHighlights3) => {
  function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) {
    const node = getTouchingPropertyName(sourceFile, position);
    if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) {
      const { openingElement, closingElement } = node.parent.parent;
      const highlightSpans = [openingElement, closingElement].map(({ tagName }) => getHighlightSpanForNode(tagName, sourceFile));
      return [{ fileName: sourceFile.fileName, highlightSpans }];
    }
    return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
  }
  DocumentHighlights3.getDocumentHighlights = getDocumentHighlights;
  function getHighlightSpanForNode(node, sourceFile) {
    return {
      fileName: sourceFile.fileName,
      textSpan: createTextSpanFromNode(node, sourceFile),
      kind: "none" /* none */
    };
  }
  function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
    const sourceFilesSet = new Set(sourceFilesToSearch.map((f) => f.fileName));
    const referenceEntries = ts_FindAllReferences_exports.getReferenceEntriesForNode(
      position,
      node,
      program,
      sourceFilesToSearch,
      cancellationToken,
      /*options*/
      void 0,
      sourceFilesSet
    );
    if (!referenceEntries)
      return void 0;
    const map2 = arrayToMultiMap(referenceEntries.map(ts_FindAllReferences_exports.toHighlightSpan), (e) => e.fileName, (e) => e.span);
    const getCanonicalFileName = createGetCanonicalFileName(program.useCaseSensitiveFileNames());
    return arrayFrom(mapDefinedIterator(map2.entries(), ([fileName, highlightSpans]) => {
      if (!sourceFilesSet.has(fileName)) {
        if (!program.redirectTargetsMap.has(toPath(fileName, program.getCurrentDirectory(), getCanonicalFileName))) {
          return void 0;
        }
        const redirectTarget = program.getSourceFile(fileName);
        const redirect = find(sourceFilesToSearch, (f) => !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget);
        fileName = redirect.fileName;
        Debug.assert(sourceFilesSet.has(fileName));
      }
      return { fileName, highlightSpans };
    }));
  }
  function getSyntacticDocumentHighlights(node, sourceFile) {
    const highlightSpans = getHighlightSpans(node, sourceFile);
    return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans }];
  }
  function getHighlightSpans(node, sourceFile) {
    switch (node.kind) {
      case 101 /* IfKeyword */:
      case 93 /* ElseKeyword */:
        return isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : void 0;
      case 107 /* ReturnKeyword */:
        return useParent(node.parent, isReturnStatement, getReturnOccurrences);
      case 111 /* ThrowKeyword */:
        return useParent(node.parent, isThrowStatement, getThrowOccurrences);
      case 113 /* TryKeyword */:
      case 85 /* CatchKeyword */:
      case 98 /* FinallyKeyword */:
        const tryStatement = node.kind === 85 /* CatchKeyword */ ? node.parent.parent : node.parent;
        return useParent(tryStatement, isTryStatement, getTryCatchFinallyOccurrences);
      case 109 /* SwitchKeyword */:
        return useParent(node.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences);
      case 84 /* CaseKeyword */:
      case 90 /* DefaultKeyword */: {
        if (isDefaultClause(node.parent) || isCaseClause(node.parent)) {
          return useParent(node.parent.parent.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences);
        }
        return void 0;
      }
      case 83 /* BreakKeyword */:
      case 88 /* ContinueKeyword */:
        return useParent(node.parent, isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
      case 99 /* ForKeyword */:
      case 117 /* WhileKeyword */:
      case 92 /* DoKeyword */:
        return useParent(node.parent, (n) => isIterationStatement(
          n,
          /*lookInLabeledStatements*/
          true
        ), getLoopBreakContinueOccurrences);
      case 137 /* ConstructorKeyword */:
        return getFromAllDeclarations(isConstructorDeclaration, [137 /* ConstructorKeyword */]);
      case 139 /* GetKeyword */:
      case 153 /* SetKeyword */:
        return getFromAllDeclarations(isAccessor, [139 /* GetKeyword */, 153 /* SetKeyword */]);
      case 135 /* AwaitKeyword */:
        return useParent(node.parent, isAwaitExpression, getAsyncAndAwaitOccurrences);
      case 134 /* AsyncKeyword */:
        return highlightSpans(getAsyncAndAwaitOccurrences(node));
      case 127 /* YieldKeyword */:
        return highlightSpans(getYieldOccurrences(node));
      case 103 /* InKeyword */:
        return void 0;
      default:
        return isModifierKind(node.kind) && (isDeclaration(node.parent) || isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) : void 0;
    }
    function getFromAllDeclarations(nodeTest, keywords) {
      return useParent(node.parent, nodeTest, (decl) => {
        var _a;
        return mapDefined((_a = tryCast(decl, canHaveSymbol)) == null ? void 0 : _a.symbol.declarations, (d) => nodeTest(d) ? find(d.getChildren(sourceFile), (c) => contains(keywords, c.kind)) : void 0);
      });
    }
    function useParent(node2, nodeTest, getNodes4) {
      return nodeTest(node2) ? highlightSpans(getNodes4(node2, sourceFile)) : void 0;
    }
    function highlightSpans(nodes) {
      return nodes && nodes.map((node2) => getHighlightSpanForNode(node2, sourceFile));
    }
  }
  function aggregateOwnedThrowStatements(node) {
    if (isThrowStatement(node)) {
      return [node];
    } else if (isTryStatement(node)) {
      return concatenate(
        node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock),
        node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)
      );
    }
    return isFunctionLike(node) ? void 0 : flatMapChildren(node, aggregateOwnedThrowStatements);
  }
  function getThrowStatementOwner(throwStatement) {
    let child = throwStatement;
    while (child.parent) {
      const parent2 = child.parent;
      if (isFunctionBlock(parent2) || parent2.kind === 311 /* SourceFile */) {
        return parent2;
      }
      if (isTryStatement(parent2) && parent2.tryBlock === child && parent2.catchClause) {
        return child;
      }
      child = parent2;
    }
    return void 0;
  }
  function aggregateAllBreakAndContinueStatements(node) {
    return isBreakOrContinueStatement(node) ? [node] : isFunctionLike(node) ? void 0 : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
  }
  function flatMapChildren(node, cb) {
    const result = [];
    node.forEachChild((child) => {
      const value = cb(child);
      if (value !== void 0) {
        result.push(...toArray(value));
      }
    });
    return result;
  }
  function ownsBreakOrContinueStatement(owner, statement) {
    const actualOwner = getBreakOrContinueOwner(statement);
    return !!actualOwner && actualOwner === owner;
  }
  function getBreakOrContinueOwner(statement) {
    return findAncestor(statement, (node) => {
      switch (node.kind) {
        case 254 /* SwitchStatement */:
          if (statement.kind === 250 /* ContinueStatement */) {
            return false;
          }
        case 247 /* ForStatement */:
        case 248 /* ForInStatement */:
        case 249 /* ForOfStatement */:
        case 246 /* WhileStatement */:
        case 245 /* DoStatement */:
          return !statement.label || isLabeledBy(node, statement.label.escapedText);
        default:
          return isFunctionLike(node) && "quit";
      }
    });
  }
  function getModifierOccurrences(modifier, declaration) {
    return mapDefined(getNodesToSearchForModifier(declaration, modifierToFlag(modifier)), (node) => findModifier(node, modifier));
  }
  function getNodesToSearchForModifier(declaration, modifierFlag) {
    const container = declaration.parent;
    switch (container.kind) {
      case 267 /* ModuleBlock */:
      case 311 /* SourceFile */:
      case 240 /* Block */:
      case 295 /* CaseClause */:
      case 296 /* DefaultClause */:
        if (modifierFlag & 256 /* Abstract */ && isClassDeclaration(declaration)) {
          return [...declaration.members, declaration];
        } else {
          return container.statements;
        }
      case 175 /* Constructor */:
      case 173 /* MethodDeclaration */:
      case 261 /* FunctionDeclaration */:
        return [...container.parameters, ...isClassLike(container.parent) ? container.parent.members : []];
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
      case 263 /* InterfaceDeclaration */:
      case 186 /* TypeLiteral */:
        const nodes = container.members;
        if (modifierFlag & (28 /* AccessibilityModifier */ | 64 /* Readonly */)) {
          const constructor = find(container.members, isConstructorDeclaration);
          if (constructor) {
            return [...nodes, ...constructor.parameters];
          }
        } else if (modifierFlag & 256 /* Abstract */) {
          return [...nodes, container];
        }
        return nodes;
      case 209 /* ObjectLiteralExpression */:
        return void 0;
      default:
        Debug.assertNever(container, "Invalid container kind.");
    }
  }
  function pushKeywordIf(keywordList, token, ...expected) {
    if (token && contains(expected, token.kind)) {
      keywordList.push(token);
      return true;
    }
    return false;
  }
  function getLoopBreakContinueOccurrences(loopNode) {
    const keywords = [];
    if (pushKeywordIf(keywords, loopNode.getFirstToken(), 99 /* ForKeyword */, 117 /* WhileKeyword */, 92 /* DoKeyword */)) {
      if (loopNode.kind === 245 /* DoStatement */) {
        const loopTokens = loopNode.getChildren();
        for (let i = loopTokens.length - 1; i >= 0; i--) {
          if (pushKeywordIf(keywords, loopTokens[i], 117 /* WhileKeyword */)) {
            break;
          }
        }
      }
    }
    forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), (statement) => {
      if (ownsBreakOrContinueStatement(loopNode, statement)) {
        pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */, 88 /* ContinueKeyword */);
      }
    });
    return keywords;
  }
  function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
    const owner = getBreakOrContinueOwner(breakOrContinueStatement);
    if (owner) {
      switch (owner.kind) {
        case 247 /* ForStatement */:
        case 248 /* ForInStatement */:
        case 249 /* ForOfStatement */:
        case 245 /* DoStatement */:
        case 246 /* WhileStatement */:
          return getLoopBreakContinueOccurrences(owner);
        case 254 /* SwitchStatement */:
          return getSwitchCaseDefaultOccurrences(owner);
      }
    }
    return void 0;
  }
  function getSwitchCaseDefaultOccurrences(switchStatement) {
    const keywords = [];
    pushKeywordIf(keywords, switchStatement.getFirstToken(), 109 /* SwitchKeyword */);
    forEach(switchStatement.caseBlock.clauses, (clause) => {
      pushKeywordIf(keywords, clause.getFirstToken(), 84 /* CaseKeyword */, 90 /* DefaultKeyword */);
      forEach(aggregateAllBreakAndContinueStatements(clause), (statement) => {
        if (ownsBreakOrContinueStatement(switchStatement, statement)) {
          pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */);
        }
      });
    });
    return keywords;
  }
  function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
    const keywords = [];
    pushKeywordIf(keywords, tryStatement.getFirstToken(), 113 /* TryKeyword */);
    if (tryStatement.catchClause) {
      pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 85 /* CatchKeyword */);
    }
    if (tryStatement.finallyBlock) {
      const finallyKeyword = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile);
      pushKeywordIf(keywords, finallyKeyword, 98 /* FinallyKeyword */);
    }
    return keywords;
  }
  function getThrowOccurrences(throwStatement, sourceFile) {
    const owner = getThrowStatementOwner(throwStatement);
    if (!owner) {
      return void 0;
    }
    const keywords = [];
    forEach(aggregateOwnedThrowStatements(owner), (throwStatement2) => {
      keywords.push(findChildOfKind(throwStatement2, 111 /* ThrowKeyword */, sourceFile));
    });
    if (isFunctionBlock(owner)) {
      forEachReturnStatement(owner, (returnStatement) => {
        keywords.push(findChildOfKind(returnStatement, 107 /* ReturnKeyword */, sourceFile));
      });
    }
    return keywords;
  }
  function getReturnOccurrences(returnStatement, sourceFile) {
    const func = getContainingFunction(returnStatement);
    if (!func) {
      return void 0;
    }
    const keywords = [];
    forEachReturnStatement(cast(func.body, isBlock), (returnStatement2) => {
      keywords.push(findChildOfKind(returnStatement2, 107 /* ReturnKeyword */, sourceFile));
    });
    forEach(aggregateOwnedThrowStatements(func.body), (throwStatement) => {
      keywords.push(findChildOfKind(throwStatement, 111 /* ThrowKeyword */, sourceFile));
    });
    return keywords;
  }
  function getAsyncAndAwaitOccurrences(node) {
    const func = getContainingFunction(node);
    if (!func) {
      return void 0;
    }
    const keywords = [];
    if (func.modifiers) {
      func.modifiers.forEach((modifier) => {
        pushKeywordIf(keywords, modifier, 134 /* AsyncKeyword */);
      });
    }
    forEachChild(func, (child) => {
      traverseWithoutCrossingFunction(child, (node2) => {
        if (isAwaitExpression(node2)) {
          pushKeywordIf(keywords, node2.getFirstToken(), 135 /* AwaitKeyword */);
        }
      });
    });
    return keywords;
  }
  function getYieldOccurrences(node) {
    const func = getContainingFunction(node);
    if (!func) {
      return void 0;
    }
    const keywords = [];
    forEachChild(func, (child) => {
      traverseWithoutCrossingFunction(child, (node2) => {
        if (isYieldExpression(node2)) {
          pushKeywordIf(keywords, node2.getFirstToken(), 127 /* YieldKeyword */);
        }
      });
    });
    return keywords;
  }
  function traverseWithoutCrossingFunction(node, cb) {
    cb(node);
    if (!isFunctionLike(node) && !isClassLike(node) && !isInterfaceDeclaration(node) && !isModuleDeclaration(node) && !isTypeAliasDeclaration(node) && !isTypeNode(node)) {
      forEachChild(node, (child) => traverseWithoutCrossingFunction(child, cb));
    }
  }
  function getIfElseOccurrences(ifStatement, sourceFile) {
    const keywords = getIfElseKeywords(ifStatement, sourceFile);
    const result = [];
    for (let i = 0; i < keywords.length; i++) {
      if (keywords[i].kind === 93 /* ElseKeyword */ && i < keywords.length - 1) {
        const elseKeyword = keywords[i];
        const ifKeyword = keywords[i + 1];
        let shouldCombineElseAndIf = true;
        for (let j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
          if (!isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
            shouldCombineElseAndIf = false;
            break;
          }
        }
        if (shouldCombineElseAndIf) {
          result.push({
            fileName: sourceFile.fileName,
            textSpan: createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
            kind: "reference" /* reference */
          });
          i++;
          continue;
        }
      }
      result.push(getHighlightSpanForNode(keywords[i], sourceFile));
    }
    return result;
  }
  function getIfElseKeywords(ifStatement, sourceFile) {
    const keywords = [];
    while (isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
      ifStatement = ifStatement.parent;
    }
    while (true) {
      const children = ifStatement.getChildren(sourceFile);
      pushKeywordIf(keywords, children[0], 101 /* IfKeyword */);
      for (let i = children.length - 1; i >= 0; i--) {
        if (pushKeywordIf(keywords, children[i], 93 /* ElseKeyword */)) {
          break;
        }
      }
      if (!ifStatement.elseStatement || !isIfStatement(ifStatement.elseStatement)) {
        break;
      }
      ifStatement = ifStatement.elseStatement;
    }
    return keywords;
  }
  function isLabeledBy(node, labelName) {
    return !!findAncestor(node.parent, (owner) => !isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName);
  }
})(DocumentHighlights || (DocumentHighlights = {}));

// src/services/documentRegistry.ts
function isDocumentRegistryEntry(entry) {
  return !!entry.sourceFile;
}
function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) {
  return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory);
}
function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory = "", externalCache) {
  const buckets = /* @__PURE__ */ new Map();
  const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames);
  function reportStats() {
    const bucketInfoArray = arrayFrom(buckets.keys()).filter((name) => name && name.charAt(0) === "_").map((name) => {
      const entries = buckets.get(name);
      const sourceFiles = [];
      entries.forEach((entry, name2) => {
        if (isDocumentRegistryEntry(entry)) {
          sourceFiles.push({
            name: name2,
            scriptKind: entry.sourceFile.scriptKind,
            refCount: entry.languageServiceRefCount
          });
        } else {
          entry.forEach((value, scriptKind) => sourceFiles.push({ name: name2, scriptKind, refCount: value.languageServiceRefCount }));
        }
      });
      sourceFiles.sort((x, y) => y.refCount - x.refCount);
      return {
        bucket: name,
        sourceFiles
      };
    });
    return JSON.stringify(bucketInfoArray, void 0, 2);
  }
  function getCompilationSettings(settingsOrHost) {
    if (typeof settingsOrHost.getCompilationSettings === "function") {
      return settingsOrHost.getCompilationSettings();
    }
    return settingsOrHost;
  }
  function acquireDocument(fileName, compilationSettings, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    const path = toPath(fileName, currentDirectory, getCanonicalFileName);
    const key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings));
    return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions);
  }
  function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    return acquireOrUpdateDocument(
      fileName,
      path,
      compilationSettings,
      key,
      scriptSnapshot,
      version2,
      /*acquiring*/
      true,
      scriptKind,
      languageVersionOrOptions
    );
  }
  function updateDocument(fileName, compilationSettings, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    const path = toPath(fileName, currentDirectory, getCanonicalFileName);
    const key = getKeyForCompilationSettings(getCompilationSettings(compilationSettings));
    return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions);
  }
  function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) {
    return acquireOrUpdateDocument(
      fileName,
      path,
      getCompilationSettings(compilationSettings),
      key,
      scriptSnapshot,
      version2,
      /*acquiring*/
      false,
      scriptKind,
      languageVersionOrOptions
    );
  }
  function getDocumentRegistryEntry(bucketEntry, scriptKind) {
    const entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided"));
    Debug.assert(scriptKind === void 0 || !entry || entry.sourceFile.scriptKind === scriptKind, `Script kind should match provided ScriptKind:${scriptKind} and sourceFile.scriptKind: ${entry == null ? void 0 : entry.sourceFile.scriptKind}, !entry: ${!entry}`);
    return entry;
  }
  function acquireOrUpdateDocument(fileName, path, compilationSettingsOrHost, key, scriptSnapshot, version2, acquiring, scriptKind, languageVersionOrOptions) {
    var _a, _b, _c, _d;
    scriptKind = ensureScriptKind(fileName, scriptKind);
    const compilationSettings = getCompilationSettings(compilationSettingsOrHost);
    const host = compilationSettingsOrHost === compilationSettings ? void 0 : compilationSettingsOrHost;
    const scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : getEmitScriptTarget(compilationSettings);
    const sourceFileOptions = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : {
      languageVersion: scriptTarget,
      impliedNodeFormat: host && getImpliedNodeFormatForFile(path, (_d = (_c = (_b = (_a = host.getCompilerHost) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getModuleResolutionCache) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.getPackageJsonInfoCache(), host, compilationSettings),
      setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings)
    };
    sourceFileOptions.languageVersion = scriptTarget;
    const oldBucketCount = buckets.size;
    const keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat);
    const bucket = getOrUpdate(buckets, keyWithMode, () => /* @__PURE__ */ new Map());
    if (tracing) {
      if (buckets.size > oldBucketCount) {
        tracing.instant(tracing.Phase.Session, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode });
      }
      const otherBucketKey = !isDeclarationFileName(path) && forEachEntry(buckets, (bucket2, bucketKey) => bucketKey !== keyWithMode && bucket2.has(path) && bucketKey);
      if (otherBucketKey) {
        tracing.instant(tracing.Phase.Session, "documentRegistryBucketOverlap", { path, key1: otherBucketKey, key2: keyWithMode });
      }
    }
    const bucketEntry = bucket.get(path);
    let entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind);
    if (!entry && externalCache) {
      const sourceFile = externalCache.getDocument(keyWithMode, path);
      if (sourceFile) {
        Debug.assert(acquiring);
        entry = {
          sourceFile,
          languageServiceRefCount: 0
        };
        setBucketEntry();
      }
    }
    if (!entry) {
      const sourceFile = createLanguageServiceSourceFile(
        fileName,
        scriptSnapshot,
        sourceFileOptions,
        version2,
        /*setNodeParents*/
        false,
        scriptKind
      );
      if (externalCache) {
        externalCache.setDocument(keyWithMode, path, sourceFile);
      }
      entry = {
        sourceFile,
        languageServiceRefCount: 1
      };
      setBucketEntry();
    } else {
      if (entry.sourceFile.version !== version2) {
        entry.sourceFile = updateLanguageServiceSourceFile(
          entry.sourceFile,
          scriptSnapshot,
          version2,
          scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)
        );
        if (externalCache) {
          externalCache.setDocument(keyWithMode, path, entry.sourceFile);
        }
      }
      if (acquiring) {
        entry.languageServiceRefCount++;
      }
    }
    Debug.assert(entry.languageServiceRefCount !== 0);
    return entry.sourceFile;
    function setBucketEntry() {
      if (!bucketEntry) {
        bucket.set(path, entry);
      } else if (isDocumentRegistryEntry(bucketEntry)) {
        const scriptKindMap = /* @__PURE__ */ new Map();
        scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry);
        scriptKindMap.set(scriptKind, entry);
        bucket.set(path, scriptKindMap);
      } else {
        bucketEntry.set(scriptKind, entry);
      }
    }
  }
  function releaseDocument(fileName, compilationSettings, scriptKind, impliedNodeFormat) {
    const path = toPath(fileName, currentDirectory, getCanonicalFileName);
    const key = getKeyForCompilationSettings(compilationSettings);
    return releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat);
  }
  function releaseDocumentWithKey(path, key, scriptKind, impliedNodeFormat) {
    const bucket = Debug.checkDefined(buckets.get(getDocumentRegistryBucketKeyWithMode(key, impliedNodeFormat)));
    const bucketEntry = bucket.get(path);
    const entry = getDocumentRegistryEntry(bucketEntry, scriptKind);
    entry.languageServiceRefCount--;
    Debug.assert(entry.languageServiceRefCount >= 0);
    if (entry.languageServiceRefCount === 0) {
      if (isDocumentRegistryEntry(bucketEntry)) {
        bucket.delete(path);
      } else {
        bucketEntry.delete(scriptKind);
        if (bucketEntry.size === 1) {
          bucket.set(path, firstDefinedIterator(bucketEntry.values(), identity));
        }
      }
    }
  }
  function getLanguageServiceRefCounts(path, scriptKind) {
    return arrayFrom(buckets.entries(), ([key, bucket]) => {
      const bucketEntry = bucket.get(path);
      const entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind);
      return [key, entry && entry.languageServiceRefCount];
    });
  }
  return {
    acquireDocument,
    acquireDocumentWithKey,
    updateDocument,
    updateDocumentWithKey,
    releaseDocument,
    releaseDocumentWithKey,
    getLanguageServiceRefCounts,
    reportStats,
    getKeyForCompilationSettings
  };
}
function getKeyForCompilationSettings(settings) {
  return getKeyForCompilerOptions(settings, sourceFileAffectingCompilerOptions);
}
function getDocumentRegistryBucketKeyWithMode(key, mode) {
  return mode ? `${key}|${mode}` : key;
}

// src/services/getEditsForFileRename.ts
function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) {
  const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host);
  const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
  const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
  const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
  return ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => {
    updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
    updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
  });
}
function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) {
  const canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
  return (path) => {
    const originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 });
    const updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path);
    return originalPath ? updatedPath === void 0 ? void 0 : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) : updatedPath;
  };
  function getUpdatedPath(pathToUpdate) {
    if (getCanonicalFileName(pathToUpdate) === canonicalOldPath)
      return newFileOrDirPath;
    const suffix = tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName);
    return suffix === void 0 ? void 0 : newFileOrDirPath + "/" + suffix;
  }
}
function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) {
  const rel = getRelativePathFromFile(a0, b0, getCanonicalFileName);
  return combinePathsSafe(getDirectoryPath(a1), rel);
}
function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) {
  const { configFile } = program.getCompilerOptions();
  if (!configFile)
    return;
  const configDir = getDirectoryPath(configFile.fileName);
  const jsonObjectLiteral = getTsConfigObjectLiteralExpression(configFile);
  if (!jsonObjectLiteral)
    return;
  forEachProperty(jsonObjectLiteral, (property, propertyName) => {
    switch (propertyName) {
      case "files":
      case "include":
      case "exclude": {
        const foundExactMatch = updatePaths(property);
        if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer))
          return;
        const includes = mapDefined(property.initializer.elements, (e) => isStringLiteral(e) ? e.text : void 0);
        if (includes.length === 0)
          return;
        const matchers = getFileMatcherPatterns(
          configDir,
          /*excludes*/
          [],
          includes,
          useCaseSensitiveFileNames,
          currentDirectory
        );
        if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
          changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath)));
        }
        return;
      }
      case "compilerOptions":
        forEachProperty(property.initializer, (property2, propertyName2) => {
          const option = getOptionFromName(propertyName2);
          Debug.assert((option == null ? void 0 : option.type) !== "listOrElement");
          if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) {
            updatePaths(property2);
          } else if (propertyName2 === "paths") {
            forEachProperty(property2.initializer, (pathsProperty) => {
              if (!isArrayLiteralExpression(pathsProperty.initializer))
                return;
              for (const e of pathsProperty.initializer.elements) {
                tryUpdateString(e);
              }
            });
          }
        });
        return;
    }
  });
  function updatePaths(property) {
    const elements = isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
    let foundExactMatch = false;
    for (const element of elements) {
      foundExactMatch = tryUpdateString(element) || foundExactMatch;
    }
    return foundExactMatch;
  }
  function tryUpdateString(element) {
    if (!isStringLiteral(element))
      return false;
    const elementFileName = combinePathsSafe(configDir, element.text);
    const updated = oldToNew(elementFileName);
    if (updated !== void 0) {
      changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated));
      return true;
    }
    return false;
  }
  function relativePath(path) {
    return getRelativePathFromDirectory(
      configDir,
      path,
      /*ignoreCase*/
      !useCaseSensitiveFileNames
    );
  }
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
  const allFiles = program.getSourceFiles();
  for (const sourceFile of allFiles) {
    const newFromOld = oldToNew(sourceFile.fileName);
    const newImportFromPath = newFromOld ?? sourceFile.fileName;
    const newImportFromDirectory = getDirectoryPath(newImportFromPath);
    const oldFromNew = newToOld(sourceFile.fileName);
    const oldImportFromPath = oldFromNew || sourceFile.fileName;
    const oldImportFromDirectory = getDirectoryPath(oldImportFromPath);
    const importingSourceFileMoved = newFromOld !== void 0 || oldFromNew !== void 0;
    updateImportsWorker(
      sourceFile,
      changeTracker,
      (referenceText) => {
        if (!pathIsRelative(referenceText))
          return void 0;
        const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText);
        const newAbsolute = oldToNew(oldAbsolute);
        return newAbsolute === void 0 ? void 0 : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
      },
      (importLiteral) => {
        const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
        if ((importedModuleSymbol == null ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some((d) => isAmbientModule(d)))
          return void 0;
        const toImport = oldFromNew !== void 0 ? getSourceFileToImportFromResolved(
          importLiteral,
          resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host),
          oldToNew,
          allFiles
        ) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
        return toImport !== void 0 && (toImport.updated || importingSourceFileMoved && pathIsRelative(importLiteral.text)) ? ts_moduleSpecifiers_exports.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath), toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) : void 0;
      }
    );
  }
}
function combineNormal(pathA, pathB) {
  return normalizePath(combinePaths(pathA, pathB));
}
function combinePathsSafe(pathA, pathB) {
  return ensurePathIsNonModuleName(combineNormal(pathA, pathB));
}
function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
  var _a;
  if (importedModuleSymbol) {
    const oldFileName = find(importedModuleSymbol.declarations, isSourceFile).fileName;
    const newFileName = oldToNew(oldFileName);
    return newFileName === void 0 ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true };
  } else {
    const mode = getModeForUsageLocation(importingSourceFile, importLiteral);
    const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? (_a = importingSourceFile.resolvedModules) == null ? void 0 : _a.get(importLiteral.text, mode) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode);
    return getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, program.getSourceFiles());
  }
}
function getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, sourceFiles) {
  if (!resolved)
    return void 0;
  if (resolved.resolvedModule) {
    const result2 = tryChange(resolved.resolvedModule.resolvedFileName);
    if (result2)
      return result2;
  }
  const result = forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting) || pathIsRelative(importLiteral.text) && forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
  if (result)
    return result;
  return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false };
  function tryChangeWithIgnoringPackageJsonExisting(oldFileName) {
    const newFileName = oldToNew(oldFileName);
    return newFileName && find(sourceFiles, (src) => src.fileName === newFileName) ? tryChangeWithIgnoringPackageJson(oldFileName) : void 0;
  }
  function tryChangeWithIgnoringPackageJson(oldFileName) {
    return !endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : void 0;
  }
  function tryChange(oldFileName) {
    const newFileName = oldToNew(oldFileName);
    return newFileName && { newFileName, updated: true };
  }
}
function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport2) {
  for (const ref of sourceFile.referencedFiles || emptyArray) {
    const updated = updateRef(ref.fileName);
    if (updated !== void 0 && updated !== sourceFile.text.slice(ref.pos, ref.end))
      changeTracker.replaceRangeWithText(sourceFile, ref, updated);
  }
  for (const importStringLiteral of sourceFile.imports) {
    const updated = updateImport2(importStringLiteral);
    if (updated !== void 0 && updated !== importStringLiteral.text)
      changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated);
  }
}
function createStringRange(node, sourceFile) {
  return createRange(node.getStart(sourceFile) + 1, node.end - 1);
}
function forEachProperty(objectLiteral, cb) {
  if (!isObjectLiteralExpression(objectLiteral))
    return;
  for (const property of objectLiteral.properties) {
    if (isPropertyAssignment(property) && isStringLiteral(property.name)) {
      cb(property, property.name.text);
    }
  }
}

// src/services/patternMatcher.ts
var PatternMatchKind = /* @__PURE__ */ ((PatternMatchKind2) => {
  PatternMatchKind2[PatternMatchKind2["exact"] = 0] = "exact";
  PatternMatchKind2[PatternMatchKind2["prefix"] = 1] = "prefix";
  PatternMatchKind2[PatternMatchKind2["substring"] = 2] = "substring";
  PatternMatchKind2[PatternMatchKind2["camelCase"] = 3] = "camelCase";
  return PatternMatchKind2;
})(PatternMatchKind || {});
function createPatternMatch(kind, isCaseSensitive) {
  return {
    kind,
    isCaseSensitive
  };
}
function createPatternMatcher(pattern) {
  const stringToWordSpans = /* @__PURE__ */ new Map();
  const dotSeparatedSegments = pattern.trim().split(".").map((p) => createSegment(p.trim()));
  if (dotSeparatedSegments.some((segment) => !segment.subWordTextChunks.length))
    return void 0;
  return {
    getFullMatch: (containers, candidate) => getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans),
    getMatchForLastSegmentOfPattern: (candidate) => matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans),
    patternContainsDots: dotSeparatedSegments.length > 1
  };
}
function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) {
  const candidateMatch = matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans);
  if (!candidateMatch) {
    return void 0;
  }
  if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
    return void 0;
  }
  let bestMatch;
  for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
    bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
  }
  return bestMatch;
}
function getWordSpans(word, stringToWordSpans) {
  let spans = stringToWordSpans.get(word);
  if (!spans) {
    stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
  }
  return spans;
}
function matchTextChunk(candidate, chunk, stringToWordSpans) {
  const index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
  if (index === 0) {
    return createPatternMatch(
      chunk.text.length === candidate.length ? 0 /* exact */ : 1 /* prefix */,
      /*isCaseSensitive:*/
      startsWith(candidate, chunk.text)
    );
  }
  if (chunk.isLowerCase) {
    if (index === -1)
      return void 0;
    const wordSpans = getWordSpans(candidate, stringToWordSpans);
    for (const span of wordSpans) {
      if (partStartsWith(
        candidate,
        span,
        chunk.text,
        /*ignoreCase*/
        true
      )) {
        return createPatternMatch(
          2 /* substring */,
          /*isCaseSensitive:*/
          partStartsWith(
            candidate,
            span,
            chunk.text,
            /*ignoreCase*/
            false
          )
        );
      }
    }
    if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) {
      return createPatternMatch(
        2 /* substring */,
        /*isCaseSensitive*/
        false
      );
    }
  } else {
    if (candidate.indexOf(chunk.text) > 0) {
      return createPatternMatch(
        2 /* substring */,
        /*isCaseSensitive*/
        true
      );
    }
    if (chunk.characterSpans.length > 0) {
      const candidateParts = getWordSpans(candidate, stringToWordSpans);
      const isCaseSensitive = tryCamelCaseMatch(
        candidate,
        candidateParts,
        chunk,
        /*ignoreCase*/
        false
      ) ? true : tryCamelCaseMatch(
        candidate,
        candidateParts,
        chunk,
        /*ignoreCase*/
        true
      ) ? false : void 0;
      if (isCaseSensitive !== void 0) {
        return createPatternMatch(3 /* camelCase */, isCaseSensitive);
      }
    }
  }
}
function matchSegment(candidate, segment, stringToWordSpans) {
  if (every2(segment.totalTextChunk.text, (ch) => ch !== 32 /* space */ && ch !== 42 /* asterisk */)) {
    const match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
    if (match)
      return match;
  }
  const subWordTextChunks = segment.subWordTextChunks;
  let bestMatch;
  for (const subWordTextChunk of subWordTextChunks) {
    bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
  }
  return bestMatch;
}
function betterMatch(a, b) {
  return min([a, b], compareMatches);
}
function compareMatches(a, b) {
  return a === void 0 ? 1 /* GreaterThan */ : b === void 0 ? -1 /* LessThan */ : compareValues(a.kind, b.kind) || compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
}
function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan = { start: 0, length: pattern.length }) {
  return patternSpan.length <= candidateSpan.length && everyInRange(0, patternSpan.length, (i) => equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase));
}
function equalChars(ch1, ch2, ignoreCase) {
  return ignoreCase ? toLowerCase2(ch1) === toLowerCase2(ch2) : ch1 === ch2;
}
function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
  const chunkCharacterSpans = chunk.characterSpans;
  let currentCandidate = 0;
  let currentChunkSpan = 0;
  let firstMatch;
  let contiguous;
  while (true) {
    if (currentChunkSpan === chunkCharacterSpans.length) {
      return true;
    } else if (currentCandidate === candidateParts.length) {
      return false;
    }
    let candidatePart = candidateParts[currentCandidate];
    let gotOneMatchThisCandidate = false;
    for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
      const chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
      if (gotOneMatchThisCandidate) {
        if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
          break;
        }
      }
      if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
        break;
      }
      gotOneMatchThisCandidate = true;
      firstMatch = firstMatch === void 0 ? currentCandidate : firstMatch;
      contiguous = contiguous === void 0 ? true : contiguous;
      candidatePart = createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
    }
    if (!gotOneMatchThisCandidate && contiguous !== void 0) {
      contiguous = false;
    }
    currentCandidate++;
  }
}
function createSegment(text) {
  return {
    totalTextChunk: createTextChunk(text),
    subWordTextChunks: breakPatternIntoTextChunks(text)
  };
}
function isUpperCaseLetter(ch) {
  if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
    return true;
  }
  if (ch < 127 /* maxAsciiCharacter */ || !isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
    return false;
  }
  const str = String.fromCharCode(ch);
  return str === str.toUpperCase();
}
function isLowerCaseLetter(ch) {
  if (ch >= 97 /* a */ && ch <= 122 /* z */) {
    return true;
  }
  if (ch < 127 /* maxAsciiCharacter */ || !isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
    return false;
  }
  const str = String.fromCharCode(ch);
  return str === str.toLowerCase();
}
function indexOfIgnoringCase(str, value) {
  const n = str.length - value.length;
  for (let start2 = 0; start2 <= n; start2++) {
    if (every2(value, (valueChar, i) => toLowerCase2(str.charCodeAt(i + start2)) === valueChar)) {
      return start2;
    }
  }
  return -1;
}
function toLowerCase2(ch) {
  if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
    return 97 /* a */ + (ch - 65 /* A */);
  }
  if (ch < 127 /* maxAsciiCharacter */) {
    return ch;
  }
  return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
}
function isDigit2(ch) {
  return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
}
function isWordChar(ch) {
  return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit2(ch) || ch === 95 /* _ */ || ch === 36 /* $ */;
}
function breakPatternIntoTextChunks(pattern) {
  const result = [];
  let wordStart = 0;
  let wordLength = 0;
  for (let i = 0; i < pattern.length; i++) {
    const ch = pattern.charCodeAt(i);
    if (isWordChar(ch)) {
      if (wordLength === 0) {
        wordStart = i;
      }
      wordLength++;
    } else {
      if (wordLength > 0) {
        result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
        wordLength = 0;
      }
    }
  }
  if (wordLength > 0) {
    result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
  }
  return result;
}
function createTextChunk(text) {
  const textLowerCase = text.toLowerCase();
  return {
    text,
    textLowerCase,
    isLowerCase: text === textLowerCase,
    characterSpans: breakIntoCharacterSpans(text)
  };
}
function breakIntoCharacterSpans(identifier) {
  return breakIntoSpans(
    identifier,
    /*word*/
    false
  );
}
function breakIntoWordSpans(identifier) {
  return breakIntoSpans(
    identifier,
    /*word*/
    true
  );
}
function breakIntoSpans(identifier, word) {
  const result = [];
  let wordStart = 0;
  for (let i = 1; i < identifier.length; i++) {
    const lastIsDigit = isDigit2(identifier.charCodeAt(i - 1));
    const currentIsDigit = isDigit2(identifier.charCodeAt(i));
    const hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
    const hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart);
    if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || hasTransitionFromUpperToLower) {
      if (!isAllPunctuation(identifier, wordStart, i)) {
        result.push(createTextSpan(wordStart, i - wordStart));
      }
      wordStart = i;
    }
  }
  if (!isAllPunctuation(identifier, wordStart, identifier.length)) {
    result.push(createTextSpan(wordStart, identifier.length - wordStart));
  }
  return result;
}
function charIsPunctuation(ch) {
  switch (ch) {
    case 33 /* exclamation */:
    case 34 /* doubleQuote */:
    case 35 /* hash */:
    case 37 /* percent */:
    case 38 /* ampersand */:
    case 39 /* singleQuote */:
    case 40 /* openParen */:
    case 41 /* closeParen */:
    case 42 /* asterisk */:
    case 44 /* comma */:
    case 45 /* minus */:
    case 46 /* dot */:
    case 47 /* slash */:
    case 58 /* colon */:
    case 59 /* semicolon */:
    case 63 /* question */:
    case 64 /* at */:
    case 91 /* openBracket */:
    case 92 /* backslash */:
    case 93 /* closeBracket */:
    case 95 /* _ */:
    case 123 /* openBrace */:
    case 125 /* closeBrace */:
      return true;
  }
  return false;
}
function isAllPunctuation(identifier, start2, end) {
  return every2(identifier, (ch) => charIsPunctuation(ch) && ch !== 95 /* _ */, start2, end);
}
function transitionFromUpperToLower(identifier, index, wordStart) {
  return index !== wordStart && index + 1 < identifier.length && isUpperCaseLetter(identifier.charCodeAt(index)) && isLowerCaseLetter(identifier.charCodeAt(index + 1)) && every2(identifier, isUpperCaseLetter, wordStart, index);
}
function transitionFromLowerToUpper(identifier, word, index) {
  const lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
  const currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
  return currentIsUpper && (!word || !lastIsUpper);
}
function everyInRange(start2, end, pred) {
  for (let i = start2; i < end; i++) {
    if (!pred(i)) {
      return false;
    }
  }
  return true;
}
function every2(s, pred, start2 = 0, end = s.length) {
  return everyInRange(start2, end, (i) => pred(s.charCodeAt(i), i));
}

// src/services/preProcess.ts
function preProcessFile(sourceText, readImportFiles = true, detectJavaScriptImports = false) {
  const pragmaContext = {
    languageVersion: 1 /* ES5 */,
    // controls whether the token scanner considers unicode identifiers or not - shouldn't matter, since we're only using it for trivia
    pragmas: void 0,
    checkJsDirective: void 0,
    referencedFiles: [],
    typeReferenceDirectives: [],
    libReferenceDirectives: [],
    amdDependencies: [],
    hasNoDefaultLib: void 0,
    moduleName: void 0
  };
  const importedFiles = [];
  let ambientExternalModules;
  let lastToken;
  let currentToken;
  let braceNesting = 0;
  let externalModule = false;
  function nextToken() {
    lastToken = currentToken;
    currentToken = scanner.scan();
    if (currentToken === 19 /* OpenBraceToken */) {
      braceNesting++;
    } else if (currentToken === 20 /* CloseBraceToken */) {
      braceNesting--;
    }
    return currentToken;
  }
  function getFileReference() {
    const fileName = scanner.getTokenValue();
    const pos = scanner.getTokenStart();
    return { fileName, pos, end: pos + fileName.length };
  }
  function recordAmbientExternalModule() {
    if (!ambientExternalModules) {
      ambientExternalModules = [];
    }
    ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
  }
  function recordModuleName() {
    importedFiles.push(getFileReference());
    markAsExternalModuleIfTopLevel();
  }
  function markAsExternalModuleIfTopLevel() {
    if (braceNesting === 0) {
      externalModule = true;
    }
  }
  function tryConsumeDeclare() {
    let token = scanner.getToken();
    if (token === 138 /* DeclareKeyword */) {
      token = nextToken();
      if (token === 144 /* ModuleKeyword */) {
        token = nextToken();
        if (token === 11 /* StringLiteral */) {
          recordAmbientExternalModule();
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeImport() {
    if (lastToken === 25 /* DotToken */) {
      return false;
    }
    let token = scanner.getToken();
    if (token === 102 /* ImportKeyword */) {
      token = nextToken();
      if (token === 21 /* OpenParenToken */) {
        token = nextToken();
        if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */) {
          recordModuleName();
          return true;
        }
      } else if (token === 11 /* StringLiteral */) {
        recordModuleName();
        return true;
      } else {
        if (token === 156 /* TypeKeyword */) {
          const skipTypeKeyword = scanner.lookAhead(() => {
            const token2 = scanner.scan();
            return token2 !== 160 /* FromKeyword */ && (token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */ || token2 === 80 /* Identifier */ || isKeyword(token2));
          });
          if (skipTypeKeyword) {
            token = nextToken();
          }
        }
        if (token === 80 /* Identifier */ || isKeyword(token)) {
          token = nextToken();
          if (token === 160 /* FromKeyword */) {
            token = nextToken();
            if (token === 11 /* StringLiteral */) {
              recordModuleName();
              return true;
            }
          } else if (token === 64 /* EqualsToken */) {
            if (tryConsumeRequireCall(
              /*skipCurrentToken*/
              true
            )) {
              return true;
            }
          } else if (token === 28 /* CommaToken */) {
            token = nextToken();
          } else {
            return true;
          }
        }
        if (token === 19 /* OpenBraceToken */) {
          token = nextToken();
          while (token !== 20 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
            token = nextToken();
          }
          if (token === 20 /* CloseBraceToken */) {
            token = nextToken();
            if (token === 160 /* FromKeyword */) {
              token = nextToken();
              if (token === 11 /* StringLiteral */) {
                recordModuleName();
              }
            }
          }
        } else if (token === 42 /* AsteriskToken */) {
          token = nextToken();
          if (token === 130 /* AsKeyword */) {
            token = nextToken();
            if (token === 80 /* Identifier */ || isKeyword(token)) {
              token = nextToken();
              if (token === 160 /* FromKeyword */) {
                token = nextToken();
                if (token === 11 /* StringLiteral */) {
                  recordModuleName();
                }
              }
            }
          }
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeExport() {
    let token = scanner.getToken();
    if (token === 95 /* ExportKeyword */) {
      markAsExternalModuleIfTopLevel();
      token = nextToken();
      if (token === 156 /* TypeKeyword */) {
        const skipTypeKeyword = scanner.lookAhead(() => {
          const token2 = scanner.scan();
          return token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */;
        });
        if (skipTypeKeyword) {
          token = nextToken();
        }
      }
      if (token === 19 /* OpenBraceToken */) {
        token = nextToken();
        while (token !== 20 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
          token = nextToken();
        }
        if (token === 20 /* CloseBraceToken */) {
          token = nextToken();
          if (token === 160 /* FromKeyword */) {
            token = nextToken();
            if (token === 11 /* StringLiteral */) {
              recordModuleName();
            }
          }
        }
      } else if (token === 42 /* AsteriskToken */) {
        token = nextToken();
        if (token === 160 /* FromKeyword */) {
          token = nextToken();
          if (token === 11 /* StringLiteral */) {
            recordModuleName();
          }
        }
      } else if (token === 102 /* ImportKeyword */) {
        token = nextToken();
        if (token === 156 /* TypeKeyword */) {
          const skipTypeKeyword = scanner.lookAhead(() => {
            const token2 = scanner.scan();
            return token2 === 80 /* Identifier */ || isKeyword(token2);
          });
          if (skipTypeKeyword) {
            token = nextToken();
          }
        }
        if (token === 80 /* Identifier */ || isKeyword(token)) {
          token = nextToken();
          if (token === 64 /* EqualsToken */) {
            if (tryConsumeRequireCall(
              /*skipCurrentToken*/
              true
            )) {
              return true;
            }
          }
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals = false) {
    let token = skipCurrentToken ? nextToken() : scanner.getToken();
    if (token === 149 /* RequireKeyword */) {
      token = nextToken();
      if (token === 21 /* OpenParenToken */) {
        token = nextToken();
        if (token === 11 /* StringLiteral */ || allowTemplateLiterals && token === 15 /* NoSubstitutionTemplateLiteral */) {
          recordModuleName();
        }
      }
      return true;
    }
    return false;
  }
  function tryConsumeDefine() {
    let token = scanner.getToken();
    if (token === 80 /* Identifier */ && scanner.getTokenValue() === "define") {
      token = nextToken();
      if (token !== 21 /* OpenParenToken */) {
        return true;
      }
      token = nextToken();
      if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */) {
        token = nextToken();
        if (token === 28 /* CommaToken */) {
          token = nextToken();
        } else {
          return true;
        }
      }
      if (token !== 23 /* OpenBracketToken */) {
        return true;
      }
      token = nextToken();
      while (token !== 24 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
        if (token === 11 /* StringLiteral */ || token === 15 /* NoSubstitutionTemplateLiteral */) {
          recordModuleName();
        }
        token = nextToken();
      }
      return true;
    }
    return false;
  }
  function processImports() {
    scanner.setText(sourceText);
    nextToken();
    while (true) {
      if (scanner.getToken() === 1 /* EndOfFileToken */) {
        break;
      }
      if (scanner.getToken() === 16 /* TemplateHead */) {
        const stack = [scanner.getToken()];
        loop:
          while (length(stack)) {
            const token = scanner.scan();
            switch (token) {
              case 1 /* EndOfFileToken */:
                break loop;
              case 102 /* ImportKeyword */:
                tryConsumeImport();
                break;
              case 16 /* TemplateHead */:
                stack.push(token);
                break;
              case 19 /* OpenBraceToken */:
                if (length(stack)) {
                  stack.push(token);
                }
                break;
              case 20 /* CloseBraceToken */:
                if (length(stack)) {
                  if (lastOrUndefined(stack) === 16 /* TemplateHead */) {
                    if (scanner.reScanTemplateToken(
                      /*isTaggedTemplate*/
                      false
                    ) === 18 /* TemplateTail */) {
                      stack.pop();
                    }
                  } else {
                    stack.pop();
                  }
                }
                break;
            }
          }
        nextToken();
      }
      if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || detectJavaScriptImports && (tryConsumeRequireCall(
        /*skipCurrentToken*/
        false,
        /*allowTemplateLiterals*/
        true
      ) || tryConsumeDefine())) {
        continue;
      } else {
        nextToken();
      }
    }
    scanner.setText(void 0);
  }
  if (readImportFiles) {
    processImports();
  }
  processCommentPragmas(pragmaContext, sourceText);
  processPragmasIntoFields(pragmaContext, noop);
  if (externalModule) {
    if (ambientExternalModules) {
      for (const decl of ambientExternalModules) {
        importedFiles.push(decl.ref);
      }
    }
    return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: void 0 };
  } else {
    let ambientModuleNames;
    if (ambientExternalModules) {
      for (const decl of ambientExternalModules) {
        if (decl.depth === 0) {
          if (!ambientModuleNames) {
            ambientModuleNames = [];
          }
          ambientModuleNames.push(decl.ref.fileName);
        } else {
          importedFiles.push(decl.ref);
        }
      }
    }
    return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
  }
}

// src/services/sourcemaps.ts
var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
function getSourceMapper(host) {
  const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
  const currentDirectory = host.getCurrentDirectory();
  const sourceFileLike = /* @__PURE__ */ new Map();
  const documentPositionMappers = /* @__PURE__ */ new Map();
  return { tryGetSourcePosition, tryGetGeneratedPosition, toLineColumnOffset, clearCache };
  function toPath3(fileName) {
    return toPath(fileName, currentDirectory, getCanonicalFileName);
  }
  function getDocumentPositionMapper2(generatedFileName, sourceFileName) {
    const path = toPath3(generatedFileName);
    const value = documentPositionMappers.get(path);
    if (value)
      return value;
    let mapper;
    if (host.getDocumentPositionMapper) {
      mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName);
    } else if (host.readFile) {
      const file = getSourceFileLike(generatedFileName);
      mapper = file && getDocumentPositionMapper(
        { getSourceFileLike, getCanonicalFileName, log: (s) => host.log(s) },
        generatedFileName,
        getLineInfo(file.text, getLineStarts(file)),
        (f) => !host.fileExists || host.fileExists(f) ? host.readFile(f) : void 0
      );
    }
    documentPositionMappers.set(path, mapper || identitySourceMapConsumer);
    return mapper || identitySourceMapConsumer;
  }
  function tryGetSourcePosition(info) {
    if (!isDeclarationFileName(info.fileName))
      return void 0;
    const file = getSourceFile(info.fileName);
    if (!file)
      return void 0;
    const newLoc = getDocumentPositionMapper2(info.fileName).getSourcePosition(info);
    return !newLoc || newLoc === info ? void 0 : tryGetSourcePosition(newLoc) || newLoc;
  }
  function tryGetGeneratedPosition(info) {
    if (isDeclarationFileName(info.fileName))
      return void 0;
    const sourceFile = getSourceFile(info.fileName);
    if (!sourceFile)
      return void 0;
    const program = host.getProgram();
    if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) {
      return void 0;
    }
    const options = program.getCompilerOptions();
    const outPath = outFile(options);
    const declarationPath = outPath ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName);
    if (declarationPath === void 0)
      return void 0;
    const newLoc = getDocumentPositionMapper2(declarationPath, info.fileName).getGeneratedPosition(info);
    return newLoc === info ? void 0 : newLoc;
  }
  function getSourceFile(fileName) {
    const program = host.getProgram();
    if (!program)
      return void 0;
    const path = toPath3(fileName);
    const file = program.getSourceFileByPath(path);
    return file && file.resolvedPath === path ? file : void 0;
  }
  function getOrCreateSourceFileLike(fileName) {
    const path = toPath3(fileName);
    const fileFromCache = sourceFileLike.get(path);
    if (fileFromCache !== void 0)
      return fileFromCache ? fileFromCache : void 0;
    if (!host.readFile || host.fileExists && !host.fileExists(path)) {
      sourceFileLike.set(path, false);
      return void 0;
    }
    const text = host.readFile(path);
    const file = text ? createSourceFileLike(text) : false;
    sourceFileLike.set(path, file);
    return file ? file : void 0;
  }
  function getSourceFileLike(fileName) {
    return !host.getSourceFileLike ? getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : host.getSourceFileLike(fileName);
  }
  function toLineColumnOffset(fileName, position) {
    const file = getSourceFileLike(fileName);
    return file.getLineAndCharacterOfPosition(position);
  }
  function clearCache() {
    sourceFileLike.clear();
    documentPositionMappers.clear();
  }
}
function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) {
  let mapFileName = tryGetSourceMappingURL(generatedFileLineInfo);
  if (mapFileName) {
    const match = base64UrlRegExp.exec(mapFileName);
    if (match) {
      if (match[1]) {
        const base64Object = match[1];
        return convertDocumentToSourceMapper(host, base64decode(sys, base64Object), generatedFileName);
      }
      mapFileName = void 0;
    }
  }
  const possibleMapLocations = [];
  if (mapFileName) {
    possibleMapLocations.push(mapFileName);
  }
  possibleMapLocations.push(generatedFileName + ".map");
  const originalMapFileName = mapFileName && getNormalizedAbsolutePath(mapFileName, getDirectoryPath(generatedFileName));
  for (const location of possibleMapLocations) {
    const mapFileName2 = getNormalizedAbsolutePath(location, getDirectoryPath(generatedFileName));
    const mapFileContents = readMapFile(mapFileName2, originalMapFileName);
    if (isString(mapFileContents)) {
      return convertDocumentToSourceMapper(host, mapFileContents, mapFileName2);
    }
    if (mapFileContents !== void 0) {
      return mapFileContents || void 0;
    }
  }
  return void 0;
}
function convertDocumentToSourceMapper(host, contents, mapFileName) {
  const map2 = tryParseRawSourceMap(contents);
  if (!map2 || !map2.sources || !map2.file || !map2.mappings) {
    return void 0;
  }
  if (map2.sourcesContent && map2.sourcesContent.some(isString))
    return void 0;
  return createDocumentPositionMapper(host, map2, mapFileName);
}
function createSourceFileLike(text, lineMap) {
  return {
    text,
    lineMap,
    getLineAndCharacterOfPosition(pos) {
      return computeLineAndCharacterOfPosition(getLineStarts(this), pos);
    }
  };
}

// src/services/suggestionDiagnostics.ts
var visitedNestedConvertibleFunctions = /* @__PURE__ */ new Map();
function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
  program.getSemanticDiagnostics(sourceFile, cancellationToken);
  const diags = [];
  const checker = program.getTypeChecker();
  const isCommonJSFile = sourceFile.impliedNodeFormat === 1 /* CommonJS */ || fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]);
  if (!isCommonJSFile && sourceFile.commonJsModuleIndicator && (programContainsEsModules(program) || compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) {
    diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module));
  }
  const isJsFile = isSourceFileJS(sourceFile);
  visitedNestedConvertibleFunctions.clear();
  check(sourceFile);
  if (getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
    for (const moduleSpecifier of sourceFile.imports) {
      const importNode = importFromModuleSpecifier(moduleSpecifier);
      const name = importNameForConvertToDefaultImport(importNode);
      if (!name)
        continue;
      const module2 = getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier));
      const resolvedFile = module2 && program.getSourceFile(module2.resolvedFileName);
      if (resolvedFile && resolvedFile.externalModuleIndicator && resolvedFile.externalModuleIndicator !== true && isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
        diags.push(createDiagnosticForNode(name, Diagnostics.Import_may_be_converted_to_a_default_import));
      }
    }
  }
  addRange(diags, sourceFile.bindSuggestionDiagnostics);
  addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
  return diags.sort((d1, d2) => d1.start - d2.start);
  function check(node) {
    if (isJsFile) {
      if (canBeConvertedToClass(node, checker)) {
        diags.push(createDiagnosticForNode(isVariableDeclaration(node.parent) ? node.parent.name : node, Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
      }
    } else {
      if (isVariableStatement(node) && node.parent === sourceFile && node.declarationList.flags & 2 /* Const */ && node.declarationList.declarations.length === 1) {
        const init = node.declarationList.declarations[0].initializer;
        if (init && isRequireCall(
          init,
          /*requireStringLiteralLikeArgument*/
          true
        )) {
          diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import));
        }
      }
      const jsdocTypedefNode = ts_codefix_exports.getJSDocTypedefNode(node);
      if (jsdocTypedefNode) {
        diags.push(createDiagnosticForNode(jsdocTypedefNode, Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type));
      }
      if (ts_codefix_exports.parameterShouldGetTypeFromJSDoc(node)) {
        diags.push(createDiagnosticForNode(node.name || node, Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
      }
    }
    if (canBeConvertedToAsync(node)) {
      addConvertToAsyncFunctionDiagnostics(node, checker, diags);
    }
    node.forEachChild(check);
  }
}
function containsTopLevelCommonjs(sourceFile) {
  return sourceFile.statements.some((statement) => {
    switch (statement.kind) {
      case 242 /* VariableStatement */:
        return statement.declarationList.declarations.some((decl) => !!decl.initializer && isRequireCall(
          propertyAccessLeftHandSide(decl.initializer),
          /*requireStringLiteralLikeArgument*/
          true
        ));
      case 243 /* ExpressionStatement */: {
        const { expression } = statement;
        if (!isBinaryExpression(expression))
          return isRequireCall(
            expression,
            /*requireStringLiteralLikeArgument*/
            true
          );
        const kind = getAssignmentDeclarationKind(expression);
        return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
      }
      default:
        return false;
    }
  });
}
function propertyAccessLeftHandSide(node) {
  return isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
}
function importNameForConvertToDefaultImport(node) {
  switch (node.kind) {
    case 271 /* ImportDeclaration */:
      const { importClause, moduleSpecifier } = node;
      return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 273 /* NamespaceImport */ && isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : void 0;
    case 270 /* ImportEqualsDeclaration */:
      return node.name;
    default:
      return void 0;
  }
}
function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
  if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) {
    diags.push(createDiagnosticForNode(
      !node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node,
      Diagnostics.This_may_be_converted_to_an_async_function
    ));
  }
}
function isConvertibleFunction(node, checker) {
  return !isAsyncFunction(node) && node.body && isBlock(node.body) && hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker);
}
function returnsPromise(node, checker) {
  const signature = checker.getSignatureFromDeclaration(node);
  const returnType = signature ? checker.getReturnTypeOfSignature(signature) : void 0;
  return !!returnType && !!checker.getPromisedTypeOfPromise(returnType);
}
function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
  return isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
}
function hasReturnStatementWithPromiseHandler(body, checker) {
  return !!forEachReturnStatement(body, (statement) => isReturnStatementWithFixablePromiseHandler(statement, checker));
}
function isReturnStatementWithFixablePromiseHandler(node, checker) {
  return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker);
}
function isFixablePromiseHandler(node, checker) {
  if (!isPromiseHandler(node) || !hasSupportedNumberOfArguments(node) || !node.arguments.every((arg) => isFixablePromiseArgument(arg, checker))) {
    return false;
  }
  let currentNode = node.expression.expression;
  while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) {
    if (isCallExpression(currentNode)) {
      if (!hasSupportedNumberOfArguments(currentNode) || !currentNode.arguments.every((arg) => isFixablePromiseArgument(arg, checker))) {
        return false;
      }
      currentNode = currentNode.expression.expression;
    } else {
      currentNode = currentNode.expression;
    }
  }
  return true;
}
function isPromiseHandler(node) {
  return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch") || hasPropertyAccessExpressionWithName(node, "finally"));
}
function hasSupportedNumberOfArguments(node) {
  const name = node.expression.name.text;
  const maxArguments = name === "then" ? 2 : name === "catch" ? 1 : name === "finally" ? 1 : 0;
  if (node.arguments.length > maxArguments)
    return false;
  if (node.arguments.length < maxArguments)
    return true;
  return maxArguments === 1 || some(node.arguments, (arg) => {
    return arg.kind === 106 /* NullKeyword */ || isIdentifier(arg) && arg.text === "undefined";
  });
}
function isFixablePromiseArgument(arg, checker) {
  switch (arg.kind) {
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
      const functionFlags = getFunctionFlags(arg);
      if (functionFlags & 1 /* Generator */) {
        return false;
      }
    case 218 /* ArrowFunction */:
      visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
    case 106 /* NullKeyword */:
      return true;
    case 80 /* Identifier */:
    case 210 /* PropertyAccessExpression */: {
      const symbol = checker.getSymbolAtLocation(arg);
      if (!symbol) {
        return false;
      }
      return checker.isUndefinedSymbol(symbol) || some(skipAlias(symbol, checker).declarations, (d) => isFunctionLike(d) || hasInitializer(d) && !!d.initializer && isFunctionLike(d.initializer));
    }
    default:
      return false;
  }
}
function getKeyFromNode(exp) {
  return `${exp.pos.toString()}:${exp.end.toString()}`;
}
function canBeConvertedToClass(node, checker) {
  var _a, _b, _c, _d;
  if (isFunctionExpression(node)) {
    if (isVariableDeclaration(node.parent) && ((_a = node.symbol.members) == null ? void 0 : _a.size)) {
      return true;
    }
    const symbol = checker.getSymbolOfExpando(
      node,
      /*allowDeclaration*/
      false
    );
    return !!(symbol && (((_b = symbol.exports) == null ? void 0 : _b.size) || ((_c = symbol.members) == null ? void 0 : _c.size)));
  }
  if (isFunctionDeclaration(node)) {
    return !!((_d = node.symbol.members) == null ? void 0 : _d.size);
  }
  return false;
}
function canBeConvertedToAsync(node) {
  switch (node.kind) {
    case 261 /* FunctionDeclaration */:
    case 173 /* MethodDeclaration */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
      return true;
    default:
      return false;
  }
}

// src/services/transpile.ts
var optionsRedundantWithVerbatimModuleSyntax = /* @__PURE__ */ new Set([
  "isolatedModules",
  "preserveValueImports",
  "importsNotUsedAsValues"
]);
function transpileModule(input, transpileOptions) {
  const diagnostics = [];
  const options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : {};
  const defaultOptions = getDefaultCompilerOptions2();
  for (const key in defaultOptions) {
    if (hasProperty(defaultOptions, key) && options[key] === void 0) {
      options[key] = defaultOptions[key];
    }
  }
  for (const option of transpileOptionValueCompilerOptions) {
    if (options.verbatimModuleSyntax && optionsRedundantWithVerbatimModuleSyntax.has(option.name)) {
      continue;
    }
    options[option.name] = option.transpileOptionValue;
  }
  options.suppressOutputPathCheck = true;
  options.allowNonTsExtensions = true;
  const newLine = getNewLineCharacter(options);
  const compilerHost = {
    getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : void 0,
    writeFile: (name, text) => {
      if (fileExtensionIs(name, ".map")) {
        Debug.assertEqual(sourceMapText, void 0, "Unexpected multiple source map outputs, file:", name);
        sourceMapText = text;
      } else {
        Debug.assertEqual(outputText, void 0, "Unexpected multiple outputs, file:", name);
        outputText = text;
      }
    },
    getDefaultLibFileName: () => "lib.d.ts",
    useCaseSensitiveFileNames: () => false,
    getCanonicalFileName: (fileName) => fileName,
    getCurrentDirectory: () => "",
    getNewLine: () => newLine,
    fileExists: (fileName) => fileName === inputFileName,
    readFile: () => "",
    directoryExists: () => true,
    getDirectories: () => []
  };
  const inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts");
  const sourceFile = createSourceFile(
    inputFileName,
    input,
    {
      languageVersion: getEmitScriptTarget(options),
      impliedNodeFormat: getImpliedNodeFormatForFile(
        toPath(inputFileName, "", compilerHost.getCanonicalFileName),
        /*packageJsonInfoCache*/
        void 0,
        compilerHost,
        options
      ),
      setExternalModuleIndicator: getSetExternalModuleIndicator(options)
    }
  );
  if (transpileOptions.moduleName) {
    sourceFile.moduleName = transpileOptions.moduleName;
  }
  if (transpileOptions.renamedDependencies) {
    sourceFile.renamedDependencies = new Map(Object.entries(transpileOptions.renamedDependencies));
  }
  let outputText;
  let sourceMapText;
  const program = createProgram([inputFileName], options, compilerHost);
  if (transpileOptions.reportDiagnostics) {
    addRange(
      /*to*/
      diagnostics,
      /*from*/
      program.getSyntacticDiagnostics(sourceFile)
    );
    addRange(
      /*to*/
      diagnostics,
      /*from*/
      program.getOptionsDiagnostics()
    );
  }
  program.emit(
    /*targetSourceFile*/
    void 0,
    /*writeFile*/
    void 0,
    /*cancellationToken*/
    void 0,
    /*emitOnlyDtsFiles*/
    void 0,
    transpileOptions.transformers
  );
  if (outputText === void 0)
    return Debug.fail("Output generation failed");
  return { outputText, diagnostics, sourceMapText };
}
function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
  const output = transpileModule(input, { compilerOptions, fileName, reportDiagnostics: !!diagnostics, moduleName });
  addRange(diagnostics, output.diagnostics);
  return output.outputText;
}
var commandLineOptionsStringToEnum;
function fixupCompilerOptions(options, diagnostics) {
  commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || filter(optionDeclarations, (o) => typeof o.type === "object" && !forEachEntry(o.type, (v) => typeof v !== "number"));
  options = cloneCompilerOptions(options);
  for (const opt of commandLineOptionsStringToEnum) {
    if (!hasProperty(options, opt.name)) {
      continue;
    }
    const value = options[opt.name];
    if (isString(value)) {
      options[opt.name] = parseCustomTypeOption(opt, value, diagnostics);
    } else {
      if (!forEachEntry(opt.type, (v) => v === value)) {
        diagnostics.push(createCompilerDiagnosticForInvalidCustomType(opt));
      }
    }
  }
  return options;
}

// src/services/_namespaces/ts.NavigateTo.ts
var ts_NavigateTo_exports = {};
__export(ts_NavigateTo_exports, {
  getNavigateToItems: () => getNavigateToItems
});

// src/services/navigateTo.ts
function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
  const patternMatcher = createPatternMatcher(searchValue);
  if (!patternMatcher)
    return emptyArray;
  const rawItems = [];
  for (const sourceFile of sourceFiles) {
    cancellationToken.throwIfCancellationRequested();
    if (excludeDtsFiles && sourceFile.isDeclarationFile) {
      continue;
    }
    sourceFile.getNamedDeclarations().forEach((declarations, name) => {
      getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems);
    });
  }
  rawItems.sort(compareNavigateToItems);
  return (maxResultCount === void 0 ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
}
function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) {
  const match = patternMatcher.getMatchForLastSegmentOfPattern(name);
  if (!match) {
    return;
  }
  for (const declaration of declarations) {
    if (!shouldKeepItem(declaration, checker))
      continue;
    if (patternMatcher.patternContainsDots) {
      const fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
      if (fullMatch) {
        rawItems.push({ name, fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration });
      }
    } else {
      rawItems.push({ name, fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration });
    }
  }
}
function shouldKeepItem(declaration, checker) {
  switch (declaration.kind) {
    case 272 /* ImportClause */:
    case 275 /* ImportSpecifier */:
    case 270 /* ImportEqualsDeclaration */:
      const importer = checker.getSymbolAtLocation(declaration.name);
      const imported = checker.getAliasedSymbol(importer);
      return importer.escapedName !== imported.escapedName;
    default:
      return true;
  }
}
function tryAddSingleDeclarationName(declaration, containers) {
  const name = getNameOfDeclaration(declaration);
  return !!name && (pushLiteral(name, containers) || name.kind === 166 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers));
}
function tryAddComputedPropertyName(expression, containers) {
  return pushLiteral(expression, containers) || isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers);
}
function pushLiteral(node, containers) {
  return isPropertyNameLiteral(node) && (containers.push(getTextOfIdentifierOrLiteral(node)), true);
}
function getContainers(declaration) {
  const containers = [];
  const name = getNameOfDeclaration(declaration);
  if (name && name.kind === 166 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) {
    return emptyArray;
  }
  containers.shift();
  let container = getContainerNode(declaration);
  while (container) {
    if (!tryAddSingleDeclarationName(container, containers)) {
      return emptyArray;
    }
    container = getContainerNode(container);
  }
  return containers.reverse();
}
function compareNavigateToItems(i1, i2) {
  return compareValues(i1.matchKind, i2.matchKind) || compareStringsCaseSensitiveUI(i1.name, i2.name);
}
function createNavigateToItem(rawItem) {
  const declaration = rawItem.declaration;
  const container = getContainerNode(declaration);
  const containerName = container && getNameOfDeclaration(container);
  return {
    name: rawItem.name,
    kind: getNodeKind(declaration),
    kindModifiers: getNodeModifiers(declaration),
    matchKind: PatternMatchKind[rawItem.matchKind],
    isCaseSensitive: rawItem.isCaseSensitive,
    fileName: rawItem.fileName,
    textSpan: createTextSpanFromNode(declaration),
    // TODO(jfreeman): What should be the containerName when the container has a computed name?
    containerName: containerName ? containerName.text : "",
    containerKind: containerName ? getNodeKind(container) : "" /* unknown */
  };
}

// src/services/_namespaces/ts.NavigationBar.ts
var ts_NavigationBar_exports = {};
__export(ts_NavigationBar_exports, {
  getNavigationBarItems: () => getNavigationBarItems,
  getNavigationTree: () => getNavigationTree
});

// src/services/navigationBar.ts
var whiteSpaceRegex = /\s+/g;
var maxLength = 150;
var curCancellationToken;
var curSourceFile;
var parentsStack = [];
var parent;
var trackedEs5ClassesStack = [];
var trackedEs5Classes;
var emptyChildItemArray = [];
function getNavigationBarItems(sourceFile, cancellationToken) {
  curCancellationToken = cancellationToken;
  curSourceFile = sourceFile;
  try {
    return map(primaryNavBarMenuItems(rootNavigationBarNode(sourceFile)), convertToPrimaryNavBarMenuItem);
  } finally {
    reset();
  }
}
function getNavigationTree(sourceFile, cancellationToken) {
  curCancellationToken = cancellationToken;
  curSourceFile = sourceFile;
  try {
    return convertToTree(rootNavigationBarNode(sourceFile));
  } finally {
    reset();
  }
}
function reset() {
  curSourceFile = void 0;
  curCancellationToken = void 0;
  parentsStack = [];
  parent = void 0;
  emptyChildItemArray = [];
}
function nodeText(node) {
  return cleanText(node.getText(curSourceFile));
}
function navigationBarNodeKind(n) {
  return n.node.kind;
}
function pushChild(parent2, child) {
  if (parent2.children) {
    parent2.children.push(child);
  } else {
    parent2.children = [child];
  }
}
function rootNavigationBarNode(sourceFile) {
  Debug.assert(!parentsStack.length);
  const root = { node: sourceFile, name: void 0, additionalNodes: void 0, parent: void 0, children: void 0, indent: 0 };
  parent = root;
  for (const statement of sourceFile.statements) {
    addChildrenRecursively(statement);
  }
  endNode();
  Debug.assert(!parent && !parentsStack.length);
  return root;
}
function addLeafNode(node, name) {
  pushChild(parent, emptyNavigationBarNode(node, name));
}
function emptyNavigationBarNode(node, name) {
  return {
    node,
    name: name || (isDeclaration(node) || isExpression(node) ? getNameOfDeclaration(node) : void 0),
    additionalNodes: void 0,
    parent,
    children: void 0,
    indent: parent.indent + 1
  };
}
function addTrackedEs5Class(name) {
  if (!trackedEs5Classes) {
    trackedEs5Classes = /* @__PURE__ */ new Map();
  }
  trackedEs5Classes.set(name, true);
}
function endNestedNodes(depth) {
  for (let i = 0; i < depth; i++)
    endNode();
}
function startNestedNodes(targetNode, entityName) {
  const names = [];
  while (!isPropertyNameLiteral(entityName)) {
    const name = getNameOrArgument(entityName);
    const nameText = getElementOrPropertyAccessName(entityName);
    entityName = entityName.expression;
    if (nameText === "prototype" || isPrivateIdentifier(name))
      continue;
    names.push(name);
  }
  names.push(entityName);
  for (let i = names.length - 1; i > 0; i--) {
    const name = names[i];
    startNode(targetNode, name);
  }
  return [names.length - 1, names[0]];
}
function startNode(node, name) {
  const navNode = emptyNavigationBarNode(node, name);
  pushChild(parent, navNode);
  parentsStack.push(parent);
  trackedEs5ClassesStack.push(trackedEs5Classes);
  trackedEs5Classes = void 0;
  parent = navNode;
}
function endNode() {
  if (parent.children) {
    mergeChildren(parent.children, parent);
    sortChildren(parent.children);
  }
  parent = parentsStack.pop();
  trackedEs5Classes = trackedEs5ClassesStack.pop();
}
function addNodeWithRecursiveChild(node, child, name) {
  startNode(node, name);
  addChildrenRecursively(child);
  endNode();
}
function addNodeWithRecursiveInitializer(node) {
  if (node.initializer && isFunctionOrClassExpression(node.initializer)) {
    startNode(node);
    forEachChild(node.initializer, addChildrenRecursively);
    endNode();
  } else {
    addNodeWithRecursiveChild(node, node.initializer);
  }
}
function hasNavigationBarName(node) {
  return !hasDynamicName(node) || node.kind !== 225 /* BinaryExpression */ && isPropertyAccessExpression(node.name.expression) && isIdentifier(node.name.expression.expression) && idText(node.name.expression.expression) === "Symbol";
}
function addChildrenRecursively(node) {
  curCancellationToken.throwIfCancellationRequested();
  if (!node || isToken(node)) {
    return;
  }
  switch (node.kind) {
    case 175 /* Constructor */:
      const ctr = node;
      addNodeWithRecursiveChild(ctr, ctr.body);
      for (const param of ctr.parameters) {
        if (isParameterPropertyDeclaration(param, ctr)) {
          addLeafNode(param);
        }
      }
      break;
    case 173 /* MethodDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 172 /* MethodSignature */:
      if (hasNavigationBarName(node)) {
        addNodeWithRecursiveChild(node, node.body);
      }
      break;
    case 171 /* PropertyDeclaration */:
      if (hasNavigationBarName(node)) {
        addNodeWithRecursiveInitializer(node);
      }
      break;
    case 170 /* PropertySignature */:
      if (hasNavigationBarName(node)) {
        addLeafNode(node);
      }
      break;
    case 272 /* ImportClause */:
      const importClause = node;
      if (importClause.name) {
        addLeafNode(importClause.name);
      }
      const { namedBindings } = importClause;
      if (namedBindings) {
        if (namedBindings.kind === 273 /* NamespaceImport */) {
          addLeafNode(namedBindings);
        } else {
          for (const element of namedBindings.elements) {
            addLeafNode(element);
          }
        }
      }
      break;
    case 303 /* ShorthandPropertyAssignment */:
      addNodeWithRecursiveChild(node, node.name);
      break;
    case 304 /* SpreadAssignment */:
      const { expression } = node;
      isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node);
      break;
    case 207 /* BindingElement */:
    case 302 /* PropertyAssignment */:
    case 259 /* VariableDeclaration */: {
      const child = node;
      if (isBindingPattern(child.name)) {
        addChildrenRecursively(child.name);
      } else {
        addNodeWithRecursiveInitializer(child);
      }
      break;
    }
    case 261 /* FunctionDeclaration */:
      const nameNode = node.name;
      if (nameNode && isIdentifier(nameNode)) {
        addTrackedEs5Class(nameNode.text);
      }
      addNodeWithRecursiveChild(node, node.body);
      break;
    case 218 /* ArrowFunction */:
    case 217 /* FunctionExpression */:
      addNodeWithRecursiveChild(node, node.body);
      break;
    case 265 /* EnumDeclaration */:
      startNode(node);
      for (const member of node.members) {
        if (!isComputedProperty(member)) {
          addLeafNode(member);
        }
      }
      endNode();
      break;
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
    case 263 /* InterfaceDeclaration */:
      startNode(node);
      for (const member of node.members) {
        addChildrenRecursively(member);
      }
      endNode();
      break;
    case 266 /* ModuleDeclaration */:
      addNodeWithRecursiveChild(node, getInteriorModule(node).body);
      break;
    case 276 /* ExportAssignment */: {
      const expression2 = node.expression;
      const child = isObjectLiteralExpression(expression2) || isCallExpression(expression2) ? expression2 : isArrowFunction(expression2) || isFunctionExpression(expression2) ? expression2.body : void 0;
      if (child) {
        startNode(node);
        addChildrenRecursively(child);
        endNode();
      } else {
        addLeafNode(node);
      }
      break;
    }
    case 280 /* ExportSpecifier */:
    case 270 /* ImportEqualsDeclaration */:
    case 180 /* IndexSignature */:
    case 178 /* CallSignature */:
    case 179 /* ConstructSignature */:
    case 264 /* TypeAliasDeclaration */:
      addLeafNode(node);
      break;
    case 212 /* CallExpression */:
    case 225 /* BinaryExpression */: {
      const special = getAssignmentDeclarationKind(node);
      switch (special) {
        case 1 /* ExportsProperty */:
        case 2 /* ModuleExports */:
          addNodeWithRecursiveChild(node, node.right);
          return;
        case 6 /* Prototype */:
        case 3 /* PrototypeProperty */: {
          const binaryExpression = node;
          const assignmentTarget = binaryExpression.left;
          const prototypeAccess = special === 3 /* PrototypeProperty */ ? assignmentTarget.expression : assignmentTarget;
          let depth = 0;
          let className;
          if (isIdentifier(prototypeAccess.expression)) {
            addTrackedEs5Class(prototypeAccess.expression.text);
            className = prototypeAccess.expression;
          } else {
            [depth, className] = startNestedNodes(binaryExpression, prototypeAccess.expression);
          }
          if (special === 6 /* Prototype */) {
            if (isObjectLiteralExpression(binaryExpression.right)) {
              if (binaryExpression.right.properties.length > 0) {
                startNode(binaryExpression, className);
                forEachChild(binaryExpression.right, addChildrenRecursively);
                endNode();
              }
            }
          } else if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) {
            addNodeWithRecursiveChild(
              node,
              binaryExpression.right,
              className
            );
          } else {
            startNode(binaryExpression, className);
            addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name);
            endNode();
          }
          endNestedNodes(depth);
          return;
        }
        case 7 /* ObjectDefinePropertyValue */:
        case 9 /* ObjectDefinePrototypeProperty */: {
          const defineCall = node;
          const className = special === 7 /* ObjectDefinePropertyValue */ ? defineCall.arguments[0] : defineCall.arguments[0].expression;
          const memberName = defineCall.arguments[1];
          const [depth, classNameIdentifier] = startNestedNodes(node, className);
          startNode(node, classNameIdentifier);
          startNode(node, setTextRange(factory.createIdentifier(memberName.text), memberName));
          addChildrenRecursively(node.arguments[2]);
          endNode();
          endNode();
          endNestedNodes(depth);
          return;
        }
        case 5 /* Property */: {
          const binaryExpression = node;
          const assignmentTarget = binaryExpression.left;
          const targetFunction = assignmentTarget.expression;
          if (isIdentifier(targetFunction) && getElementOrPropertyAccessName(assignmentTarget) !== "prototype" && trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) {
            if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) {
              addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction);
            } else if (isBindableStaticAccessExpression(assignmentTarget)) {
              startNode(binaryExpression, targetFunction);
              addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, getNameOrArgument(assignmentTarget));
              endNode();
            }
            return;
          }
          break;
        }
        case 4 /* ThisProperty */:
        case 0 /* None */:
        case 8 /* ObjectDefinePropertyExports */:
          break;
        default:
          Debug.assertNever(special);
      }
    }
    default:
      if (hasJSDocNodes(node)) {
        forEach(node.jsDoc, (jsDoc) => {
          forEach(jsDoc.tags, (tag) => {
            if (isJSDocTypeAlias(tag)) {
              addLeafNode(tag);
            }
          });
        });
      }
      forEachChild(node, addChildrenRecursively);
  }
}
function mergeChildren(children, node) {
  const nameToItems = /* @__PURE__ */ new Map();
  filterMutate(children, (child, index) => {
    const declName = child.name || getNameOfDeclaration(child.node);
    const name = declName && nodeText(declName);
    if (!name) {
      return true;
    }
    const itemsWithSameName = nameToItems.get(name);
    if (!itemsWithSameName) {
      nameToItems.set(name, child);
      return true;
    }
    if (itemsWithSameName instanceof Array) {
      for (const itemWithSameName of itemsWithSameName) {
        if (tryMerge(itemWithSameName, child, index, node)) {
          return false;
        }
      }
      itemsWithSameName.push(child);
      return true;
    } else {
      const itemWithSameName = itemsWithSameName;
      if (tryMerge(itemWithSameName, child, index, node)) {
        return false;
      }
      nameToItems.set(name, [itemWithSameName, child]);
      return true;
    }
  });
}
var isEs5ClassMember = {
  [5 /* Property */]: true,
  [3 /* PrototypeProperty */]: true,
  [7 /* ObjectDefinePropertyValue */]: true,
  [9 /* ObjectDefinePrototypeProperty */]: true,
  [0 /* None */]: false,
  [1 /* ExportsProperty */]: false,
  [2 /* ModuleExports */]: false,
  [8 /* ObjectDefinePropertyExports */]: false,
  [6 /* Prototype */]: true,
  [4 /* ThisProperty */]: false
};
function tryMergeEs5Class(a, b, bIndex, parent2) {
  function isPossibleConstructor(node) {
    return isFunctionExpression(node) || isFunctionDeclaration(node) || isVariableDeclaration(node);
  }
  const bAssignmentDeclarationKind = isBinaryExpression(b.node) || isCallExpression(b.node) ? getAssignmentDeclarationKind(b.node) : 0 /* None */;
  const aAssignmentDeclarationKind = isBinaryExpression(a.node) || isCallExpression(a.node) ? getAssignmentDeclarationKind(a.node) : 0 /* None */;
  if (isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind] || isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind] || isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind] || isClassDeclaration(a.node) && isSynthesized(a.node) && isEs5ClassMember[bAssignmentDeclarationKind] || isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind] || isClassDeclaration(a.node) && isSynthesized(a.node) && isPossibleConstructor(b.node) || isClassDeclaration(b.node) && isPossibleConstructor(a.node) && isSynthesized(a.node)) {
    let lastANode = a.additionalNodes && lastOrUndefined(a.additionalNodes) || a.node;
    if (!isClassDeclaration(a.node) && !isClassDeclaration(b.node) || isPossibleConstructor(a.node) || isPossibleConstructor(b.node)) {
      const ctorFunction = isPossibleConstructor(a.node) ? a.node : isPossibleConstructor(b.node) ? b.node : void 0;
      if (ctorFunction !== void 0) {
        const ctorNode = setTextRange(
          factory.createConstructorDeclaration(
            /*modifiers*/
            void 0,
            [],
            /*body*/
            void 0
          ),
          ctorFunction
        );
        const ctor = emptyNavigationBarNode(ctorNode);
        ctor.indent = a.indent + 1;
        ctor.children = a.node === ctorFunction ? a.children : b.children;
        a.children = a.node === ctorFunction ? concatenate([ctor], b.children || [b]) : concatenate(a.children || [{ ...a }], [ctor]);
      } else {
        if (a.children || b.children) {
          a.children = concatenate(a.children || [{ ...a }], b.children || [b]);
          if (a.children) {
            mergeChildren(a.children, a);
            sortChildren(a.children);
          }
        }
      }
      lastANode = a.node = setTextRange(factory.createClassDeclaration(
        /*modifiers*/
        void 0,
        a.name || factory.createIdentifier("__class__"),
        /*typeParameters*/
        void 0,
        /*heritageClauses*/
        void 0,
        []
      ), a.node);
    } else {
      a.children = concatenate(a.children, b.children);
      if (a.children) {
        mergeChildren(a.children, a);
      }
    }
    const bNode = b.node;
    if (parent2.children[bIndex - 1].node.end === lastANode.end) {
      setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end });
    } else {
      if (!a.additionalNodes)
        a.additionalNodes = [];
      a.additionalNodes.push(setTextRange(factory.createClassDeclaration(
        /*modifiers*/
        void 0,
        a.name || factory.createIdentifier("__class__"),
        /*typeParameters*/
        void 0,
        /*heritageClauses*/
        void 0,
        []
      ), b.node));
    }
    return true;
  }
  return bAssignmentDeclarationKind === 0 /* None */ ? false : true;
}
function tryMerge(a, b, bIndex, parent2) {
  if (tryMergeEs5Class(a, b, bIndex, parent2)) {
    return true;
  }
  if (shouldReallyMerge(a.node, b.node, parent2)) {
    merge(a, b);
    return true;
  }
  return false;
}
function shouldReallyMerge(a, b, parent2) {
  if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent2) && isOwnChild(b, parent2))) {
    return false;
  }
  switch (a.kind) {
    case 171 /* PropertyDeclaration */:
    case 173 /* MethodDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
      return isStatic(a) === isStatic(b);
    case 266 /* ModuleDeclaration */:
      return areSameModule(a, b) && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b);
    default:
      return true;
  }
}
function isSynthesized(node) {
  return !!(node.flags & 8 /* Synthesized */);
}
function isOwnChild(n, parent2) {
  const par = isModuleBlock(n.parent) ? n.parent.parent : n.parent;
  return par === parent2.node || contains(parent2.additionalNodes, par);
}
function areSameModule(a, b) {
  if (!a.body || !b.body) {
    return a.body === b.body;
  }
  return a.body.kind === b.body.kind && (a.body.kind !== 266 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
}
function merge(target, source) {
  target.additionalNodes = target.additionalNodes || [];
  target.additionalNodes.push(source.node);
  if (source.additionalNodes) {
    target.additionalNodes.push(...source.additionalNodes);
  }
  target.children = concatenate(target.children, source.children);
  if (target.children) {
    mergeChildren(target.children, target);
    sortChildren(target.children);
  }
}
function sortChildren(children) {
  children.sort(compareChildren);
}
function compareChildren(child1, child2) {
  return compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) || compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2));
}
function tryGetName(node) {
  if (node.kind === 266 /* ModuleDeclaration */) {
    return getModuleName(node);
  }
  const declName = getNameOfDeclaration(node);
  if (declName && isPropertyName(declName)) {
    const propertyName = getPropertyNameForPropertyNameNode(declName);
    return propertyName && unescapeLeadingUnderscores(propertyName);
  }
  switch (node.kind) {
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
    case 230 /* ClassExpression */:
      return getFunctionOrClassName(node);
    default:
      return void 0;
  }
}
function getItemName(node, name) {
  if (node.kind === 266 /* ModuleDeclaration */) {
    return cleanText(getModuleName(node));
  }
  if (name) {
    const text = isIdentifier(name) ? name.text : isElementAccessExpression(name) ? `[${nodeText(name.argumentExpression)}]` : nodeText(name);
    if (text.length > 0) {
      return cleanText(text);
    }
  }
  switch (node.kind) {
    case 311 /* SourceFile */:
      const sourceFile = node;
      return isExternalModule(sourceFile) ? `"${escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName))))}"` : "<global>";
    case 276 /* ExportAssignment */:
      return isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
    case 218 /* ArrowFunction */:
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
      if (getSyntacticModifierFlags(node) & 1024 /* Default */) {
        return "default";
      }
      return getFunctionOrClassName(node);
    case 175 /* Constructor */:
      return "constructor";
    case 179 /* ConstructSignature */:
      return "new()";
    case 178 /* CallSignature */:
      return "()";
    case 180 /* IndexSignature */:
      return "[]";
    default:
      return "<unknown>";
  }
}
function primaryNavBarMenuItems(root) {
  const primaryNavBarMenuItems2 = [];
  function recur(item) {
    if (shouldAppearInPrimaryNavBarMenu(item)) {
      primaryNavBarMenuItems2.push(item);
      if (item.children) {
        for (const child of item.children) {
          recur(child);
        }
      }
    }
  }
  recur(root);
  return primaryNavBarMenuItems2;
  function shouldAppearInPrimaryNavBarMenu(item) {
    if (item.children) {
      return true;
    }
    switch (navigationBarNodeKind(item)) {
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
      case 265 /* EnumDeclaration */:
      case 263 /* InterfaceDeclaration */:
      case 266 /* ModuleDeclaration */:
      case 311 /* SourceFile */:
      case 264 /* TypeAliasDeclaration */:
      case 352 /* JSDocTypedefTag */:
      case 344 /* JSDocCallbackTag */:
        return true;
      case 218 /* ArrowFunction */:
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
        return isTopLevelFunctionDeclaration(item);
      default:
        return false;
    }
    function isTopLevelFunctionDeclaration(item2) {
      if (!item2.node.body) {
        return false;
      }
      switch (navigationBarNodeKind(item2.parent)) {
        case 267 /* ModuleBlock */:
        case 311 /* SourceFile */:
        case 173 /* MethodDeclaration */:
        case 175 /* Constructor */:
          return true;
        default:
          return false;
      }
    }
  }
}
function convertToTree(n) {
  return {
    text: getItemName(n.node, n.name),
    kind: getNodeKind(n.node),
    kindModifiers: getModifiers2(n.node),
    spans: getSpans(n),
    nameSpan: n.name && getNodeSpan(n.name),
    childItems: map(n.children, convertToTree)
  };
}
function convertToPrimaryNavBarMenuItem(n) {
  return {
    text: getItemName(n.node, n.name),
    kind: getNodeKind(n.node),
    kindModifiers: getModifiers2(n.node),
    spans: getSpans(n),
    childItems: map(n.children, convertToSecondaryNavBarMenuItem) || emptyChildItemArray,
    indent: n.indent,
    bolded: false,
    grayed: false
  };
  function convertToSecondaryNavBarMenuItem(n2) {
    return {
      text: getItemName(n2.node, n2.name),
      kind: getNodeKind(n2.node),
      kindModifiers: getNodeModifiers(n2.node),
      spans: getSpans(n2),
      childItems: emptyChildItemArray,
      indent: 0,
      bolded: false,
      grayed: false
    };
  }
}
function getSpans(n) {
  const spans = [getNodeSpan(n.node)];
  if (n.additionalNodes) {
    for (const node of n.additionalNodes) {
      spans.push(getNodeSpan(node));
    }
  }
  return spans;
}
function getModuleName(moduleDeclaration) {
  if (isAmbientModule(moduleDeclaration)) {
    return getTextOfNode(moduleDeclaration.name);
  }
  return getFullyQualifiedModuleName(moduleDeclaration);
}
function getFullyQualifiedModuleName(moduleDeclaration) {
  const result = [getTextOfIdentifierOrLiteral(moduleDeclaration.name)];
  while (moduleDeclaration.body && moduleDeclaration.body.kind === 266 /* ModuleDeclaration */) {
    moduleDeclaration = moduleDeclaration.body;
    result.push(getTextOfIdentifierOrLiteral(moduleDeclaration.name));
  }
  return result.join(".");
}
function getInteriorModule(decl) {
  return decl.body && isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl;
}
function isComputedProperty(member) {
  return !member.name || member.name.kind === 166 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
  return node.kind === 311 /* SourceFile */ ? createTextSpanFromRange(node) : createTextSpanFromNode(node, curSourceFile);
}
function getModifiers2(node) {
  if (node.parent && node.parent.kind === 259 /* VariableDeclaration */) {
    node = node.parent;
  }
  return getNodeModifiers(node);
}
function getFunctionOrClassName(node) {
  const { parent: parent2 } = node;
  if (node.name && getFullWidth(node.name) > 0) {
    return cleanText(declarationNameToString(node.name));
  } else if (isVariableDeclaration(parent2)) {
    return cleanText(declarationNameToString(parent2.name));
  } else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */) {
    return nodeText(parent2.left).replace(whiteSpaceRegex, "");
  } else if (isPropertyAssignment(parent2)) {
    return nodeText(parent2.name);
  } else if (getSyntacticModifierFlags(node) & 1024 /* Default */) {
    return "default";
  } else if (isClassLike(node)) {
    return "<class>";
  } else if (isCallExpression(parent2)) {
    let name = getCalledExpressionName(parent2.expression);
    if (name !== void 0) {
      name = cleanText(name);
      if (name.length > maxLength) {
        return `${name} callback`;
      }
      const args = cleanText(mapDefined(parent2.arguments, (a) => isStringLiteralLike(a) ? a.getText(curSourceFile) : void 0).join(", "));
      return `${name}(${args}) callback`;
    }
  }
  return "<function>";
}
function getCalledExpressionName(expr) {
  if (isIdentifier(expr)) {
    return expr.text;
  } else if (isPropertyAccessExpression(expr)) {
    const left = getCalledExpressionName(expr.expression);
    const right = expr.name.text;
    return left === void 0 ? right : `${left}.${right}`;
  } else {
    return void 0;
  }
}
function isFunctionOrClassExpression(node) {
  switch (node.kind) {
    case 218 /* ArrowFunction */:
    case 217 /* FunctionExpression */:
    case 230 /* ClassExpression */:
      return true;
    default:
      return false;
  }
}
function cleanText(text) {
  text = text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
  return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, "");
}

// src/services/_namespaces/ts.refactor.ts
var ts_refactor_exports = {};
__export(ts_refactor_exports, {
  addExportToChanges: () => addExportToChanges,
  addExports: () => addExports,
  addNewFileToTsconfig: () => addNewFileToTsconfig,
  addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports,
  convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports,
  convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports,
  convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports,
  convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports,
  createNewFileName: () => createNewFileName,
  createOldFileImportsFromTargetFile: () => createOldFileImportsFromTargetFile,
  deleteMovedStatements: () => deleteMovedStatements,
  deleteUnusedImports: () => deleteUnusedImports,
  deleteUnusedOldImports: () => deleteUnusedOldImports,
  doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault,
  extractSymbol: () => ts_refactor_extractSymbol_exports,
  filterImport: () => filterImport,
  forEachImportInStatement: () => forEachImportInStatement,
  generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports,
  getApplicableRefactors: () => getApplicableRefactors,
  getEditsForRefactor: () => getEditsForRefactor,
  getStatementsToMove: () => getStatementsToMove,
  getTopLevelDeclarationStatement: () => getTopLevelDeclarationStatement,
  getUsageInfo: () => getUsageInfo,
  inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports,
  isRefactorErrorInfo: () => isRefactorErrorInfo,
  isTopLevelDeclaration: () => isTopLevelDeclaration,
  makeImportOrRequire: () => makeImportOrRequire,
  moduleSpecifierFromImport: () => moduleSpecifierFromImport,
  nameOfTopLevelDeclaration: () => nameOfTopLevelDeclaration,
  refactorKindBeginsWith: () => refactorKindBeginsWith,
  registerRefactor: () => registerRefactor,
  updateImportsInOtherFiles: () => updateImportsInOtherFiles
});

// src/services/refactorProvider.ts
var refactors = /* @__PURE__ */ new Map();
function registerRefactor(name, refactor) {
  refactors.set(name, refactor);
}
function getApplicableRefactors(context, includeInteractiveActions) {
  return arrayFrom(flatMapIterator(refactors.values(), (refactor) => {
    var _a;
    return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions);
  }));
}
function getEditsForRefactor(context, refactorName13, actionName2, interactiveRefactorArguments) {
  const refactor = refactors.get(refactorName13);
  return refactor && refactor.getEditsForAction(context, actionName2, interactiveRefactorArguments);
}

// src/services/refactors/convertExport.ts
var refactorName = "Convert export";
var defaultToNamedAction = {
  name: "Convert default export to named export",
  description: Diagnostics.Convert_default_export_to_named_export.message,
  kind: "refactor.rewrite.export.named"
};
var namedToDefaultAction = {
  name: "Convert named export to default export",
  description: Diagnostics.Convert_named_export_to_default_export.message,
  kind: "refactor.rewrite.export.default"
};
registerRefactor(refactorName, {
  kinds: [
    defaultToNamedAction.kind,
    namedToDefaultAction.kind
  ],
  getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) {
    const info = getInfo2(context, context.triggerReason === "invoked");
    if (!info)
      return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction;
      return [{ name: refactorName, description: action.description, actions: [action] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [
        { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [
          { ...defaultToNamedAction, notApplicableReason: info.error },
          { ...namedToDefaultAction, notApplicableReason: info.error }
        ] }
      ];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) {
    Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name");
    const info = getInfo2(context);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(context.file, context.program, info, t, context.cancellationToken));
    return { edits, renameFilename: void 0, renameLocation: void 0 };
  }
});
function getInfo2(context, considerPartialSpans = true) {
  const { file, program } = context;
  const span = getRefactorContextSpan(context);
  const token = getTokenAtPosition(file, span.start);
  const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span);
  if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) };
  }
  const checker = program.getTypeChecker();
  const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker);
  const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */);
  const wasDefault = !!(flags & 1024 /* Default */);
  if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
    return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) };
  }
  const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) };
  switch (exportNode.kind) {
    case 261 /* FunctionDeclaration */:
    case 262 /* ClassDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 265 /* EnumDeclaration */:
    case 264 /* TypeAliasDeclaration */:
    case 266 /* ModuleDeclaration */: {
      const node = exportNode;
      if (!node.name)
        return void 0;
      return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol };
    }
    case 242 /* VariableStatement */: {
      const vs = exportNode;
      if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
        return void 0;
      }
      const decl = first(vs.declarationList.declarations);
      if (!decl.initializer)
        return void 0;
      Debug.assert(!wasDefault, "Can't have a default flag here");
      return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol };
    }
    case 276 /* ExportAssignment */: {
      const node = exportNode;
      if (node.isExportEquals)
        return void 0;
      return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol };
    }
    default:
      return void 0;
  }
}
function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
  changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
  changeImports(program, info, changes, cancellationToken);
}
function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) {
  if (wasDefault) {
    if (isExportAssignment(exportNode) && !exportNode.isExportEquals) {
      const exp = exportNode.expression;
      const spec = makeExportSpecifier(exp.text, exp.text);
      changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        factory.createNamedExports([spec])
      ));
    } else {
      changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list"));
    }
  } else {
    const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list");
    switch (exportNode.kind) {
      case 261 /* FunctionDeclaration */:
      case 262 /* ClassDeclaration */:
      case 263 /* InterfaceDeclaration */:
        changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */));
        break;
      case 242 /* VariableStatement */:
        const decl = first(exportNode.declarationList.declarations);
        if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) {
          changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present")));
          break;
        }
      case 265 /* EnumDeclaration */:
      case 264 /* TypeAliasDeclaration */:
      case 266 /* ModuleDeclaration */:
        changes.deleteModifier(exportingSourceFile, exportKeyword);
        changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text)));
        break;
      default:
        Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`);
    }
  }
}
function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) {
  const checker = program.getTypeChecker();
  const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
  ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => {
    if (exportName === ref)
      return;
    const importingSourceFile = ref.getSourceFile();
    if (wasDefault) {
      changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
    } else {
      changeNamedToDefaultImport(importingSourceFile, ref, changes);
    }
  });
}
function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
  const { parent: parent2 } = ref;
  switch (parent2.kind) {
    case 210 /* PropertyAccessExpression */:
      changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName));
      break;
    case 275 /* ImportSpecifier */:
    case 280 /* ExportSpecifier */: {
      const spec = parent2;
      changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
      break;
    }
    case 272 /* ImportClause */: {
      const clause = parent2;
      Debug.assert(clause.name === ref, "Import clause name should match provided ref");
      const spec = makeImportSpecifier(exportName, ref.text);
      const { namedBindings } = clause;
      if (!namedBindings) {
        changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec]));
      } else if (namedBindings.kind === 273 /* NamespaceImport */) {
        changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
        const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
        const newImport = makeImport(
          /*defaultImport*/
          void 0,
          [makeImportSpecifier(exportName, ref.text)],
          clause.parent.moduleSpecifier,
          quotePreference
        );
        changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
      } else {
        changes.delete(importingSourceFile, ref);
        changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
      }
      break;
    }
    case 204 /* ImportType */:
      const importTypeNode = parent2;
      changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf));
      break;
    default:
      Debug.failBadSyntaxKind(parent2);
  }
}
function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
  const parent2 = ref.parent;
  switch (parent2.kind) {
    case 210 /* PropertyAccessExpression */:
      changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default"));
      break;
    case 275 /* ImportSpecifier */: {
      const defaultImport = factory.createIdentifier(parent2.name.text);
      if (parent2.parent.elements.length === 1) {
        changes.replaceNode(importingSourceFile, parent2.parent, defaultImport);
      } else {
        changes.delete(importingSourceFile, parent2);
        changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport);
      }
      break;
    }
    case 280 /* ExportSpecifier */: {
      changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text));
      break;
    }
    default:
      Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`);
  }
}
function makeImportSpecifier(propertyName, name) {
  return factory.createImportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName === name ? void 0 : factory.createIdentifier(propertyName),
    factory.createIdentifier(name)
  );
}
function makeExportSpecifier(propertyName, name) {
  return factory.createExportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName === name ? void 0 : factory.createIdentifier(propertyName),
    factory.createIdentifier(name)
  );
}
function getExportingModuleSymbol(parent2, checker) {
  if (isSourceFile(parent2)) {
    return parent2.symbol;
  }
  const symbol = parent2.parent.symbol;
  if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) {
    return checker.getMergedSymbol(symbol);
  }
  return symbol;
}

// src/services/refactors/convertImport.ts
var refactorName2 = "Convert import";
var actions = {
  [0 /* Named */]: {
    name: "Convert namespace import to named imports",
    description: Diagnostics.Convert_namespace_import_to_named_imports.message,
    kind: "refactor.rewrite.import.named"
  },
  [2 /* Namespace */]: {
    name: "Convert named imports to namespace import",
    description: Diagnostics.Convert_named_imports_to_namespace_import.message,
    kind: "refactor.rewrite.import.namespace"
  },
  [1 /* Default */]: {
    name: "Convert named imports to default import",
    description: Diagnostics.Convert_named_imports_to_default_import.message,
    kind: "refactor.rewrite.import.default"
  }
};
registerRefactor(refactorName2, {
  kinds: getOwnValues(actions).map((a) => a.kind),
  getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) {
    const info = getImportConversionInfo(context, context.triggerReason === "invoked");
    if (!info)
      return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      const action = actions[info.convertTo];
      return [{ name: refactorName2, description: action.description, actions: [action] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return getOwnValues(actions).map((action) => ({
        name: refactorName2,
        description: action.description,
        actions: [{ ...action, notApplicableReason: info.error }]
      }));
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) {
    Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name");
    const info = getImportConversionInfo(context);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(context.file, context.program, t, info));
    return { edits, renameFilename: void 0, renameLocation: void 0 };
  }
});
function getImportConversionInfo(context, considerPartialSpans = true) {
  const { file } = context;
  const span = getRefactorContextSpan(context);
  const token = getTokenAtPosition(file, span.start);
  const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span);
  if (!importDecl || !isImportDeclaration(importDecl))
    return { error: "Selection is not an import declaration." };
  const end = span.start + span.length;
  const nextToken = findNextToken(importDecl, importDecl.parent, file);
  if (nextToken && end > nextToken.getStart())
    return void 0;
  const { importClause } = importDecl;
  if (!importClause) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) };
  }
  if (!importClause.namedBindings) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) };
  }
  if (importClause.namedBindings.kind === 273 /* NamespaceImport */) {
    return { convertTo: 0 /* Named */, import: importClause.namedBindings };
  }
  const shouldUseDefault = getShouldUseDefault(context.program, importClause);
  return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings };
}
function getShouldUseDefault(program, importClause) {
  return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker());
}
function doChange2(sourceFile, program, changes, info) {
  const checker = program.getTypeChecker();
  if (info.convertTo === 0 /* Named */) {
    doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions()));
  } else {
    doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */);
  }
}
function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
  let usedAsNamespaceOrDefault = false;
  const nodesToReplace = [];
  const conflictingNames = /* @__PURE__ */ new Map();
  ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => {
    if (!isPropertyAccessOrQualifiedName(id.parent)) {
      usedAsNamespaceOrDefault = true;
    } else {
      const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text;
      if (checker.resolveName(
        exportName,
        id,
        67108863 /* All */,
        /*excludeGlobals*/
        true
      )) {
        conflictingNames.set(exportName, true);
      }
      Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id");
      nodesToReplace.push(id.parent);
    }
  });
  const exportNameToImportName = /* @__PURE__ */ new Map();
  for (const propertyAccessOrQualifiedName of nodesToReplace) {
    const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text;
    let importName = exportNameToImportName.get(exportName);
    if (importName === void 0) {
      exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName);
    }
    changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName));
  }
  const importSpecifiers = [];
  exportNameToImportName.forEach((name, propertyName) => {
    importSpecifiers.push(factory.createImportSpecifier(
      /*isTypeOnly*/
      false,
      name === propertyName ? void 0 : factory.createIdentifier(propertyName),
      factory.createIdentifier(name)
    ));
  });
  const importDecl = toConvert.parent.parent;
  if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
    changes.insertNodeAfter(sourceFile, importDecl, updateImport(
      importDecl,
      /*defaultImportName*/
      void 0,
      importSpecifiers
    ));
  } else {
    changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers));
  }
}
function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) {
  return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right;
}
function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) {
  return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left;
}
function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) {
  const checker = program.getTypeChecker();
  const importDecl = toConvert.parent.parent;
  const { moduleSpecifier } = importDecl;
  const toConvertSymbols = /* @__PURE__ */ new Set();
  toConvert.elements.forEach((namedImport) => {
    const symbol = checker.getSymbolAtLocation(namedImport.name);
    if (symbol) {
      toConvertSymbols.add(symbol);
    }
  });
  const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module";
  function hasNamespaceNameConflict(namedImport) {
    return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => {
      const symbol = checker.resolveName(
        preferredName,
        id,
        67108863 /* All */,
        /*excludeGlobals*/
        true
      );
      if (symbol) {
        if (toConvertSymbols.has(symbol)) {
          return isExportSpecifier(id.parent);
        }
        return true;
      }
      return false;
    });
  }
  const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict);
  const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName;
  const neededNamedImports = /* @__PURE__ */ new Set();
  for (const element of toConvert.elements) {
    const propertyName = (element.propertyName || element.name).text;
    ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => {
      const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName);
      if (isShorthandPropertyAssignment(id.parent)) {
        changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access));
      } else if (isExportSpecifier(id.parent)) {
        neededNamedImports.add(element);
      } else {
        changes.replaceNode(sourceFile, id, access);
      }
    });
  }
  changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName)));
  if (neededNamedImports.size) {
    const newNamedImports = arrayFrom(neededNamedImports.values(), (element) => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text)));
    changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(
      importDecl,
      /*defaultImportName*/
      void 0,
      newNamedImports
    ));
  }
}
function isExportEqualsModule(moduleSpecifier, checker) {
  const externalModule = checker.resolveExternalModuleName(moduleSpecifier);
  if (!externalModule)
    return false;
  const exportEquals = checker.resolveExternalModuleSymbol(externalModule);
  return externalModule !== exportEquals;
}
function updateImport(old, defaultImportName, elements) {
  return factory.createImportDeclaration(
    /*modifiers*/
    void 0,
    factory.createImportClause(
      /*isTypeOnly*/
      false,
      defaultImportName,
      elements && elements.length ? factory.createNamedImports(elements) : void 0
    ),
    old.moduleSpecifier,
    /*assertClause*/
    void 0
  );
}

// src/services/refactors/extractType.ts
var refactorName3 = "Extract type";
var extractToTypeAliasAction = {
  name: "Extract to type alias",
  description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias),
  kind: "refactor.extract.type"
};
var extractToInterfaceAction = {
  name: "Extract to interface",
  description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface),
  kind: "refactor.extract.interface"
};
var extractToTypeDefAction = {
  name: "Extract to typedef",
  description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef),
  kind: "refactor.extract.typedef"
};
registerRefactor(refactorName3, {
  kinds: [
    extractToTypeAliasAction.kind,
    extractToInterfaceAction.kind,
    extractToTypeDefAction.kind
  ],
  getAvailableActions: function getRefactorActionsToExtractType(context) {
    const info = getRangeToExtract(context, context.triggerReason === "invoked");
    if (!info)
      return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      return [{
        name: refactorName3,
        description: getLocaleSpecificMessage(Diagnostics.Extract_type),
        actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction)
      }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{
        name: refactorName3,
        description: getLocaleSpecificMessage(Diagnostics.Extract_type),
        actions: [
          { ...extractToTypeDefAction, notApplicableReason: info.error },
          { ...extractToTypeAliasAction, notApplicableReason: info.error },
          { ...extractToInterfaceAction, notApplicableReason: info.error }
        ]
      }];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) {
    const { file } = context;
    const info = getRangeToExtract(context);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract");
    const name = getUniqueName("NewType", file);
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      switch (actionName2) {
        case extractToTypeAliasAction.name:
          Debug.assert(!info.isJS, "Invalid actionName/JS combo");
          return doTypeAliasChange(changes, file, name, info);
        case extractToTypeDefAction.name:
          Debug.assert(info.isJS, "Invalid actionName/JS combo");
          return doTypedefChange(changes, context, file, name, info);
        case extractToInterfaceAction.name:
          Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo");
          return doInterfaceChange(changes, file, name, info);
        default:
          Debug.fail("Unexpected action name");
      }
    });
    const renameFilename = file.fileName;
    const renameLocation = getRenameLocation(
      edits,
      renameFilename,
      name,
      /*preferLastLocation*/
      false
    );
    return { edits, renameFilename, renameLocation };
  }
});
function getRangeToExtract(context, considerEmptySpans = true) {
  const { file, startPosition } = context;
  const isJS = isSourceFileJS(file);
  const current = getTokenAtPosition(file, startPosition);
  const range = createTextRangeFromSpan(getRefactorContextSpan(context));
  const cursorRequest = range.pos === range.end && considerEmptySpans;
  const selection = findAncestor(current, (node) => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || nodeOverlapsWithStartEnd(current, file, range.pos, range.end)));
  if (!selection || !isTypeNode(selection))
    return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) };
  const checker = context.program.getTypeChecker();
  const enclosingNode = getEnclosingNode(selection, isJS);
  if (enclosingNode === void 0)
    return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) };
  const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file);
  if (!typeParameters)
    return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) };
  const typeElements = flattenTypeLiteralNodeReference(checker, selection);
  return { isJS, selection, enclosingNode, typeParameters, typeElements };
}
function flattenTypeLiteralNodeReference(checker, node) {
  if (!node)
    return void 0;
  if (isIntersectionTypeNode(node)) {
    const result = [];
    const seen = /* @__PURE__ */ new Map();
    for (const type of node.types) {
      const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type);
      if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) {
        return void 0;
      }
      addRange(result, flattenedTypeMembers);
    }
    return result;
  } else if (isParenthesizedTypeNode(node)) {
    return flattenTypeLiteralNodeReference(checker, node.type);
  } else if (isTypeLiteralNode(node)) {
    return node.members;
  }
  return void 0;
}
function rangeContainsSkipTrivia(r1, node, file) {
  return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end);
}
function collectTypeParameters(checker, selection, enclosingNode, file) {
  const result = [];
  return visitor(selection) ? void 0 : result;
  function visitor(node) {
    if (isTypeReferenceNode(node)) {
      if (isIdentifier(node.typeName)) {
        const typeName = node.typeName;
        const symbol = checker.resolveName(
          typeName.text,
          typeName,
          262144 /* TypeParameter */,
          /*excludeGlobals*/
          true
        );
        for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) {
          if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) {
            if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) {
              return true;
            }
            if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) {
              pushIfUnique(result, decl);
              break;
            }
          }
        }
      }
    } else if (isInferTypeNode(node)) {
      const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file));
      if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) {
        return true;
      }
    } else if (isTypePredicateNode(node) || isThisTypeNode(node)) {
      const functionLikeNode = findAncestor(node.parent, isFunctionLike);
      if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) {
        return true;
      }
    } else if (isTypeQueryNode(node)) {
      if (isIdentifier(node.exprName)) {
        const symbol = checker.resolveName(
          node.exprName.text,
          node.exprName,
          111551 /* Value */,
          /*excludeGlobals*/
          false
        );
        if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) {
          return true;
        }
      } else {
        if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) {
          return true;
        }
      }
    }
    if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) {
      setEmitFlags(node, 1 /* SingleLine */);
    }
    return forEachChild(node, visitor);
  }
}
function doTypeAliasChange(changes, file, name, info) {
  const { enclosingNode, selection, typeParameters } = info;
  const newTypeNode = factory.createTypeAliasDeclaration(
    /*modifiers*/
    void 0,
    name,
    typeParameters.map((id) => factory.updateTypeParameterDeclaration(
      id,
      id.modifiers,
      id.name,
      id.constraint,
      /*defaultType*/
      void 0
    )),
    selection
  );
  changes.insertNodeBefore(
    file,
    enclosingNode,
    ignoreSourceNewlines(newTypeNode),
    /*blankLineBetween*/
    true
  );
  changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode(
    id.name,
    /*typeArguments*/
    void 0
  ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace });
}
function doInterfaceChange(changes, file, name, info) {
  var _a;
  const { enclosingNode, selection, typeParameters, typeElements } = info;
  const newTypeNode = factory.createInterfaceDeclaration(
    /*modifiers*/
    void 0,
    name,
    typeParameters,
    /*heritageClauses*/
    void 0,
    typeElements
  );
  setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent);
  changes.insertNodeBefore(
    file,
    enclosingNode,
    ignoreSourceNewlines(newTypeNode),
    /*blankLineBetween*/
    true
  );
  changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode(
    id.name,
    /*typeArguments*/
    void 0
  ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace });
}
function doTypedefChange(changes, context, file, name, info) {
  var _a;
  const { enclosingNode, selection, typeParameters } = info;
  setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */);
  const node = factory.createJSDocTypedefTag(
    factory.createIdentifier("typedef"),
    factory.createJSDocTypeExpression(selection),
    factory.createIdentifier(name)
  );
  const templates = [];
  forEach(typeParameters, (typeParameter) => {
    const constraint = getEffectiveConstraintOfTypeParameter(typeParameter);
    const parameter = factory.createTypeParameterDeclaration(
      /*modifiers*/
      void 0,
      typeParameter.name
    );
    const template = factory.createJSDocTemplateTag(
      factory.createIdentifier("template"),
      constraint && cast(constraint, isJSDocTypeExpression),
      [parameter]
    );
    templates.push(template);
  });
  const jsDoc = factory.createJSDocComment(
    /*comment*/
    void 0,
    factory.createNodeArray(concatenate(templates, [node]))
  );
  if (isJSDoc(enclosingNode)) {
    const pos = enclosingNode.getStart(file);
    const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options);
    changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, {
      suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos)
    });
  } else {
    changes.insertNodeBefore(
      file,
      enclosingNode,
      jsDoc,
      /*blankLineBetween*/
      true
    );
  }
  changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode(
    id.name,
    /*typeArguments*/
    void 0
  ))));
}
function getEnclosingNode(node, isJS) {
  return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0);
}

// src/services/refactors/helpers.ts
function isRefactorErrorInfo(info) {
  return info.error !== void 0;
}
function refactorKindBeginsWith(known, requested) {
  if (!requested)
    return true;
  return known.substr(0, requested.length) === requested;
}

// src/services/refactors/moveToNewFile.ts
var refactorName4 = "Move to a new file";
var description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file);
var moveToNewFileAction = {
  name: refactorName4,
  description,
  kind: "refactor.move.newFile"
};
registerRefactor(refactorName4, {
  kinds: [moveToNewFileAction.kind],
  getAvailableActions: function getRefactorActionsToMoveToNewFile(context) {
    const statements = getStatementsToMove(context);
    if (context.preferences.allowTextChangesInNewFiles && statements) {
      return [{ name: refactorName4, description, actions: [moveToNewFileAction] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{
        name: refactorName4,
        description,
        actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }]
      }];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) {
    Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked");
    const statements = Debug.checkDefined(getStatementsToMove(context));
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context.file, context.program, statements, t, context.host, context.preferences, context));
    return { edits, renameFilename: void 0, renameLocation: void 0 };
  }
});
function doChange3(oldFile, program, toMove, changes, host, preferences, context) {
  const checker = program.getTypeChecker();
  const usage = getUsageInfo(oldFile, toMove.all, checker);
  const newFilename = createNewFileName(oldFile, program, context, host);
  changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences));
  addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host));
}
function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) {
  const checker = program.getTypeChecker();
  const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective);
  if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0) {
    deleteMovedStatements(oldFile, toMove.ranges, changes);
    return [...prologueDirectives, ...toMove.all];
  }
  const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(newFilename, program, host, !!oldFile.commonJsModuleIndicator);
  const quotePreference = getQuotePreference(oldFile, preferences);
  const importsFromNewFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, newFilename, program, host, useEsModuleSyntax, quotePreference);
  if (importsFromNewFile) {
    insertImports(
      changes,
      oldFile,
      importsFromNewFile,
      /*blankLineBetween*/
      true,
      preferences
    );
  }
  deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
  deleteMovedStatements(oldFile, toMove.ranges, changes);
  updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference);
  const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference);
  const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax);
  if (imports.length && body.length) {
    return [
      ...prologueDirectives,
      ...imports,
      4 /* NewLineTrivia */,
      ...body
    ];
  }
  return [
    ...prologueDirectives,
    ...imports,
    ...body
  ];
}
function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) {
  const copiedOldImports = [];
  for (const oldStatement of oldFile.statements) {
    forEachImportInStatement(oldStatement, (i) => {
      append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name))));
    });
  }
  let oldFileDefault;
  const oldFileNamedImports = [];
  const markSeenTop = nodeSeenTracker();
  newFileImportsFromOldFile.forEach((symbol) => {
    if (!symbol.declarations) {
      return;
    }
    for (const decl of symbol.declarations) {
      if (!isTopLevelDeclaration(decl))
        continue;
      const name = nameOfTopLevelDeclaration(decl);
      if (!name)
        continue;
      const top = getTopLevelDeclarationStatement(decl);
      if (markSeenTop(top)) {
        addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax);
      }
      if (hasSyntacticModifier(decl, 1024 /* Default */)) {
        oldFileDefault = name;
      } else {
        oldFileNamedImports.push(name.text);
      }
    }
  });
  append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference));
  return copiedOldImports;
}

// src/services/refactors/moveToFile.ts
var refactorNameForMoveToFile = "Move to file";
var description2 = getLocaleSpecificMessage(Diagnostics.Move_to_file);
var moveToFileAction = {
  name: "Move to file",
  description: description2,
  kind: "refactor.move.file"
};
registerRefactor(refactorNameForMoveToFile, {
  kinds: [moveToFileAction.kind],
  getAvailableActions: function getRefactorActionsToMoveToFile(context, interactiveRefactorArguments) {
    const statements = getStatementsToMove(context);
    if (!interactiveRefactorArguments) {
      return emptyArray;
    }
    if (context.preferences.allowTextChangesInNewFiles && statements) {
      return [{ name: refactorNameForMoveToFile, description: description2, actions: [moveToFileAction] }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{
        name: refactorNameForMoveToFile,
        description: description2,
        actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }]
      }];
    }
    return emptyArray;
  },
  getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) {
    Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked");
    const statements = Debug.checkDefined(getStatementsToMove(context));
    Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available");
    const targetFile = interactiveRefactorArguments.targetFile;
    if (hasJSFileExtension(targetFile) || hasTSFileExtension(targetFile)) {
      const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences));
      return { edits, renameFilename: void 0, renameLocation: void 0 };
    }
    return { edits: [], renameFilename: void 0, renameLocation: void 0, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid) };
  }
});
function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) {
  const checker = program.getTypeChecker();
  const usage = getUsageInfo(oldFile, toMove.all, checker);
  if (!host.fileExists(targetFile)) {
    changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences));
    addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host));
  } else {
    const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile));
    const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host);
    getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, usage, changes, toMove, program, host, preferences, importAdder);
  }
}
function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) {
  const checker = program.getTypeChecker();
  const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective);
  if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0 && usage.targetFileImportsFromOldFile.size === 0 && typeof targetFile === "string") {
    deleteMovedStatements(oldFile, toMove.ranges, changes);
    return [...prologueDirectives, ...toMove.all];
  }
  const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName;
  const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator);
  const quotePreference = getQuotePreference(oldFile, preferences);
  const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference);
  if (importsFromTargetFile) {
    insertImports(
      changes,
      oldFile,
      importsFromTargetFile,
      /*blankLineBetween*/
      true,
      preferences
    );
  }
  deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
  deleteMovedStatements(oldFile, toMove.ranges, changes);
  updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFileName, quotePreference);
  const imports = getTargetFileImportsAndAddExportInOldFile(oldFile, targetFileName, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder);
  const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax);
  if (typeof targetFile !== "string") {
    if (targetFile.statements.length > 0) {
      changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body);
    } else {
      changes.insertNodesAtEndOfFile(
        targetFile,
        body,
        /*blankLineBetween*/
        false
      );
    }
    if (imports.length > 0) {
      insertImports(
        changes,
        targetFile,
        imports,
        /*blankLineBetween*/
        true,
        preferences
      );
    }
  }
  if (importAdder) {
    importAdder.writeFixes(changes);
  }
  if (imports.length && body.length) {
    return [
      ...prologueDirectives,
      ...imports,
      4 /* NewLineTrivia */,
      ...body
    ];
  }
  return [
    ...prologueDirectives,
    ...imports,
    ...body
  ];
}
function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) {
  const copiedOldImports = [];
  if (importAdder) {
    importsToCopy.forEach((isValidTypeOnlyUseSite, symbol) => {
      try {
        importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker), isValidTypeOnlyUseSite);
      } catch {
        for (const oldStatement of oldFile.statements) {
          forEachImportInStatement(oldStatement, (i) => {
            append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name))));
          });
        }
      }
    });
  } else {
    const targetSourceFile = program.getSourceFile(targetFile);
    for (const oldStatement of oldFile.statements) {
      forEachImportInStatement(oldStatement, (i) => {
        var _a, _b;
        const moduleSpecifier = moduleSpecifierFromImport(i);
        const resolved = (_a = oldFile.resolvedModules) == null ? void 0 : _a.get(moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier));
        const fileName = (_b = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _b.resolvedFileName;
        if (fileName && targetSourceFile) {
          const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host));
          append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name))));
        } else {
          append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name))));
        }
      });
    }
  }
  const targetFileSourceFile = program.getSourceFile(targetFile);
  let oldFileDefault;
  const oldFileNamedImports = [];
  const markSeenTop = nodeSeenTracker();
  targetFileImportsFromOldFile.forEach((symbol) => {
    if (!symbol.declarations) {
      return;
    }
    for (const decl of symbol.declarations) {
      if (!isTopLevelDeclaration(decl))
        continue;
      const name = nameOfTopLevelDeclaration(decl);
      if (!name)
        continue;
      const top = getTopLevelDeclarationStatement(decl);
      if (markSeenTop(top)) {
        addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax);
      }
      if (importAdder && checker.isUnknownSymbol(symbol)) {
        importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker));
      } else {
        if (hasSyntacticModifier(decl, 1024 /* Default */)) {
          oldFileDefault = name;
        } else {
          oldFileNamedImports.push(name.text);
        }
      }
    }
  });
  return targetFileSourceFile ? append(copiedOldImports, makeImportOrRequire(targetFileSourceFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)) : append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference));
}
function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
  const cfg = program.getCompilerOptions().configFile;
  if (!cfg)
    return;
  const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension));
  const newFilePath = getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
  const cfgObject = cfg.statements[0] && tryCast(cfg.statements[0].expression, isObjectLiteralExpression);
  const filesProp = cfgObject && find(cfgObject.properties, (prop) => isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files");
  if (filesProp && isArrayLiteralExpression(filesProp.initializer)) {
    changes.insertNodeInListAfter(cfg, last(filesProp.initializer.elements), factory.createStringLiteral(newFilePath), filesProp.initializer.elements);
  }
}
function deleteMovedStatements(sourceFile, moved, changes) {
  for (const { first: first2, afterLast } of moved) {
    changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast);
  }
}
function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
  for (const statement of oldFile.statements) {
    if (contains(toMove, statement))
      continue;
    forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name))));
  }
}
function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) {
  const checker = program.getTypeChecker();
  for (const sourceFile of program.getSourceFiles()) {
    if (sourceFile === oldFile)
      continue;
    for (const statement of sourceFile.statements) {
      forEachImportInStatement(statement, (importNode) => {
        if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
          return;
        const shouldMove = (name) => {
          const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker);
          return !!symbol && movedSymbols.has(symbol);
        };
        deleteUnusedImports(sourceFile, importNode, changes, shouldMove);
        const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), targetFileName);
        const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host));
        const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove);
        if (newImportDeclaration)
          changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
        const ns = getNamespaceLikeImport(importNode);
        if (ns)
          updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference);
      });
    }
  }
}
function getNamespaceLikeImport(node) {
  switch (node.kind) {
    case 271 /* ImportDeclaration */:
      return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0;
    case 270 /* ImportEqualsDeclaration */:
      return node.name;
    case 259 /* VariableDeclaration */:
      return tryCast(node.name, isIdentifier);
    default:
      return Debug.assertNever(node, `Unexpected node kind ${node.kind}`);
  }
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) {
  const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */);
  let needUniqueName = false;
  const toChange = [];
  ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => {
    if (!isPropertyAccessExpression(ref.parent))
      return;
    needUniqueName = needUniqueName || !!checker.resolveName(
      preferredNewNamespaceName,
      ref,
      67108863 /* All */,
      /*excludeGlobals*/
      true
    );
    if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) {
      toChange.push(ref);
    }
  });
  if (toChange.length) {
    const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName;
    for (const ref of toChange) {
      changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName));
    }
    changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference));
  }
}
function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) {
  const newNamespaceId = factory.createIdentifier(newNamespaceName);
  const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference);
  switch (node.kind) {
    case 271 /* ImportDeclaration */:
      return factory.createImportDeclaration(
        /*modifiers*/
        void 0,
        factory.createImportClause(
          /*isTypeOnly*/
          false,
          /*name*/
          void 0,
          factory.createNamespaceImport(newNamespaceId)
        ),
        newModuleString,
        /*assertClause*/
        void 0
      );
    case 270 /* ImportEqualsDeclaration */:
      return factory.createImportEqualsDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        newNamespaceId,
        factory.createExternalModuleReference(newModuleString)
      );
    case 259 /* VariableDeclaration */:
      return factory.createVariableDeclaration(
        newNamespaceId,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        createRequireCall(newModuleString)
      );
    default:
      return Debug.assertNever(node, `Unexpected node kind ${node.kind}`);
  }
}
function createRequireCall(moduleSpecifier) {
  return factory.createCallExpression(
    factory.createIdentifier("require"),
    /*typeArguments*/
    void 0,
    [moduleSpecifier]
  );
}
function moduleSpecifierFromImport(i) {
  return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0];
}
function forEachImportInStatement(statement, cb) {
  if (isImportDeclaration(statement)) {
    if (isStringLiteral(statement.moduleSpecifier))
      cb(statement);
  } else if (isImportEqualsDeclaration(statement)) {
    if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) {
      cb(statement);
    }
  } else if (isVariableStatement(statement)) {
    for (const decl of statement.declarationList.declarations) {
      if (decl.initializer && isRequireCall(
        decl.initializer,
        /*requireStringLiteralLikeArgument*/
        true
      )) {
        cb(decl);
      }
    }
  }
}
function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) {
  let defaultImport;
  const imports = [];
  targetFileNeedExport.forEach((symbol) => {
    if (symbol.escapedName === "default" /* Default */) {
      defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol));
    } else {
      imports.push(symbol.name);
    }
  });
  return makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference);
}
function makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) {
  const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension);
  const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host));
  if (useEs6Imports) {
    const specifiers = imports.map((i) => factory.createImportSpecifier(
      /*isTypeOnly*/
      false,
      /*propertyName*/
      void 0,
      factory.createIdentifier(i)
    ));
    return makeImportIfNecessary(defaultImport, specifiers, pathToTargetFileWithCorrectExtension, quotePreference);
  } else {
    Debug.assert(!defaultImport, "No default import should exist");
    const bindingElements = imports.map((i) => factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      /*propertyName*/
      void 0,
      i
    ));
    return bindingElements.length ? makeVariableStatement(
      factory.createObjectBindingPattern(bindingElements),
      /*type*/
      void 0,
      createRequireCall(makeStringLiteral(pathToTargetFileWithCorrectExtension, quotePreference))
    ) : void 0;
  }
}
function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) {
  return factory.createVariableStatement(
    /*modifiers*/
    void 0,
    factory.createVariableDeclarationList([factory.createVariableDeclaration(
      name,
      /*exclamationToken*/
      void 0,
      type,
      initializer
    )], flags)
  );
}
function addExports(sourceFile, toMove, needExport, useEs6Exports) {
  return flatMap(toMove, (statement) => {
    if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => {
      var _a;
      return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol));
    })) {
      const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports);
      if (exports)
        return exports;
    }
    return getSynthesizedDeepClone(statement);
  });
}
function isExported(sourceFile, decl, useEs6Exports, name) {
  var _a;
  if (useEs6Exports) {
    return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText)));
  }
  return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2)));
}
function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
  switch (importDecl.kind) {
    case 271 /* ImportDeclaration */:
      deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
      break;
    case 270 /* ImportEqualsDeclaration */:
      if (isUnused(importDecl.name)) {
        changes.delete(sourceFile, importDecl);
      }
      break;
    case 259 /* VariableDeclaration */:
      deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
      break;
    default:
      Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`);
  }
}
function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
  if (!importDecl.importClause)
    return;
  const { name, namedBindings } = importDecl.importClause;
  const defaultUnused = !name || isUnused(name);
  const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name)));
  if (defaultUnused && namedBindingsUnused) {
    changes.delete(sourceFile, importDecl);
  } else {
    if (name && defaultUnused) {
      changes.delete(sourceFile, name);
    }
    if (namedBindings) {
      if (namedBindingsUnused) {
        changes.replaceNode(
          sourceFile,
          importDecl.importClause,
          factory.updateImportClause(
            importDecl.importClause,
            importDecl.importClause.isTypeOnly,
            name,
            /*namedBindings*/
            void 0
          )
        );
      } else if (namedBindings.kind === 274 /* NamedImports */) {
        for (const element of namedBindings.elements) {
          if (isUnused(element.name))
            changes.delete(sourceFile, element);
        }
      }
    }
  }
}
function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
  const { name } = varDecl;
  switch (name.kind) {
    case 80 /* Identifier */:
      if (isUnused(name)) {
        if (varDecl.initializer && isRequireCall(
          varDecl.initializer,
          /*requireStringLiteralLikeArgument*/
          true
        )) {
          changes.delete(
            sourceFile,
            isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl
          );
        } else {
          changes.delete(sourceFile, name);
        }
      }
      break;
    case 206 /* ArrayBindingPattern */:
      break;
    case 205 /* ObjectBindingPattern */:
      if (name.elements.every((e) => isIdentifier(e.name) && isUnused(e.name))) {
        changes.delete(
          sourceFile,
          isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl
        );
      } else {
        for (const element of name.elements) {
          if (isIdentifier(element.name) && isUnused(element.name)) {
            changes.delete(sourceFile, element.name);
          }
        }
      }
      break;
  }
}
function isTopLevelDeclarationStatement(node) {
  Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile");
  return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node);
}
function addExport(decl, useEs6Exports) {
  return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
}
function addEs6Export(d) {
  const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0;
  switch (d.kind) {
    case 261 /* FunctionDeclaration */:
      return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
    case 262 /* ClassDeclaration */:
      const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0;
      return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members);
    case 242 /* VariableStatement */:
      return factory.updateVariableStatement(d, modifiers, d.declarationList);
    case 266 /* ModuleDeclaration */:
      return factory.updateModuleDeclaration(d, modifiers, d.name, d.body);
    case 265 /* EnumDeclaration */:
      return factory.updateEnumDeclaration(d, modifiers, d.name, d.members);
    case 264 /* TypeAliasDeclaration */:
      return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type);
    case 263 /* InterfaceDeclaration */:
      return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
    case 270 /* ImportEqualsDeclaration */:
      return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference);
    case 243 /* ExpressionStatement */:
      return Debug.fail();
    default:
      return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`);
  }
}
function addCommonjsExport(decl) {
  return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)];
}
function createExportAssignment(name) {
  return factory.createExpressionStatement(
    factory.createBinaryExpression(
      factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)),
      64 /* EqualsToken */,
      factory.createIdentifier(name)
    )
  );
}
function getNamesToExportInCommonJS(decl) {
  switch (decl.kind) {
    case 261 /* FunctionDeclaration */:
    case 262 /* ClassDeclaration */:
      return [decl.name.text];
    case 242 /* VariableStatement */:
      return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0);
    case 266 /* ModuleDeclaration */:
    case 265 /* EnumDeclaration */:
    case 264 /* TypeAliasDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 270 /* ImportEqualsDeclaration */:
      return emptyArray;
    case 243 /* ExpressionStatement */:
      return Debug.fail("Can't export an ExpressionStatement");
    default:
      return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`);
  }
}
function filterImport(i, moduleSpecifier, keep) {
  switch (i.kind) {
    case 271 /* ImportDeclaration */: {
      const clause = i.importClause;
      if (!clause)
        return void 0;
      const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0;
      const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
      return defaultImport || namedBindings ? factory.createImportDeclaration(
        /*modifiers*/
        void 0,
        factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings),
        getSynthesizedDeepClone(moduleSpecifier),
        /*assertClause*/
        void 0
      ) : void 0;
    }
    case 270 /* ImportEqualsDeclaration */:
      return keep(i.name) ? i : void 0;
    case 259 /* VariableDeclaration */: {
      const name = filterBindingName(i.name, keep);
      return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0;
    }
    default:
      return Debug.assertNever(i, `Unexpected import kind ${i.kind}`);
  }
}
function filterNamedBindings(namedBindings, keep) {
  if (namedBindings.kind === 273 /* NamespaceImport */) {
    return keep(namedBindings.name) ? namedBindings : void 0;
  } else {
    const newElements = namedBindings.elements.filter((e) => keep(e.name));
    return newElements.length ? factory.createNamedImports(newElements) : void 0;
  }
}
function filterBindingName(name, keep) {
  switch (name.kind) {
    case 80 /* Identifier */:
      return keep(name) ? name : void 0;
    case 206 /* ArrayBindingPattern */:
      return name;
    case 205 /* ObjectBindingPattern */: {
      const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name));
      return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0;
    }
  }
}
function nameOfTopLevelDeclaration(d) {
  return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier);
}
function getTopLevelDeclarationStatement(d) {
  switch (d.kind) {
    case 259 /* VariableDeclaration */:
      return d.parent.parent;
    case 207 /* BindingElement */:
      return getTopLevelDeclarationStatement(
        cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p))
      );
    default:
      return d;
  }
}
function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) {
  if (isExported(sourceFile, decl, useEs6Exports, name))
    return;
  if (useEs6Exports) {
    if (!isExpressionStatement(decl))
      changes.insertExportModifier(sourceFile, decl);
  } else {
    const names = getNamesToExportInCommonJS(decl);
    if (names.length !== 0)
      changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
  }
}
function createNewFileName(oldFile, program, context, host) {
  const checker = program.getTypeChecker();
  const toMove = getStatementsToMove(context);
  let usage;
  if (toMove) {
    usage = getUsageInfo(oldFile, toMove.all, checker);
    const currentDirectory = getDirectoryPath(oldFile.fileName);
    const extension = extensionFromPath(oldFile.fileName);
    const newFileName = combinePaths(
      // new file is always placed in the same directory as the old file
      currentDirectory,
      // ensures the filename computed below isn't already taken
      makeUniqueFilename(
        // infers a name for the new file from the symbols being moved
        inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols),
        extension,
        currentDirectory,
        host
      )
    ) + extension;
    return newFileName;
  }
  return "";
}
function getRangeToMove(context) {
  const { file } = context;
  const range = createTextRangeFromSpan(getRefactorContextSpan(context));
  const { statements } = file;
  const startNodeIndex = findIndex(statements, (s) => s.end > range.pos);
  if (startNodeIndex === -1)
    return void 0;
  const startStatement = statements[startNodeIndex];
  if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) {
    return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] };
  }
  if (range.pos > startStatement.getStart(file))
    return void 0;
  const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex);
  if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
    return void 0;
  return {
    toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex),
    afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex]
  };
}
function getStatementsToMove(context) {
  const rangeToMove = getRangeToMove(context);
  if (rangeToMove === void 0)
    return void 0;
  const all = [];
  const ranges = [];
  const { toMove, afterLast } = rangeToMove;
  getRangesWhere(toMove, isAllowedStatementToMove, (start2, afterEndIndex) => {
    for (let i = start2; i < afterEndIndex; i++)
      all.push(toMove[i]);
    ranges.push({ first: toMove[start2], afterLast });
  });
  return all.length === 0 ? void 0 : { all, ranges };
}
function isAllowedStatementToMove(statement) {
  return !isPureImport(statement) && !isPrologueDirective(statement);
}
function isPureImport(node) {
  switch (node.kind) {
    case 271 /* ImportDeclaration */:
      return true;
    case 270 /* ImportEqualsDeclaration */:
      return !hasSyntacticModifier(node, 1 /* Export */);
    case 242 /* VariableStatement */:
      return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall(
        d.initializer,
        /*requireStringLiteralLikeArgument*/
        true
      ));
    default:
      return false;
  }
}
function getUsageInfo(oldFile, toMove, checker) {
  const movedSymbols = /* @__PURE__ */ new Set();
  const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map();
  const targetFileImportsFromOldFile = /* @__PURE__ */ new Set();
  const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */));
  const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
  if (jsxNamespaceSymbol) {
    oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false);
  }
  for (const statement of toMove) {
    forEachTopLevelDeclaration(statement, (decl) => {
      movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
    });
  }
  for (const statement of toMove) {
    forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => {
      if (!symbol.declarations)
        return;
      for (const decl of symbol.declarations) {
        if (isInImport(decl)) {
          const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol);
          oldImportsNeededByTargetFile.set(symbol, prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite);
        } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) {
          targetFileImportsFromOldFile.add(symbol);
        }
      }
    });
  }
  const unusedImportsFromOldFile = new Set(oldImportsNeededByTargetFile.keys());
  const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set();
  for (const statement of oldFile.statements) {
    if (contains(toMove, statement))
      continue;
    if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
      unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
    }
    forEachReference(statement, checker, (symbol) => {
      if (movedSymbols.has(symbol))
        oldFileImportsFromTargetFile.add(symbol);
      unusedImportsFromOldFile.delete(symbol);
    });
  }
  return { movedSymbols, targetFileImportsFromOldFile, oldFileImportsFromTargetFile, oldImportsNeededByTargetFile, unusedImportsFromOldFile };
  function getJsxNamespaceSymbol(containsJsx2) {
    if (containsJsx2 === void 0) {
      return void 0;
    }
    const jsxNamespace = checker.getJsxNamespace(containsJsx2);
    const jsxNamespaceSymbol2 = checker.resolveName(
      jsxNamespace,
      containsJsx2,
      1920 /* Namespace */,
      /*excludeGlobals*/
      true
    );
    return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0;
  }
}
function makeUniqueFilename(proposedFilename, extension, inDirectory, host) {
  let newFilename = proposedFilename;
  for (let i = 1; ; i++) {
    const name = combinePaths(inDirectory, newFilename + extension);
    if (!host.fileExists(name))
      return newFilename;
    newFilename = `${proposedFilename}.${i}`;
  }
}
function inferNewFileName(importsFromNewFile, movedSymbols) {
  return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile";
}
function forEachReference(node, checker, onReference) {
  node.forEachChild(function cb(node2) {
    if (isIdentifier(node2) && !isDeclarationName(node2)) {
      const sym = checker.getSymbolAtLocation(node2);
      if (sym)
        onReference(sym, isValidTypeOnlyAliasUseSite(node2));
    } else {
      node2.forEachChild(cb);
    }
  });
}
function forEachTopLevelDeclaration(statement, cb) {
  switch (statement.kind) {
    case 261 /* FunctionDeclaration */:
    case 262 /* ClassDeclaration */:
    case 266 /* ModuleDeclaration */:
    case 265 /* EnumDeclaration */:
    case 264 /* TypeAliasDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 270 /* ImportEqualsDeclaration */:
      return cb(statement);
    case 242 /* VariableStatement */:
      return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb));
    case 243 /* ExpressionStatement */: {
      const { expression } = statement;
      return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0;
    }
  }
}
function isInImport(decl) {
  switch (decl.kind) {
    case 270 /* ImportEqualsDeclaration */:
    case 275 /* ImportSpecifier */:
    case 272 /* ImportClause */:
    case 273 /* NamespaceImport */:
      return true;
    case 259 /* VariableDeclaration */:
      return isVariableDeclarationInImport(decl);
    case 207 /* BindingElement */:
      return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
    default:
      return false;
  }
}
function isVariableDeclarationInImport(decl) {
  return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall(
    decl.initializer,
    /*requireStringLiteralLikeArgument*/
    true
  );
}
function isTopLevelDeclaration(node) {
  return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent);
}
function sourceFileOfTopLevelDeclaration(node) {
  return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent;
}
function forEachTopLevelDeclarationInBindingName(name, cb) {
  switch (name.kind) {
    case 80 /* Identifier */:
      return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x)));
    case 206 /* ArrayBindingPattern */:
    case 205 /* ObjectBindingPattern */:
      return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb));
    default:
      return Debug.assertNever(name, `Unexpected name kind ${name.kind}`);
  }
}
function isNonVariableTopLevelDeclaration(node) {
  switch (node.kind) {
    case 261 /* FunctionDeclaration */:
    case 262 /* ClassDeclaration */:
    case 266 /* ModuleDeclaration */:
    case 265 /* EnumDeclaration */:
    case 264 /* TypeAliasDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 270 /* ImportEqualsDeclaration */:
      return true;
    default:
      return false;
  }
}

// src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts
var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {};

// src/services/refactors/convertOverloadListToSingleSignature.ts
var refactorName5 = "Convert overload list to single signature";
var refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message;
var functionOverloadAction = {
  name: refactorName5,
  description: refactorDescription,
  kind: "refactor.rewrite.function.overloadList"
};
registerRefactor(refactorName5, {
  kinds: [functionOverloadAction.kind],
  getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature,
  getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature
});
function getRefactorActionsToConvertOverloadsToOneSignature(context) {
  const { file, startPosition, program } = context;
  const info = getConvertableOverloadListAtPosition(file, startPosition, program);
  if (!info)
    return emptyArray;
  return [{
    name: refactorName5,
    description: refactorDescription,
    actions: [functionOverloadAction]
  }];
}
function getRefactorEditsToConvertOverloadsToOneSignature(context) {
  const { file, startPosition, program } = context;
  const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program);
  if (!signatureDecls)
    return void 0;
  const checker = program.getTypeChecker();
  const lastDeclaration = signatureDecls[signatureDecls.length - 1];
  let updated = lastDeclaration;
  switch (lastDeclaration.kind) {
    case 172 /* MethodSignature */: {
      updated = factory.updateMethodSignature(
        lastDeclaration,
        lastDeclaration.modifiers,
        lastDeclaration.name,
        lastDeclaration.questionToken,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type
      );
      break;
    }
    case 173 /* MethodDeclaration */: {
      updated = factory.updateMethodDeclaration(
        lastDeclaration,
        lastDeclaration.modifiers,
        lastDeclaration.asteriskToken,
        lastDeclaration.name,
        lastDeclaration.questionToken,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type,
        lastDeclaration.body
      );
      break;
    }
    case 178 /* CallSignature */: {
      updated = factory.updateCallSignature(
        lastDeclaration,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type
      );
      break;
    }
    case 175 /* Constructor */: {
      updated = factory.updateConstructorDeclaration(
        lastDeclaration,
        lastDeclaration.modifiers,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.body
      );
      break;
    }
    case 179 /* ConstructSignature */: {
      updated = factory.updateConstructSignature(
        lastDeclaration,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type
      );
      break;
    }
    case 261 /* FunctionDeclaration */: {
      updated = factory.updateFunctionDeclaration(
        lastDeclaration,
        lastDeclaration.modifiers,
        lastDeclaration.asteriskToken,
        lastDeclaration.name,
        lastDeclaration.typeParameters,
        getNewParametersForCombinedSignature(signatureDecls),
        lastDeclaration.type,
        lastDeclaration.body
      );
      break;
    }
    default:
      return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring");
  }
  if (updated === lastDeclaration) {
    return;
  }
  const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
    t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated);
  });
  return { renameFilename: void 0, renameLocation: void 0, edits };
  function getNewParametersForCombinedSignature(signatureDeclarations) {
    const lastSig = signatureDeclarations[signatureDeclarations.length - 1];
    if (isFunctionLikeDeclaration(lastSig) && lastSig.body) {
      signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1);
    }
    return factory.createNodeArray([
      factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        factory.createToken(26 /* DotDotDotToken */),
        "args",
        /*questionToken*/
        void 0,
        factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple))
      )
    ]);
  }
  function convertSignatureParametersToTuple(decl) {
    const members = map(decl.parameters, convertParameterToNamedTupleMember);
    return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */);
  }
  function convertParameterToNamedTupleMember(p) {
    Debug.assert(isIdentifier(p.name));
    const result = setTextRange(factory.createNamedTupleMember(
      p.dotDotDotToken,
      p.name,
      p.questionToken,
      p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */)
    ), p);
    const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker);
    if (parameterDocComment) {
      const newComment = displayPartsToString(parameterDocComment);
      if (newComment.length) {
        setSyntheticLeadingComments(result, [{
          text: `*
${newComment.split("\n").map((c) => ` * ${c}`).join("\n")}
 `,
          kind: 3 /* MultiLineCommentTrivia */,
          pos: -1,
          end: -1,
          hasTrailingNewLine: true,
          hasLeadingNewline: true
        }]);
      }
    }
    return result;
  }
}
function isConvertableSignatureDeclaration(d) {
  switch (d.kind) {
    case 172 /* MethodSignature */:
    case 173 /* MethodDeclaration */:
    case 178 /* CallSignature */:
    case 175 /* Constructor */:
    case 179 /* ConstructSignature */:
    case 261 /* FunctionDeclaration */:
      return true;
  }
  return false;
}
function getConvertableOverloadListAtPosition(file, startPosition, program) {
  const node = getTokenAtPosition(file, startPosition);
  const containingDecl = findAncestor(node, isConvertableSignatureDeclaration);
  if (!containingDecl) {
    return;
  }
  if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) {
    return;
  }
  const checker = program.getTypeChecker();
  const signatureSymbol = containingDecl.symbol;
  if (!signatureSymbol) {
    return;
  }
  const decls = signatureSymbol.declarations;
  if (length(decls) <= 1) {
    return;
  }
  if (!every(decls, (d) => getSourceFileOfNode(d) === file)) {
    return;
  }
  if (!isConvertableSignatureDeclaration(decls[0])) {
    return;
  }
  const kindOne = decls[0].kind;
  if (!every(decls, (d) => d.kind === kindOne)) {
    return;
  }
  const signatureDecls = decls;
  if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) {
    return;
  }
  const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d));
  if (length(signatures) !== length(decls)) {
    return;
  }
  const returnOne = checker.getReturnTypeOfSignature(signatures[0]);
  if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) {
    return;
  }
  return signatureDecls;
}

// src/services/refactors/addOrRemoveBracesToArrowFunction.ts
var refactorName6 = "Add or remove braces in an arrow function";
var refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
var addBracesAction = {
  name: "Add braces to arrow function",
  description: Diagnostics.Add_braces_to_arrow_function.message,
  kind: "refactor.rewrite.arrow.braces.add"
};
var removeBracesAction = {
  name: "Remove braces from arrow function",
  description: Diagnostics.Remove_braces_from_arrow_function.message,
  kind: "refactor.rewrite.arrow.braces.remove"
};
registerRefactor(refactorName6, {
  kinds: [removeBracesAction.kind],
  getEditsForAction: getRefactorEditsToRemoveFunctionBraces,
  getAvailableActions: getRefactorActionsToRemoveFunctionBraces
});
function getRefactorActionsToRemoveFunctionBraces(context) {
  const { file, startPosition, triggerReason } = context;
  const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked");
  if (!info)
    return emptyArray;
  if (!isRefactorErrorInfo(info)) {
    return [{
      name: refactorName6,
      description: refactorDescription2,
      actions: [
        info.addBraces ? addBracesAction : removeBracesAction
      ]
    }];
  }
  if (context.preferences.provideRefactorNotApplicableReason) {
    return [{
      name: refactorName6,
      description: refactorDescription2,
      actions: [
        { ...addBracesAction, notApplicableReason: info.error },
        { ...removeBracesAction, notApplicableReason: info.error }
      ]
    }];
  }
  return emptyArray;
}
function getRefactorEditsToRemoveFunctionBraces(context, actionName2) {
  const { file, startPosition } = context;
  const info = getConvertibleArrowFunctionAtPosition(file, startPosition);
  Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
  const { expression, returnStatement, func } = info;
  let body;
  if (actionName2 === addBracesAction.name) {
    const returnStatement2 = factory.createReturnStatement(expression);
    body = factory.createBlock(
      [returnStatement2],
      /*multiLine*/
      true
    );
    copyLeadingComments(
      expression,
      returnStatement2,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      true
    );
  } else if (actionName2 === removeBracesAction.name && returnStatement) {
    const actualExpression = expression || factory.createVoidZero();
    body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression;
    copyTrailingAsLeadingComments(
      returnStatement,
      body,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
    copyLeadingComments(
      returnStatement,
      body,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
    copyTrailingComments(
      returnStatement,
      body,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
  } else {
    Debug.fail("invalid action");
  }
  const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
    t.replaceNode(file, func.body, body);
  });
  return { renameFilename: void 0, renameLocation: void 0, edits };
}
function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) {
  const node = getTokenAtPosition(file, startPosition);
  const func = getContainingFunction(node);
  if (!func) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function)
    };
  }
  if (!isArrowFunction(func)) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function)
    };
  }
  if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) {
    return void 0;
  }
  if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) {
    return { func, addBraces: true, expression: func.body };
  } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) {
    const firstStatement = first(func.body.statements);
    if (isReturnStatement(firstStatement)) {
      return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement };
    }
  }
  return void 0;
}

// src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts
var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {};

// src/services/refactors/convertArrowFunctionOrFunctionExpression.ts
var refactorName7 = "Convert arrow function or function expression";
var refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression);
var toAnonymousFunctionAction = {
  name: "Convert to anonymous function",
  description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function),
  kind: "refactor.rewrite.function.anonymous"
};
var toNamedFunctionAction = {
  name: "Convert to named function",
  description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function),
  kind: "refactor.rewrite.function.named"
};
var toArrowFunctionAction = {
  name: "Convert to arrow function",
  description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function),
  kind: "refactor.rewrite.function.arrow"
};
registerRefactor(refactorName7, {
  kinds: [
    toAnonymousFunctionAction.kind,
    toNamedFunctionAction.kind,
    toArrowFunctionAction.kind
  ],
  getEditsForAction: getRefactorEditsToConvertFunctionExpressions,
  getAvailableActions: getRefactorActionsToConvertFunctionExpressions
});
function getRefactorActionsToConvertFunctionExpressions(context) {
  const { file, startPosition, program, kind } = context;
  const info = getFunctionInfo(file, startPosition, program);
  if (!info)
    return emptyArray;
  const { selectedVariableDeclaration, func } = info;
  const possibleActions = [];
  const errors = [];
  if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) {
    const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function);
    if (error) {
      errors.push({ ...toNamedFunctionAction, notApplicableReason: error });
    } else {
      possibleActions.push(toNamedFunctionAction);
    }
  }
  if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) {
    const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function);
    if (error) {
      errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error });
    } else {
      possibleActions.push(toAnonymousFunctionAction);
    }
  }
  if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) {
    const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function);
    if (error) {
      errors.push({ ...toArrowFunctionAction, notApplicableReason: error });
    } else {
      possibleActions.push(toArrowFunctionAction);
    }
  }
  return [{
    name: refactorName7,
    description: refactorDescription3,
    actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions
  }];
}
function getRefactorEditsToConvertFunctionExpressions(context, actionName2) {
  const { file, startPosition, program } = context;
  const info = getFunctionInfo(file, startPosition, program);
  if (!info)
    return void 0;
  const { func } = info;
  const edits = [];
  switch (actionName2) {
    case toAnonymousFunctionAction.name:
      edits.push(...getEditInfoForConvertToAnonymousFunction(context, func));
      break;
    case toNamedFunctionAction.name:
      const variableInfo = getVariableInfo(func);
      if (!variableInfo)
        return void 0;
      edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo));
      break;
    case toArrowFunctionAction.name:
      if (!isFunctionExpression(func))
        return void 0;
      edits.push(...getEditInfoForConvertToArrowFunction(context, func));
      break;
    default:
      return Debug.fail("invalid action");
  }
  return { renameFilename: void 0, renameLocation: void 0, edits };
}
function containingThis(node) {
  let containsThis = false;
  node.forEachChild(function checkThis(child) {
    if (isThis(child)) {
      containsThis = true;
      return;
    }
    if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) {
      forEachChild(child, checkThis);
    }
  });
  return containsThis;
}
function getFunctionInfo(file, startPosition, program) {
  const token = getTokenAtPosition(file, startPosition);
  const typeChecker = program.getTypeChecker();
  const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent);
  if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) {
    return { selectedVariableDeclaration: true, func };
  }
  const maybeFunc = getContainingFunction(token);
  if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) {
    if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc))
      return void 0;
    return { selectedVariableDeclaration: false, func: maybeFunc };
  }
  return void 0;
}
function isSingleVariableDeclaration(parent2) {
  return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1;
}
function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) {
  if (!isSingleVariableDeclaration(parent2)) {
    return void 0;
  }
  const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations);
  const initializer = variableDeclaration.initializer;
  if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) {
    return initializer;
  }
  return void 0;
}
function convertToBlock(body) {
  if (isExpression(body)) {
    const returnStatement = factory.createReturnStatement(body);
    const file = body.getSourceFile();
    setTextRange(returnStatement, body);
    suppressLeadingAndTrailingTrivia(returnStatement);
    copyTrailingAsLeadingComments(
      body,
      returnStatement,
      file,
      /*commentKind*/
      void 0,
      /*hasTrailingNewLine*/
      true
    );
    return factory.createBlock(
      [returnStatement],
      /*multiLine*/
      true
    );
  } else {
    return body;
  }
}
function getVariableInfo(func) {
  const variableDeclaration = func.parent;
  if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration))
    return void 0;
  const variableDeclarationList = variableDeclaration.parent;
  const statement = variableDeclarationList.parent;
  if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name))
    return void 0;
  return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name };
}
function getEditInfoForConvertToAnonymousFunction(context, func) {
  const { file } = context;
  const body = convertToBlock(func.body);
  const newNode = factory.createFunctionExpression(
    func.modifiers,
    func.asteriskToken,
    /*name*/
    void 0,
    func.typeParameters,
    func.parameters,
    func.type,
    body
  );
  return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode));
}
function getEditInfoForConvertToNamedFunction(context, func, variableInfo) {
  const { file } = context;
  const body = convertToBlock(func.body);
  const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo;
  suppressLeadingTrivia(statement);
  const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func);
  const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags);
  const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body);
  if (variableDeclarationList.declarations.length === 1) {
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode));
  } else {
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      t.delete(file, variableDeclaration);
      t.insertNodeAfter(file, statement, newNode);
    });
  }
}
function getEditInfoForConvertToArrowFunction(context, func) {
  const { file } = context;
  const statements = func.body.statements;
  const head = statements[0];
  let body;
  if (canBeConvertedToExpression(func.body, head)) {
    body = head.expression;
    suppressLeadingAndTrailingTrivia(body);
    copyComments(head, body);
  } else {
    body = func.body;
  }
  const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body);
  return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode));
}
function canBeConvertedToExpression(body, head) {
  return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression);
}
function isFunctionReferencedInFile(sourceFile, typeChecker, node) {
  return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile);
}

// src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts
var ts_refactor_convertParamsToDestructuredObject_exports = {};

// src/services/refactors/convertParamsToDestructuredObject.ts
var refactorName8 = "Convert parameters to destructured object";
var minimumParameterLength = 1;
var refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object);
var toDestructuredAction = {
  name: refactorName8,
  description: refactorDescription4,
  kind: "refactor.rewrite.parameters.toDestructured"
};
registerRefactor(refactorName8, {
  kinds: [toDestructuredAction.kind],
  getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject,
  getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject
});
function getRefactorActionsToConvertParametersToDestructuredObject(context) {
  const { file, startPosition } = context;
  const isJSFile = isSourceFileJS(file);
  if (isJSFile)
    return emptyArray;
  const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
  if (!functionDeclaration)
    return emptyArray;
  return [{
    name: refactorName8,
    description: refactorDescription4,
    actions: [toDestructuredAction]
  }];
}
function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) {
  Debug.assert(actionName2 === refactorName8, "Unexpected action name");
  const { file, startPosition, program, cancellationToken, host } = context;
  const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
  if (!functionDeclaration || !cancellationToken)
    return void 0;
  const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
  if (groupedReferences.valid) {
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(file, program, host, t, functionDeclaration, groupedReferences));
    return { renameFilename: void 0, renameLocation: void 0, edits };
  }
  return { edits: [] };
}
function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
  const signature = groupedReferences.signature;
  const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param));
  if (signature) {
    const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param));
    replaceParameters(signature, newSignatureParams);
  }
  replaceParameters(functionDeclaration, newFunctionDeclarationParams);
  const functionCalls = sortAndDeduplicate(
    groupedReferences.functionCalls,
    /*comparer*/
    (a, b) => compareValues(a.pos, b.pos)
  );
  for (const call of functionCalls) {
    if (call.arguments && call.arguments.length) {
      const newArgument = getSynthesizedDeepClone(
        createNewArgument(functionDeclaration, call.arguments),
        /*includeTrivia*/
        true
      );
      changes.replaceNodeRange(
        getSourceFileOfNode(call),
        first(call.arguments),
        last(call.arguments),
        newArgument,
        { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include }
      );
    }
  }
  function replaceParameters(declarationOrSignature, parameterDeclarations) {
    changes.replaceNodeRangeWithNodes(
      sourceFile,
      first(declarationOrSignature.parameters),
      last(declarationOrSignature.parameters),
      parameterDeclarations,
      {
        joiner: ", ",
        // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
        indentation: 0,
        leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll,
        trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
      }
    );
  }
}
function getGroupedReferences(functionDeclaration, program, cancellationToken) {
  const functionNames = getFunctionNames(functionDeclaration);
  const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
  const names = deduplicate([...functionNames, ...classNames], equateValues);
  const checker = program.getTypeChecker();
  const references = flatMap(
    names,
    /*mapfn*/
    (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)
  );
  const groupedReferences = groupReferences(references);
  if (!every(
    groupedReferences.declarations,
    /*callback*/
    (decl) => contains(names, decl)
  )) {
    groupedReferences.valid = false;
  }
  return groupedReferences;
  function groupReferences(referenceEntries) {
    const classReferences = { accessExpressions: [], typeUsages: [] };
    const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true };
    const functionSymbols = map(functionNames, getSymbolTargetAtLocation);
    const classSymbols = map(classNames, getSymbolTargetAtLocation);
    const isConstructor = isConstructorDeclaration(functionDeclaration);
    const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker));
    for (const entry of referenceEntries) {
      if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) {
        groupedReferences2.valid = false;
        continue;
      }
      if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) {
        if (isValidMethodSignature(entry.node.parent)) {
          groupedReferences2.signature = entry.node.parent;
          continue;
        }
        const call = entryToFunctionCall(entry);
        if (call) {
          groupedReferences2.functionCalls.push(call);
          continue;
        }
      }
      const contextualSymbol = getSymbolForContextualType(entry.node, checker);
      if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) {
        const decl = entryToDeclaration(entry);
        if (decl) {
          groupedReferences2.declarations.push(decl);
          continue;
        }
      }
      if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) {
        const importOrExportReference = entryToImportOrExport(entry);
        if (importOrExportReference) {
          continue;
        }
        const decl = entryToDeclaration(entry);
        if (decl) {
          groupedReferences2.declarations.push(decl);
          continue;
        }
        const call = entryToFunctionCall(entry);
        if (call) {
          groupedReferences2.functionCalls.push(call);
          continue;
        }
      }
      if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) {
        const importOrExportReference = entryToImportOrExport(entry);
        if (importOrExportReference) {
          continue;
        }
        const decl = entryToDeclaration(entry);
        if (decl) {
          groupedReferences2.declarations.push(decl);
          continue;
        }
        const accessExpression = entryToAccessExpression(entry);
        if (accessExpression) {
          classReferences.accessExpressions.push(accessExpression);
          continue;
        }
        if (isClassDeclaration(functionDeclaration.parent)) {
          const type = entryToType(entry);
          if (type) {
            classReferences.typeUsages.push(type);
            continue;
          }
        }
      }
      groupedReferences2.valid = false;
    }
    return groupedReferences2;
  }
  function getSymbolTargetAtLocation(node) {
    const symbol = checker.getSymbolAtLocation(node);
    return symbol && getSymbolTarget(symbol, checker);
  }
}
function getSymbolForContextualType(node, checker) {
  const element = getContainingObjectLiteralElement(node);
  if (element) {
    const contextualType = checker.getContextualTypeForObjectLiteralElement(element);
    const symbol = contextualType == null ? void 0 : contextualType.getSymbol();
    if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) {
      return symbol;
    }
  }
}
function entryToImportOrExport(entry) {
  const node = entry.node;
  if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) {
    return node;
  }
  if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) {
    return node;
  }
  return void 0;
}
function entryToDeclaration(entry) {
  if (isDeclaration(entry.node.parent)) {
    return entry.node;
  }
  return void 0;
}
function entryToFunctionCall(entry) {
  if (entry.node.parent) {
    const functionReference = entry.node;
    const parent2 = functionReference.parent;
    switch (parent2.kind) {
      case 212 /* CallExpression */:
      case 213 /* NewExpression */:
        const callOrNewExpression = tryCast(parent2, isCallOrNewExpression);
        if (callOrNewExpression && callOrNewExpression.expression === functionReference) {
          return callOrNewExpression;
        }
        break;
      case 210 /* PropertyAccessExpression */:
        const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression);
        if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
          const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression);
          if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) {
            return callOrNewExpression2;
          }
        }
        break;
      case 211 /* ElementAccessExpression */:
        const elementAccessExpression = tryCast(parent2, isElementAccessExpression);
        if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
          const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression);
          if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) {
            return callOrNewExpression2;
          }
        }
        break;
    }
  }
  return void 0;
}
function entryToAccessExpression(entry) {
  if (entry.node.parent) {
    const reference = entry.node;
    const parent2 = reference.parent;
    switch (parent2.kind) {
      case 210 /* PropertyAccessExpression */:
        const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression);
        if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
          return propertyAccessExpression;
        }
        break;
      case 211 /* ElementAccessExpression */:
        const elementAccessExpression = tryCast(parent2, isElementAccessExpression);
        if (elementAccessExpression && elementAccessExpression.expression === reference) {
          return elementAccessExpression;
        }
        break;
    }
  }
  return void 0;
}
function entryToType(entry) {
  const reference = entry.node;
  if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
    return reference;
  }
  return void 0;
}
function getFunctionDeclarationAtPosition(file, startPosition, checker) {
  const node = getTouchingToken(file, startPosition);
  const functionDeclaration = getContainingFunctionDeclaration(node);
  if (isTopLevelJSDoc(node))
    return void 0;
  if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node)))
    return functionDeclaration;
  return void 0;
}
function isTopLevelJSDoc(node) {
  const containingJSDoc = findAncestor(node, isJSDocNode);
  if (containingJSDoc) {
    const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n));
    return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc);
  }
  return false;
}
function isValidMethodSignature(node) {
  return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent));
}
function isValidFunctionDeclaration(functionDeclaration, checker) {
  var _a;
  if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
    return false;
  switch (functionDeclaration.kind) {
    case 261 /* FunctionDeclaration */:
      return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker);
    case 173 /* MethodDeclaration */:
      if (isObjectLiteralExpression(functionDeclaration.parent)) {
        const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker);
        return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker);
      }
      return isSingleImplementation(functionDeclaration, checker);
    case 175 /* Constructor */:
      if (isClassDeclaration(functionDeclaration.parent)) {
        return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker);
      } else {
        return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker);
      }
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
      return isValidVariableDeclaration(functionDeclaration.parent);
  }
  return false;
}
function isSingleImplementation(functionDeclaration, checker) {
  return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
}
function hasNameOrDefault(functionOrClassDeclaration) {
  if (!functionOrClassDeclaration.name) {
    const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */);
    return !!defaultKeyword;
  }
  return true;
}
function isValidParameterNodeArray(parameters, checker) {
  return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(
    parameters,
    /*callback*/
    (paramDecl) => isValidParameterDeclaration(paramDecl, checker)
  );
}
function isValidParameterDeclaration(parameterDeclaration, checker) {
  if (isRestParameter(parameterDeclaration)) {
    const type = checker.getTypeAtLocation(parameterDeclaration);
    if (!checker.isArrayType(type) && !checker.isTupleType(type))
      return false;
  }
  return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name);
}
function isValidVariableDeclaration(node) {
  return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type;
}
function hasThisParameter(parameters) {
  return parameters.length > 0 && isThis(parameters[0].name);
}
function getRefactorableParametersLength(parameters) {
  if (hasThisParameter(parameters)) {
    return parameters.length - 1;
  }
  return parameters.length;
}
function getRefactorableParameters(parameters) {
  if (hasThisParameter(parameters)) {
    parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
  }
  return parameters;
}
function createPropertyOrShorthandAssignment(name, initializer) {
  if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) {
    return factory.createShorthandPropertyAssignment(name);
  }
  return factory.createPropertyAssignment(name, initializer);
}
function createNewArgument(functionDeclaration, functionArguments) {
  const parameters = getRefactorableParameters(functionDeclaration.parameters);
  const hasRestParameter2 = isRestParameter(last(parameters));
  const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
  const properties = map(nonRestArguments, (arg, i) => {
    const parameterName = getParameterName(parameters[i]);
    const property = createPropertyOrShorthandAssignment(parameterName, arg);
    suppressLeadingAndTrailingTrivia(property.name);
    if (isPropertyAssignment(property))
      suppressLeadingAndTrailingTrivia(property.initializer);
    copyComments(arg, property);
    return property;
  });
  if (hasRestParameter2 && functionArguments.length >= parameters.length) {
    const restArguments = functionArguments.slice(parameters.length - 1);
    const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments));
    properties.push(restProperty);
  }
  const objectLiteral = factory.createObjectLiteralExpression(
    properties,
    /*multiLine*/
    false
  );
  return objectLiteral;
}
function createNewParameters(functionDeclaration, program, host) {
  const checker = program.getTypeChecker();
  const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
  const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration);
  const objectParameterName = factory.createObjectBindingPattern(bindingElements);
  const objectParameterType = createParameterTypeNode(refactorableParameters);
  let objectInitializer;
  if (every(refactorableParameters, isOptionalParameter)) {
    objectInitializer = factory.createObjectLiteralExpression();
  }
  const objectParameter = factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    objectParameterName,
    /*questionToken*/
    void 0,
    objectParameterType,
    objectInitializer
  );
  if (hasThisParameter(functionDeclaration.parameters)) {
    const thisParameter = functionDeclaration.parameters[0];
    const newThisParameter = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      thisParameter.name,
      /*questionToken*/
      void 0,
      thisParameter.type
    );
    suppressLeadingAndTrailingTrivia(newThisParameter.name);
    copyComments(thisParameter.name, newThisParameter.name);
    if (thisParameter.type) {
      suppressLeadingAndTrailingTrivia(newThisParameter.type);
      copyComments(thisParameter.type, newThisParameter.type);
    }
    return factory.createNodeArray([newThisParameter, objectParameter]);
  }
  return factory.createNodeArray([objectParameter]);
  function createBindingElementFromParameterDeclaration(parameterDeclaration) {
    const element = factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      /*propertyName*/
      void 0,
      getParameterName(parameterDeclaration),
      isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer
    );
    suppressLeadingAndTrailingTrivia(element);
    if (parameterDeclaration.initializer && element.initializer) {
      copyComments(parameterDeclaration.initializer, element.initializer);
    }
    return element;
  }
  function createParameterTypeNode(parameters) {
    const members = map(parameters, createPropertySignatureFromParameterDeclaration);
    const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */);
    return typeNode;
  }
  function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
    let parameterType = parameterDeclaration.type;
    if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) {
      parameterType = getTypeNode3(parameterDeclaration);
    }
    const propertySignature = factory.createPropertySignature(
      /*modifiers*/
      void 0,
      getParameterName(parameterDeclaration),
      isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken,
      parameterType
    );
    suppressLeadingAndTrailingTrivia(propertySignature);
    copyComments(parameterDeclaration.name, propertySignature.name);
    if (parameterDeclaration.type && propertySignature.type) {
      copyComments(parameterDeclaration.type, propertySignature.type);
    }
    return propertySignature;
  }
  function getTypeNode3(node) {
    const type = checker.getTypeAtLocation(node);
    return getTypeNodeIfAccessible(type, node, program, host);
  }
  function isOptionalParameter(parameterDeclaration) {
    if (isRestParameter(parameterDeclaration)) {
      const type = checker.getTypeAtLocation(parameterDeclaration);
      return !checker.isTupleType(type);
    }
    return checker.isOptionalParameter(parameterDeclaration);
  }
}
function getParameterName(paramDeclaration) {
  return getTextOfIdentifierOrLiteral(paramDeclaration.name);
}
function getClassNames(constructorDeclaration) {
  switch (constructorDeclaration.parent.kind) {
    case 262 /* ClassDeclaration */:
      const classDeclaration = constructorDeclaration.parent;
      if (classDeclaration.name)
        return [classDeclaration.name];
      const defaultModifier = Debug.checkDefined(
        findModifier(classDeclaration, 90 /* DefaultKeyword */),
        "Nameless class declaration should be a default export"
      );
      return [defaultModifier];
    case 230 /* ClassExpression */:
      const classExpression = constructorDeclaration.parent;
      const variableDeclaration = constructorDeclaration.parent.parent;
      const className = classExpression.name;
      if (className)
        return [className, variableDeclaration.name];
      return [variableDeclaration.name];
  }
}
function getFunctionNames(functionDeclaration) {
  switch (functionDeclaration.kind) {
    case 261 /* FunctionDeclaration */:
      if (functionDeclaration.name)
        return [functionDeclaration.name];
      const defaultModifier = Debug.checkDefined(
        findModifier(functionDeclaration, 90 /* DefaultKeyword */),
        "Nameless function declaration should be a default export"
      );
      return [defaultModifier];
    case 173 /* MethodDeclaration */:
      return [functionDeclaration.name];
    case 175 /* Constructor */:
      const ctrKeyword = Debug.checkDefined(
        findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()),
        "Constructor declaration should have constructor keyword"
      );
      if (functionDeclaration.parent.kind === 230 /* ClassExpression */) {
        const variableDeclaration = functionDeclaration.parent.parent;
        return [variableDeclaration.name, ctrKeyword];
      }
      return [ctrKeyword];
    case 218 /* ArrowFunction */:
      return [functionDeclaration.parent.name];
    case 217 /* FunctionExpression */:
      if (functionDeclaration.name)
        return [functionDeclaration.name, functionDeclaration.parent.name];
      return [functionDeclaration.parent.name];
    default:
      return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`);
  }
}

// src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts
var ts_refactor_convertStringOrTemplateLiteral_exports = {};

// src/services/refactors/convertStringOrTemplateLiteral.ts
var refactorName9 = "Convert to template string";
var refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string);
var convertStringAction = {
  name: refactorName9,
  description: refactorDescription5,
  kind: "refactor.rewrite.string"
};
registerRefactor(refactorName9, {
  kinds: [convertStringAction.kind],
  getEditsForAction: getRefactorEditsToConvertToTemplateString,
  getAvailableActions: getRefactorActionsToConvertToTemplateString
});
function getRefactorActionsToConvertToTemplateString(context) {
  const { file, startPosition } = context;
  const node = getNodeOrParentOfParentheses(file, startPosition);
  const maybeBinary = getParentBinaryExpression(node);
  const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] };
  if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) {
    refactorInfo.actions.push(convertStringAction);
    return [refactorInfo];
  } else if (context.preferences.provideRefactorNotApplicableReason) {
    refactorInfo.actions.push({
      ...convertStringAction,
      notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation)
    });
    return [refactorInfo];
  }
  return emptyArray;
}
function getNodeOrParentOfParentheses(file, startPosition) {
  const node = getTokenAtPosition(file, startPosition);
  const nestedBinary = getParentBinaryExpression(node);
  const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation;
  if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) {
    return nestedBinary.parent.parent;
  }
  return node;
}
function getRefactorEditsToConvertToTemplateString(context, actionName2) {
  const { file, startPosition } = context;
  const node = getNodeOrParentOfParentheses(file, startPosition);
  switch (actionName2) {
    case refactorDescription5:
      return { edits: getEditsForToTemplateLiteral(context, node) };
    default:
      return Debug.fail("invalid action");
  }
}
function getEditsForToTemplateLiteral(context, node) {
  const maybeBinary = getParentBinaryExpression(node);
  const file = context.file;
  const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file);
  const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end);
  if (trailingCommentRanges) {
    const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1];
    const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end };
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      t.deleteRange(file, trailingRange);
      t.replaceNode(file, maybeBinary, templateLiteral);
    });
  } else {
    return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral));
  }
}
function isNotEqualsOperator(node) {
  return node.operatorToken.kind !== 64 /* EqualsToken */;
}
function getParentBinaryExpression(expr) {
  const container = findAncestor(expr.parent, (n) => {
    switch (n.kind) {
      case 210 /* PropertyAccessExpression */:
      case 211 /* ElementAccessExpression */:
        return false;
      case 227 /* TemplateExpression */:
      case 225 /* BinaryExpression */:
        return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent));
      default:
        return "quit";
    }
  });
  return container || expr;
}
function treeToArray(current) {
  const loop = (current2) => {
    if (!isBinaryExpression(current2)) {
      return {
        nodes: [current2],
        operators: [],
        validOperators: true,
        hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2)
      };
    }
    const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left);
    if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) {
      return { nodes: [current2], operators: [], hasString: false, validOperators: true };
    }
    const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */;
    const validOperators2 = leftOperatorValid && currentOperatorValid;
    nodes2.push(current2.right);
    operators2.push(current2.operatorToken);
    return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 };
  };
  const { nodes, operators, validOperators, hasString } = loop(current);
  return { nodes, operators, isValidConcatenation: validOperators && hasString };
}
var copyTrailingOperatorComments = (operators, file) => (index, targetNode) => {
  if (index < operators.length) {
    copyTrailingComments(
      operators[index],
      targetNode,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
  }
};
var copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => {
  while (indexes.length > 0) {
    const index = indexes.shift();
    copyTrailingComments(
      nodes[index],
      targetNode,
      file,
      3 /* MultiLineCommentTrivia */,
      /*hasTrailingNewLine*/
      false
    );
    copyOperatorComments(index, targetNode);
  }
};
function escapeRawStringForTemplate(s) {
  return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m);
}
function getRawTextOfTemplate(node) {
  const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1;
  return getTextOfNode(node).slice(1, rightShaving);
}
function concatConsecutiveString(index, nodes) {
  const indexes = [];
  let text = "", rawText = "";
  while (index < nodes.length) {
    const node = nodes[index];
    if (isStringLiteralLike(node)) {
      text += node.text;
      rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1));
      indexes.push(index);
      index++;
    } else if (isTemplateExpression(node)) {
      text += node.head.text;
      rawText += getRawTextOfTemplate(node.head);
      break;
    } else {
      break;
    }
  }
  return [index, text, rawText, indexes];
}
function nodesToTemplate({ nodes, operators }, file) {
  const copyOperatorComments = copyTrailingOperatorComments(operators, file);
  const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments);
  const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes);
  if (begin === nodes.length) {
    const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText);
    copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral);
    return noSubstitutionTemplateLiteral;
  }
  const templateSpans = [];
  const templateHead = factory.createTemplateHead(headText, rawHeadText);
  copyCommentFromStringLiterals(headIndexes, templateHead);
  for (let i = begin; i < nodes.length; i++) {
    const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]);
    copyOperatorComments(i, currentNode);
    const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes);
    i = newIndex - 1;
    const isLast = i === nodes.length - 1;
    if (isTemplateExpression(currentNode)) {
      const spans = map(currentNode.templateSpans, (span, index) => {
        copyExpressionComments(span);
        const isLastSpan = index === currentNode.templateSpans.length - 1;
        const text = span.literal.text + (isLastSpan ? subsequentText : "");
        const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : "");
        return factory.createTemplateSpan(span.expression, isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText));
      });
      templateSpans.push(...spans);
    } else {
      const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText);
      copyCommentFromStringLiterals(stringIndexes, templatePart);
      templateSpans.push(factory.createTemplateSpan(currentNode, templatePart));
    }
  }
  return factory.createTemplateExpression(templateHead, templateSpans);
}
function copyExpressionComments(node) {
  const file = node.getSourceFile();
  copyTrailingComments(
    node,
    node.expression,
    file,
    3 /* MultiLineCommentTrivia */,
    /*hasTrailingNewLine*/
    false
  );
  copyTrailingAsLeadingComments(
    node.expression,
    node.expression,
    file,
    3 /* MultiLineCommentTrivia */,
    /*hasTrailingNewLine*/
    false
  );
}
function getExpressionFromParenthesesOrExpression(node) {
  if (isParenthesizedExpression(node)) {
    copyExpressionComments(node);
    node = node.expression;
  }
  return node;
}

// src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts
var ts_refactor_convertToOptionalChainExpression_exports = {};

// src/services/refactors/convertToOptionalChainExpression.ts
var refactorName10 = "Convert to optional chain expression";
var convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression);
var toOptionalChainAction = {
  name: refactorName10,
  description: convertToOptionalChainExpressionMessage,
  kind: "refactor.rewrite.expression.optionalChain"
};
registerRefactor(refactorName10, {
  kinds: [toOptionalChainAction.kind],
  getEditsForAction: getRefactorEditsToConvertToOptionalChain,
  getAvailableActions: getRefactorActionsToConvertToOptionalChain
});
function getRefactorActionsToConvertToOptionalChain(context) {
  const info = getInfo3(context, context.triggerReason === "invoked");
  if (!info)
    return emptyArray;
  if (!isRefactorErrorInfo(info)) {
    return [{
      name: refactorName10,
      description: convertToOptionalChainExpressionMessage,
      actions: [toOptionalChainAction]
    }];
  }
  if (context.preferences.provideRefactorNotApplicableReason) {
    return [{
      name: refactorName10,
      description: convertToOptionalChainExpressionMessage,
      actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }]
    }];
  }
  return emptyArray;
}
function getRefactorEditsToConvertToOptionalChain(context, actionName2) {
  const info = getInfo3(context);
  Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
  const edits = ts_textChanges_exports.ChangeTracker.with(
    context,
    (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2)
  );
  return { edits, renameFilename: void 0, renameLocation: void 0 };
}
function isValidExpression(node) {
  return isBinaryExpression(node) || isConditionalExpression(node);
}
function isValidStatement(node) {
  return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node);
}
function isValidExpressionOrStatement(node) {
  return isValidExpression(node) || isValidStatement(node);
}
function getInfo3(context, considerEmptySpans = true) {
  const { file, program } = context;
  const span = getRefactorContextSpan(context);
  const forEmptySpan = span.length === 0;
  if (forEmptySpan && !considerEmptySpans)
    return void 0;
  const startToken = getTokenAtPosition(file, span.start);
  const endToken = findTokenOnLeftOfPosition(file, span.start + span.length);
  const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd());
  const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan);
  const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0;
  if (!expression)
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) };
  const checker = program.getTypeChecker();
  return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression);
}
function getConditionalInfo(expression, checker) {
  const condition = expression.condition;
  const finalExpression = getFinalExpressionInChain(expression.whenTrue);
  if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) };
  }
  if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) {
    return { finalExpression, occurrences: [condition], expression };
  } else if (isBinaryExpression(condition)) {
    const occurrences = getOccurrencesInExpression(finalExpression.expression, condition);
    return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) };
  }
}
function getBinaryInfo(expression) {
  if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) {
    return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) };
  }
  const finalExpression = getFinalExpressionInChain(expression.right);
  if (!finalExpression)
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) };
  const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left);
  return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) };
}
function getOccurrencesInExpression(matchTo, expression) {
  const occurrences = [];
  while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
    const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right));
    if (!match) {
      break;
    }
    occurrences.push(match);
    matchTo = match;
    expression = expression.left;
  }
  const finalMatch = getMatchingStart(matchTo, expression);
  if (finalMatch) {
    occurrences.push(finalMatch);
  }
  return occurrences.length > 0 ? occurrences : void 0;
}
function getMatchingStart(chain, subchain) {
  if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) {
    return void 0;
  }
  return chainStartsWith(chain, subchain) ? subchain : void 0;
}
function chainStartsWith(chain, subchain) {
  while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) {
    if (getTextOfChainNode(chain) === getTextOfChainNode(subchain))
      break;
    chain = chain.expression;
  }
  while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) {
    if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain))
      return false;
    chain = chain.expression;
    subchain = subchain.expression;
  }
  return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText();
}
function getTextOfChainNode(node) {
  if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) {
    return node.getText();
  }
  if (isPropertyAccessExpression(node)) {
    return getTextOfChainNode(node.name);
  }
  if (isElementAccessExpression(node)) {
    return getTextOfChainNode(node.argumentExpression);
  }
  return void 0;
}
function getValidParentNodeContainingSpan(node, span) {
  while (node.parent) {
    if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) {
      return node;
    }
    node = node.parent;
  }
  return void 0;
}
function getValidParentNodeOfEmptySpan(node) {
  while (node.parent) {
    if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) {
      return node;
    }
    node = node.parent;
  }
  return void 0;
}
function getExpression(node) {
  if (isValidExpression(node)) {
    return node;
  }
  if (isVariableStatement(node)) {
    const variable = getSingleVariableOfVariableStatement(node);
    const initializer = variable == null ? void 0 : variable.initializer;
    return initializer && isValidExpression(initializer) ? initializer : void 0;
  }
  return node.expression && isValidExpression(node.expression) ? node.expression : void 0;
}
function getFinalExpressionInChain(node) {
  node = skipParentheses(node);
  if (isBinaryExpression(node)) {
    return getFinalExpressionInChain(node.left);
  } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) {
    return node;
  }
  return void 0;
}
function convertOccurrences(checker, toConvert, occurrences) {
  if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) {
    const chain = convertOccurrences(checker, toConvert.expression, occurrences);
    const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0;
    const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText();
    if (isOccurrence)
      occurrences.pop();
    if (isCallExpression(toConvert)) {
      return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments);
    } else if (isPropertyAccessExpression(toConvert)) {
      return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name);
    } else if (isElementAccessExpression(toConvert)) {
      return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression);
    }
  }
  return toConvert;
}
function doChange6(sourceFile, checker, changes, info, _actionName) {
  const { finalExpression, occurrences, expression } = info;
  const firstOccurrence = occurrences[occurrences.length - 1];
  const convertedChain = convertOccurrences(checker, finalExpression, occurrences);
  if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) {
    if (isBinaryExpression(expression)) {
      changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain);
    } else if (isConditionalExpression(expression)) {
      changes.replaceNode(
        sourceFile,
        expression,
        factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse)
      );
    }
  }
}

// src/services/_namespaces/ts.refactor.extractSymbol.ts
var ts_refactor_extractSymbol_exports = {};
__export(ts_refactor_extractSymbol_exports, {
  Messages: () => Messages,
  RangeFacts: () => RangeFacts,
  getRangeToExtract: () => getRangeToExtract2,
  getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol,
  getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol
});

// src/services/refactors/extractSymbol.ts
var refactorName11 = "Extract Symbol";
var extractConstantAction = {
  name: "Extract Constant",
  description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
  kind: "refactor.extract.constant"
};
var extractFunctionAction = {
  name: "Extract Function",
  description: getLocaleSpecificMessage(Diagnostics.Extract_function),
  kind: "refactor.extract.function"
};
registerRefactor(refactorName11, {
  kinds: [
    extractConstantAction.kind,
    extractFunctionAction.kind
  ],
  getEditsForAction: getRefactorEditsToExtractSymbol,
  getAvailableActions: getRefactorActionsToExtractSymbol
});
function getRefactorActionsToExtractSymbol(context) {
  const requestedRefactor = context.kind;
  const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked");
  const targetRange = rangeToExtract.targetRange;
  if (targetRange === void 0) {
    if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) {
      return emptyArray;
    }
    const errors = [];
    if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
      errors.push({
        name: refactorName11,
        description: extractFunctionAction.description,
        actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }]
      });
    }
    if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
      errors.push({
        name: refactorName11,
        description: extractConstantAction.description,
        actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }]
      });
    }
    return errors;
  }
  const extractions = getPossibleExtractions(targetRange, context);
  if (extractions === void 0) {
    return emptyArray;
  }
  const functionActions = [];
  const usedFunctionNames = /* @__PURE__ */ new Map();
  let innermostErrorFunctionAction;
  const constantActions = [];
  const usedConstantNames = /* @__PURE__ */ new Map();
  let innermostErrorConstantAction;
  let i = 0;
  for (const { functionExtraction, constantExtraction } of extractions) {
    if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
      const description3 = functionExtraction.description;
      if (functionExtraction.errors.length === 0) {
        if (!usedFunctionNames.has(description3)) {
          usedFunctionNames.set(description3, true);
          functionActions.push({
            description: description3,
            name: `function_scope_${i}`,
            kind: extractFunctionAction.kind
          });
        }
      } else if (!innermostErrorFunctionAction) {
        innermostErrorFunctionAction = {
          description: description3,
          name: `function_scope_${i}`,
          notApplicableReason: getStringError(functionExtraction.errors),
          kind: extractFunctionAction.kind
        };
      }
    }
    if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
      const description3 = constantExtraction.description;
      if (constantExtraction.errors.length === 0) {
        if (!usedConstantNames.has(description3)) {
          usedConstantNames.set(description3, true);
          constantActions.push({
            description: description3,
            name: `constant_scope_${i}`,
            kind: extractConstantAction.kind
          });
        }
      } else if (!innermostErrorConstantAction) {
        innermostErrorConstantAction = {
          description: description3,
          name: `constant_scope_${i}`,
          notApplicableReason: getStringError(constantExtraction.errors),
          kind: extractConstantAction.kind
        };
      }
    }
    i++;
  }
  const infos = [];
  if (functionActions.length) {
    infos.push({
      name: refactorName11,
      description: getLocaleSpecificMessage(Diagnostics.Extract_function),
      actions: functionActions
    });
  } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) {
    infos.push({
      name: refactorName11,
      description: getLocaleSpecificMessage(Diagnostics.Extract_function),
      actions: [innermostErrorFunctionAction]
    });
  }
  if (constantActions.length) {
    infos.push({
      name: refactorName11,
      description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
      actions: constantActions
    });
  } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) {
    infos.push({
      name: refactorName11,
      description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
      actions: [innermostErrorConstantAction]
    });
  }
  return infos.length ? infos : emptyArray;
  function getStringError(errors) {
    let error = errors[0].messageText;
    if (typeof error !== "string") {
      error = error.messageText;
    }
    return error;
  }
}
function getRefactorEditsToExtractSymbol(context, actionName2) {
  const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context));
  const targetRange = rangeToExtract.targetRange;
  const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2);
  if (parsedFunctionIndexMatch) {
    const index = +parsedFunctionIndexMatch[1];
    Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
    return getFunctionExtractionAtIndex(targetRange, context, index);
  }
  const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2);
  if (parsedConstantIndexMatch) {
    const index = +parsedConstantIndexMatch[1];
    Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
    return getConstantExtractionAtIndex(targetRange, context, index);
  }
  Debug.fail("Unrecognized action name");
}
var Messages;
((Messages2) => {
  function createMessage(message) {
    return { message, code: 0, category: 3 /* Message */, key: message };
  }
  Messages2.cannotExtractRange = createMessage("Cannot extract range.");
  Messages2.cannotExtractImport = createMessage("Cannot extract import statement.");
  Messages2.cannotExtractSuper = createMessage("Cannot extract super call.");
  Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc.");
  Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range.");
  Messages2.expressionExpected = createMessage("expression expected.");
  Messages2.uselessConstantType = createMessage("No reason to extract constant of type.");
  Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected.");
  Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements.");
  Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement.");
  Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
  Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
  Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
  Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
  Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier.");
  Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
  Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
  Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
  Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
  Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
  Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
  Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
  Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method");
})(Messages || (Messages = {}));
var RangeFacts = /* @__PURE__ */ ((RangeFacts2) => {
  RangeFacts2[RangeFacts2["None"] = 0] = "None";
  RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn";
  RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator";
  RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction";
  RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis";
  RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction";
  RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion";
  return RangeFacts2;
})(RangeFacts || {});
function getRangeToExtract2(sourceFile, span, invoked = true) {
  const { length: length2 } = span;
  if (length2 === 0 && !invoked) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] };
  }
  const cursorRequest = length2 === 0 && invoked;
  const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start);
  const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span));
  const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span;
  const start2 = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan);
  const end = cursorRequest ? start2 : getParentNodeInSpan(endToken, sourceFile, adjustedSpan);
  let rangeFacts = 0 /* None */;
  let thisNode;
  if (!start2 || !end) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
  }
  if (start2.flags & 8388608 /* JSDoc */) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] };
  }
  if (start2.parent !== end.parent) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
  }
  if (start2 !== end) {
    if (!isBlockLike(start2.parent)) {
      return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
    }
    const statements = [];
    for (const statement of start2.parent.statements) {
      if (statement === start2 || statements.length) {
        const errors2 = checkNode(statement);
        if (errors2) {
          return { errors: errors2 };
        }
        statements.push(statement);
      }
      if (statement === end) {
        break;
      }
    }
    if (!statements.length) {
      return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
    }
    return { targetRange: { range: statements, facts: rangeFacts, thisNode } };
  }
  if (isReturnStatement(start2) && !start2.expression) {
    return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] };
  }
  const node = refineNode(start2);
  const errors = checkRootNode(node) || checkNode(node);
  if (errors) {
    return { errors };
  }
  return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } };
  function refineNode(node2) {
    if (isReturnStatement(node2)) {
      if (node2.expression) {
        return node2.expression;
      }
    } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) {
      const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations;
      let numInitializers = 0;
      let lastInitializer;
      for (const declaration of declarations) {
        if (declaration.initializer) {
          numInitializers++;
          lastInitializer = declaration.initializer;
        }
      }
      if (numInitializers === 1) {
        return lastInitializer;
      }
    } else if (isVariableDeclaration(node2)) {
      if (node2.initializer) {
        return node2.initializer;
      }
    }
    return node2;
  }
  function checkRootNode(node2) {
    if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) {
      return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)];
    }
    return void 0;
  }
  function checkForStaticContext(nodeToCheck, containingClass) {
    let current = nodeToCheck;
    while (current !== containingClass) {
      if (current.kind === 171 /* PropertyDeclaration */) {
        if (isStatic(current)) {
          rangeFacts |= 32 /* InStaticRegion */;
        }
        break;
      } else if (current.kind === 168 /* Parameter */) {
        const ctorOrMethod = getContainingFunction(current);
        if (ctorOrMethod.kind === 175 /* Constructor */) {
          rangeFacts |= 32 /* InStaticRegion */;
        }
        break;
      } else if (current.kind === 173 /* MethodDeclaration */) {
        if (isStatic(current)) {
          rangeFacts |= 32 /* InStaticRegion */;
        }
      }
      current = current.parent;
    }
  }
  function checkNode(nodeToCheck) {
    let PermittedJumps;
    ((PermittedJumps2) => {
      PermittedJumps2[PermittedJumps2["None"] = 0] = "None";
      PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break";
      PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue";
      PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return";
    })(PermittedJumps || (PermittedJumps = {}));
    Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)");
    Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)");
    if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) {
      return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
    }
    if (nodeToCheck.flags & 16777216 /* Ambient */) {
      return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
    }
    const containingClass = getContainingClass(nodeToCheck);
    if (containingClass) {
      checkForStaticContext(nodeToCheck, containingClass);
    }
    let errors2;
    let permittedJumps = 4 /* Return */;
    let seenLabels;
    visit(nodeToCheck);
    if (rangeFacts & 8 /* UsesThis */) {
      const container = getThisContainer(
        nodeToCheck,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) {
        rangeFacts |= 16 /* UsesThisInFunction */;
      }
    }
    return errors2;
    function visit(node2) {
      if (errors2) {
        return true;
      }
      if (isDeclaration(node2)) {
        const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2;
        if (hasSyntacticModifier(declaringNode, 1 /* Export */)) {
          (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity));
          return true;
        }
      }
      switch (node2.kind) {
        case 271 /* ImportDeclaration */:
          (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport));
          return true;
        case 276 /* ExportAssignment */:
          (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity));
          return true;
        case 108 /* SuperKeyword */:
          if (node2.parent.kind === 212 /* CallExpression */) {
            const containingClass2 = getContainingClass(node2);
            if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) {
              (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper));
              return true;
            }
          } else {
            rangeFacts |= 8 /* UsesThis */;
            thisNode = node2;
          }
          break;
        case 218 /* ArrowFunction */:
          forEachChild(node2, function check(n) {
            if (isThis(n)) {
              rangeFacts |= 8 /* UsesThis */;
              thisNode = node2;
            } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) {
              return false;
            } else {
              forEachChild(n, check);
            }
          });
        case 262 /* ClassDeclaration */:
        case 261 /* FunctionDeclaration */:
          if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) {
            (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope));
          }
        case 230 /* ClassExpression */:
        case 217 /* FunctionExpression */:
        case 173 /* MethodDeclaration */:
        case 175 /* Constructor */:
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
          return false;
      }
      const savedPermittedJumps = permittedJumps;
      switch (node2.kind) {
        case 244 /* IfStatement */:
          permittedJumps &= ~4 /* Return */;
          break;
        case 257 /* TryStatement */:
          permittedJumps = 0 /* None */;
          break;
        case 240 /* Block */:
          if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) {
            permittedJumps = 4 /* Return */;
          }
          break;
        case 296 /* DefaultClause */:
        case 295 /* CaseClause */:
          permittedJumps |= 1 /* Break */;
          break;
        default:
          if (isIterationStatement(
            node2,
            /*lookInLabeledStatements*/
            false
          )) {
            permittedJumps |= 1 /* Break */ | 2 /* Continue */;
          }
          break;
      }
      switch (node2.kind) {
        case 196 /* ThisType */:
        case 110 /* ThisKeyword */:
          rangeFacts |= 8 /* UsesThis */;
          thisNode = node2;
          break;
        case 255 /* LabeledStatement */: {
          const label = node2.label;
          (seenLabels || (seenLabels = [])).push(label.escapedText);
          forEachChild(node2, visit);
          seenLabels.pop();
          break;
        }
        case 251 /* BreakStatement */:
        case 250 /* ContinueStatement */: {
          const label = node2.label;
          if (label) {
            if (!contains(seenLabels, label.escapedText)) {
              (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
            }
          } else {
            if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
              (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
            }
          }
          break;
        }
        case 222 /* AwaitExpression */:
          rangeFacts |= 4 /* IsAsyncFunction */;
          break;
        case 228 /* YieldExpression */:
          rangeFacts |= 2 /* IsGenerator */;
          break;
        case 252 /* ReturnStatement */:
          if (permittedJumps & 4 /* Return */) {
            rangeFacts |= 1 /* HasReturn */;
          } else {
            (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement));
          }
          break;
        default:
          forEachChild(node2, visit);
          break;
      }
      permittedJumps = savedPermittedJumps;
    }
  }
}
function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) {
  const start2 = startNode2.getStart(sourceFile);
  let end = endNode2.getEnd();
  if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) {
    end++;
  }
  return { start: start2, length: end - start2 };
}
function getStatementOrExpressionRange(node) {
  if (isStatement(node)) {
    return [node];
  }
  if (isExpressionNode(node)) {
    return isExpressionStatement(node.parent) ? [node.parent] : node;
  }
  if (isStringLiteralJsxAttribute(node)) {
    return node;
  }
  return void 0;
}
function isScope(node) {
  return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node);
}
function collectEnclosingScopes(range) {
  let current = isReadonlyArray(range.range) ? first(range.range) : range.range;
  if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) {
    const containingClass = getContainingClass(current);
    if (containingClass) {
      const containingFunction = findAncestor(current, isFunctionLikeDeclaration);
      return containingFunction ? [containingFunction, containingClass] : [containingClass];
    }
  }
  const scopes = [];
  while (true) {
    current = current.parent;
    if (current.kind === 168 /* Parameter */) {
      current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent;
    }
    if (isScope(current)) {
      scopes.push(current);
      if (current.kind === 311 /* SourceFile */) {
        return scopes;
      }
    }
  }
}
function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) {
  const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
  Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
  context.cancellationToken.throwIfCancellationRequested();
  return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
}
function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) {
  const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
  Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
  Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
  context.cancellationToken.throwIfCancellationRequested();
  const expression = isExpression(target) ? target : target.statements[0].expression;
  return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
}
function getPossibleExtractions(targetRange, context) {
  const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context);
  const extractions = scopes.map((scope, i) => {
    const functionDescriptionPart = getDescriptionForFunctionInScope(scope);
    const constantDescriptionPart = getDescriptionForConstantInScope(scope);
    const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope);
    let functionDescription;
    let constantDescription;
    if (scopeDescription === 1 /* Global */) {
      functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
    } else if (scopeDescription === 0 /* Module */) {
      functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
    } else {
      functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
    }
    if (i === 0 && !isClassLike(scope)) {
      constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
    }
    return {
      functionExtraction: {
        description: functionDescription,
        errors: functionErrorsPerScope[i]
      },
      constantExtraction: {
        description: constantDescription,
        errors: constantErrorsPerScope[i]
      }
    };
  });
  return extractions;
}
function getPossibleExtractionsWorker(targetRange, context) {
  const { file: sourceFile } = context;
  const scopes = collectEnclosingScopes(targetRange);
  const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
  const readsAndWrites = collectReadsAndWrites(
    targetRange,
    scopes,
    enclosingTextRange,
    sourceFile,
    context.program.getTypeChecker(),
    context.cancellationToken
  );
  return { scopes, readsAndWrites };
}
function getDescriptionForFunctionInScope(scope) {
  return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function";
}
function getDescriptionForConstantInScope(scope) {
  return isClassLike(scope) ? "readonly field" : "constant";
}
function getDescriptionForFunctionLikeDeclaration(scope) {
  switch (scope.kind) {
    case 175 /* Constructor */:
      return "constructor";
    case 217 /* FunctionExpression */:
    case 261 /* FunctionDeclaration */:
      return scope.name ? `function '${scope.name.text}'` : ANONYMOUS;
    case 218 /* ArrowFunction */:
      return "arrow function";
    case 173 /* MethodDeclaration */:
      return `method '${scope.name.getText()}'`;
    case 176 /* GetAccessor */:
      return `'get ${scope.name.getText()}'`;
    case 177 /* SetAccessor */:
      return `'set ${scope.name.getText()}'`;
    default:
      Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`);
  }
}
function getDescriptionForClassLikeDeclaration(scope) {
  return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression";
}
function getDescriptionForModuleLikeDeclaration(scope) {
  return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
}
function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) {
  const checker = context.program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
  const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host);
  const file = scope.getSourceFile();
  const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file);
  const isJS = isInJSFile(scope);
  const functionName = factory.createIdentifier(functionNameText);
  let returnType;
  const parameters = [];
  const callArguments = [];
  let writes;
  usagesInScope.forEach((usage, name) => {
    let typeNode;
    if (!isJS) {
      let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
      type = checker.getBaseTypeOfLiteralType(type);
      typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */);
    }
    const paramDecl = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      /*name*/
      name,
      /*questionToken*/
      void 0,
      typeNode
    );
    parameters.push(paramDecl);
    if (usage.usage === 2 /* Write */) {
      (writes || (writes = [])).push(usage);
    }
    callArguments.push(factory.createIdentifier(name));
  });
  const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) }));
  const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
  const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration);
  const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode(
    decl.name,
    /*typeArguments*/
    void 0
  )) : void 0;
  if (isExpression(node) && !isJS) {
    const contextualType = checker.getContextualType(node);
    returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */);
  }
  const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */));
  suppressLeadingAndTrailingTrivia(body);
  let newFunction;
  const callThis = !!(range.facts & 16 /* UsesThisInFunction */);
  if (isClassLike(scope)) {
    const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)];
    if (range.facts & 32 /* InStaticRegion */) {
      modifiers.push(factory.createModifier(126 /* StaticKeyword */));
    }
    if (range.facts & 4 /* IsAsyncFunction */) {
      modifiers.push(factory.createModifier(134 /* AsyncKeyword */));
    }
    newFunction = factory.createMethodDeclaration(
      modifiers.length ? modifiers : void 0,
      range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0,
      functionName,
      /*questionToken*/
      void 0,
      typeParameters,
      parameters,
      returnType,
      body
    );
  } else {
    if (callThis) {
      parameters.unshift(
        factory.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          /*name*/
          "this",
          /*questionToken*/
          void 0,
          checker.typeToTypeNode(
            checker.getTypeAtLocation(range.thisNode),
            scope,
            1 /* NoTruncation */
          ),
          /*initializer*/
          void 0
        )
      );
    }
    newFunction = factory.createFunctionDeclaration(
      range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0,
      range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0,
      functionName,
      typeParameters,
      parameters,
      returnType,
      body
    );
  }
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end;
  const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
  if (nodeToInsertBefore) {
    changeTracker.insertNodeBefore(
      context.file,
      nodeToInsertBefore,
      newFunction,
      /*blankLineBetween*/
      true
    );
  } else {
    changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
  }
  importAdder.writeFixes(changeTracker);
  const newNodes = [];
  const called = getCalledExpression(scope, range, functionNameText);
  if (callThis) {
    callArguments.unshift(factory.createIdentifier("this"));
  }
  let call = factory.createCallExpression(
    callThis ? factory.createPropertyAccessExpression(
      called,
      "call"
    ) : called,
    callTypeArguments,
    // Note that no attempt is made to take advantage of type argument inference
    callArguments
  );
  if (range.facts & 2 /* IsGenerator */) {
    call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call);
  }
  if (range.facts & 4 /* IsAsyncFunction */) {
    call = factory.createAwaitExpression(call);
  }
  if (isInJSXContent(node)) {
    call = factory.createJsxExpression(
      /*dotDotDotToken*/
      void 0,
      call
    );
  }
  if (exposedVariableDeclarations.length && !writes) {
    Debug.assert(!returnValueProperty, "Expected no returnValueProperty");
    Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset");
    if (exposedVariableDeclarations.length === 1) {
      const variableDeclaration = exposedVariableDeclarations[0];
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            getSynthesizedDeepClone(variableDeclaration.name),
            /*exclamationToken*/
            void 0,
            /*type*/
            getSynthesizedDeepClone(variableDeclaration.type),
            /*initializer*/
            call
          )],
          variableDeclaration.parent.flags
        )
      ));
    } else {
      const bindingElements = [];
      const typeElements = [];
      let commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
      let sawExplicitType = false;
      for (const variableDeclaration of exposedVariableDeclarations) {
        bindingElements.push(factory.createBindingElement(
          /*dotDotDotToken*/
          void 0,
          /*propertyName*/
          void 0,
          /*name*/
          getSynthesizedDeepClone(variableDeclaration.name)
        ));
        const variableType = checker.typeToTypeNode(
          checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)),
          scope,
          1 /* NoTruncation */
        );
        typeElements.push(factory.createPropertySignature(
          /*modifiers*/
          void 0,
          /*name*/
          variableDeclaration.symbol.name,
          /*questionToken*/
          void 0,
          /*type*/
          variableType
        ));
        sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0;
        commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
      }
      const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0;
      if (typeLiteral) {
        setEmitFlags(typeLiteral, 1 /* SingleLine */);
      }
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            factory.createObjectBindingPattern(bindingElements),
            /*exclamationToken*/
            void 0,
            /*type*/
            typeLiteral,
            /*initializer*/
            call
          )],
          commonNodeFlags
        )
      ));
    }
  } else if (exposedVariableDeclarations.length || writes) {
    if (exposedVariableDeclarations.length) {
      for (const variableDeclaration of exposedVariableDeclarations) {
        let flags = variableDeclaration.parent.flags;
        if (flags & 2 /* Const */) {
          flags = flags & ~2 /* Const */ | 1 /* Let */;
        }
        newNodes.push(factory.createVariableStatement(
          /*modifiers*/
          void 0,
          factory.createVariableDeclarationList(
            [factory.createVariableDeclaration(
              variableDeclaration.symbol.name,
              /*exclamationToken*/
              void 0,
              getTypeDeepCloneUnionUndefined(variableDeclaration.type)
            )],
            flags
          )
        ));
      }
    }
    if (returnValueProperty) {
      newNodes.push(factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList(
          [factory.createVariableDeclaration(
            returnValueProperty,
            /*exclamationToken*/
            void 0,
            getTypeDeepCloneUnionUndefined(returnType)
          )],
          1 /* Let */
        )
      ));
    }
    const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
    if (returnValueProperty) {
      assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty));
    }
    if (assignments.length === 1) {
      Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here");
      newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call)));
      if (range.facts & 1 /* HasReturn */) {
        newNodes.push(factory.createReturnStatement());
      }
    } else {
      newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call)));
      if (returnValueProperty) {
        newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty)));
      }
    }
  } else {
    if (range.facts & 1 /* HasReturn */) {
      newNodes.push(factory.createReturnStatement(call));
    } else if (isReadonlyArray(range.range)) {
      newNodes.push(factory.createExpressionStatement(call));
    } else {
      newNodes.push(call);
    }
  }
  if (isReadonlyArray(range.range)) {
    changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes);
  } else {
    changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes);
  }
  const edits = changeTracker.getChanges();
  const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range;
  const renameFilename = renameRange.getSourceFile().fileName;
  const renameLocation = getRenameLocation(
    edits,
    renameFilename,
    functionNameText,
    /*preferLastLocation*/
    false
  );
  return { renameFilename, renameLocation, edits };
  function getTypeDeepCloneUnionUndefined(typeNode) {
    if (typeNode === void 0) {
      return void 0;
    }
    const clone2 = getSynthesizedDeepClone(typeNode);
    let withoutParens = clone2;
    while (isParenthesizedTypeNode(withoutParens)) {
      withoutParens = withoutParens.type;
    }
    return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
  }
}
function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) {
  const checker = context.program.getTypeChecker();
  const file = scope.getSourceFile();
  const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(
    node.name.text,
    node,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file);
  const isJS = isInJSFile(scope);
  let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */);
  let initializer = transformConstantInitializer(skipParentheses(node), substitutions);
  ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer));
  suppressLeadingAndTrailingTrivia(initializer);
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  if (isClassLike(scope)) {
    Debug.assert(!isJS, "Cannot extract to a JS class");
    const modifiers = [];
    modifiers.push(factory.createModifier(123 /* PrivateKeyword */));
    if (rangeFacts & 32 /* InStaticRegion */) {
      modifiers.push(factory.createModifier(126 /* StaticKeyword */));
    }
    modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */));
    const newVariable = factory.createPropertyDeclaration(
      modifiers,
      localNameText,
      /*questionOrExclamationToken*/
      void 0,
      variableType,
      initializer
    );
    let localReference = factory.createPropertyAccessExpression(
      rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(),
      factory.createIdentifier(localNameText)
    );
    if (isInJSXContent(node)) {
      localReference = factory.createJsxExpression(
        /*dotDotDotToken*/
        void 0,
        localReference
      );
    }
    const maxInsertionPos = node.pos;
    const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope);
    changeTracker.insertNodeBefore(
      context.file,
      nodeToInsertBefore,
      newVariable,
      /*blankLineBetween*/
      true
    );
    changeTracker.replaceNode(context.file, node, localReference);
  } else {
    const newVariableDeclaration = factory.createVariableDeclaration(
      localNameText,
      /*exclamationToken*/
      void 0,
      variableType,
      initializer
    );
    const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope);
    if (oldVariableDeclaration) {
      changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration);
      const localReference = factory.createIdentifier(localNameText);
      changeTracker.replaceNode(context.file, node, localReference);
    } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) {
      const newVariableStatement = factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)
      );
      changeTracker.replaceNode(context.file, node.parent, newVariableStatement);
    } else {
      const newVariableStatement = factory.createVariableStatement(
        /*modifiers*/
        void 0,
        factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)
      );
      const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope);
      if (nodeToInsertBefore.pos === 0) {
        changeTracker.insertNodeAtTopOfFile(
          context.file,
          newVariableStatement,
          /*blankLineBetween*/
          false
        );
      } else {
        changeTracker.insertNodeBefore(
          context.file,
          nodeToInsertBefore,
          newVariableStatement,
          /*blankLineBetween*/
          false
        );
      }
      if (node.parent.kind === 243 /* ExpressionStatement */) {
        changeTracker.delete(context.file, node.parent);
      } else {
        let localReference = factory.createIdentifier(localNameText);
        if (isInJSXContent(node)) {
          localReference = factory.createJsxExpression(
            /*dotDotDotToken*/
            void 0,
            localReference
          );
        }
        changeTracker.replaceNode(context.file, node, localReference);
      }
    }
  }
  const edits = changeTracker.getChanges();
  const renameFilename = node.getSourceFile().fileName;
  const renameLocation = getRenameLocation(
    edits,
    renameFilename,
    localNameText,
    /*preferLastLocation*/
    true
  );
  return { renameFilename, renameLocation, edits };
  function transformFunctionInitializerAndType(variableType2, initializer2) {
    if (variableType2 === void 0)
      return { variableType: variableType2, initializer: initializer2 };
    if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters)
      return { variableType: variableType2, initializer: initializer2 };
    const functionType = checker.getTypeAtLocation(node);
    const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */));
    if (!functionSignature)
      return { variableType: variableType2, initializer: initializer2 };
    if (!!functionSignature.getTypeParameters())
      return { variableType: variableType2, initializer: initializer2 };
    const parameters = [];
    let hasAny = false;
    for (const p of initializer2.parameters) {
      if (p.type) {
        parameters.push(p);
      } else {
        const paramType = checker.getTypeAtLocation(p);
        if (paramType === checker.getAnyType())
          hasAny = true;
        parameters.push(factory.updateParameterDeclaration(
          p,
          p.modifiers,
          p.dotDotDotToken,
          p.name,
          p.questionToken,
          p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */),
          p.initializer
        ));
      }
    }
    if (hasAny)
      return { variableType: variableType2, initializer: initializer2 };
    variableType2 = void 0;
    if (isArrowFunction(initializer2)) {
      initializer2 = factory.updateArrowFunction(
        initializer2,
        canHaveModifiers(node) ? getModifiers(node) : void 0,
        initializer2.typeParameters,
        parameters,
        initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */),
        initializer2.equalsGreaterThanToken,
        initializer2.body
      );
    } else {
      if (functionSignature && !!functionSignature.thisParameter) {
        const firstParameter = firstOrUndefined(parameters);
        if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") {
          const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node);
          parameters.splice(0, 0, factory.createParameterDeclaration(
            /*modifiers*/
            void 0,
            /*dotDotDotToken*/
            void 0,
            "this",
            /*questionToken*/
            void 0,
            checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */)
          ));
        }
      }
      initializer2 = factory.updateFunctionExpression(
        initializer2,
        canHaveModifiers(node) ? getModifiers(node) : void 0,
        initializer2.asteriskToken,
        initializer2.name,
        initializer2.typeParameters,
        parameters,
        initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */),
        initializer2.body
      );
    }
    return { variableType: variableType2, initializer: initializer2 };
  }
}
function getContainingVariableDeclarationIfInList(node, scope) {
  let prevNode;
  while (node !== void 0 && node !== scope) {
    if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) {
      return node;
    }
    prevNode = node;
    node = node.parent;
  }
}
function getFirstDeclarationBeforePosition(type, position) {
  let firstDeclaration;
  const symbol = type.symbol;
  if (symbol && symbol.declarations) {
    for (const declaration of symbol.declarations) {
      if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) {
        firstDeclaration = declaration;
      }
    }
  }
  return firstDeclaration;
}
function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) {
  return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive(
    type1.symbol ? type1.symbol.getName() : "",
    type2.symbol ? type2.symbol.getName() : ""
  ) || compareValues(type1.id, type2.id);
}
function getCalledExpression(scope, range, functionNameText) {
  const functionReference = factory.createIdentifier(functionNameText);
  if (isClassLike(scope)) {
    const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis();
    return factory.createPropertyAccessExpression(lhs, functionReference);
  } else {
    return functionReference;
  }
}
function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) {
  const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0;
  if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
    return { body: factory.createBlock(
      body.statements,
      /*multiLine*/
      true
    ), returnValueProperty: void 0 };
  }
  let returnValueProperty;
  let ignoreReturns = false;
  const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]);
  if (hasWritesOrVariableDeclarations || substitutions.size) {
    const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice();
    if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) {
      const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
      if (assignments.length === 1) {
        rewrittenStatements.push(factory.createReturnStatement(assignments[0].name));
      } else {
        rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)));
      }
    }
    return { body: factory.createBlock(
      rewrittenStatements,
      /*multiLine*/
      true
    ), returnValueProperty };
  } else {
    return { body: factory.createBlock(
      statements,
      /*multiLine*/
      true
    ), returnValueProperty: void 0 };
  }
  function visitor(node) {
    if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) {
      const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
      if (node.expression) {
        if (!returnValueProperty) {
          returnValueProperty = "__return";
        }
        assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression)));
      }
      if (assignments.length === 1) {
        return factory.createReturnStatement(assignments[0].name);
      } else {
        return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments));
      }
    } else {
      const oldIgnoreReturns = ignoreReturns;
      ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node);
      const substitution = substitutions.get(getNodeId(node).toString());
      const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext);
      ignoreReturns = oldIgnoreReturns;
      return result;
    }
  }
}
function transformConstantInitializer(initializer, substitutions) {
  return substitutions.size ? visitor(initializer) : initializer;
  function visitor(node) {
    const substitution = substitutions.get(getNodeId(node).toString());
    return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext);
  }
}
function getStatementsOrClassElements(scope) {
  if (isFunctionLikeDeclaration(scope)) {
    const body = scope.body;
    if (isBlock(body)) {
      return body.statements;
    }
  } else if (isModuleBlock(scope) || isSourceFile(scope)) {
    return scope.statements;
  } else if (isClassLike(scope)) {
    return scope.members;
  } else {
    assertType(scope);
  }
  return emptyArray;
}
function getNodeToInsertFunctionBefore(minPos, scope) {
  return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child));
}
function getNodeToInsertPropertyBefore(maxPos, scope) {
  const members = scope.members;
  Debug.assert(members.length > 0, "Found no members");
  let prevMember;
  let allProperties = true;
  for (const member of members) {
    if (member.pos > maxPos) {
      return prevMember || members[0];
    }
    if (allProperties && !isPropertyDeclaration(member)) {
      if (prevMember !== void 0) {
        return member;
      }
      allProperties = false;
    }
    prevMember = member;
  }
  if (prevMember === void 0)
    return Debug.fail();
  return prevMember;
}
function getNodeToInsertConstantBefore(node, scope) {
  Debug.assert(!isClassLike(scope));
  let prevScope;
  for (let curr = node; curr !== scope; curr = curr.parent) {
    if (isScope(curr)) {
      prevScope = curr;
    }
  }
  for (let curr = (prevScope || node).parent; ; curr = curr.parent) {
    if (isBlockLike(curr)) {
      let prevStatement;
      for (const statement of curr.statements) {
        if (statement.pos > node.pos) {
          break;
        }
        prevStatement = statement;
      }
      if (!prevStatement && isCaseClause(curr)) {
        Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement");
        return curr.parent.parent;
      }
      return Debug.checkDefined(prevStatement, "prevStatement failed to get set");
    }
    Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
  }
}
function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
  const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name));
  const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name));
  return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments);
}
function isReadonlyArray(v) {
  return isArray(v);
}
function getEnclosingTextRange(targetRange, sourceFile) {
  return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range;
}
function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) {
  const allTypeParameterUsages = /* @__PURE__ */ new Map();
  const usagesPerScope = [];
  const substitutionsPerScope = [];
  const functionErrorsPerScope = [];
  const constantErrorsPerScope = [];
  const visibleDeclarationsInExtractedRange = [];
  const exposedVariableSymbolSet = /* @__PURE__ */ new Map();
  const exposedVariableDeclarations = [];
  let firstExposedNonVariableDeclaration;
  const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0;
  let expressionDiagnostic;
  if (expression === void 0) {
    const statements = targetRange.range;
    const start2 = first(statements).getStart();
    const end = last(statements).end;
    expressionDiagnostic = createFileDiagnostic(sourceFile, start2, end - start2, Messages.expressionExpected);
  } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) {
    expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType);
  }
  for (const scope of scopes) {
    usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() });
    substitutionsPerScope.push(/* @__PURE__ */ new Map());
    functionErrorsPerScope.push([]);
    const constantErrors = [];
    if (expressionDiagnostic) {
      constantErrors.push(expressionDiagnostic);
    }
    if (isClassLike(scope) && isInJSFile(scope)) {
      constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
    }
    if (isArrowFunction(scope) && !isBlock(scope.body)) {
      constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
    }
    constantErrorsPerScope.push(constantErrors);
  }
  const seenUsages = /* @__PURE__ */ new Map();
  const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range;
  const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range;
  const inGenericContext = isInGenericContext(unmodifiedNode);
  collectUsages(target);
  if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) {
    const contextualType = checker.getContextualType(targetRange.range);
    recordTypeParameterUsages(contextualType);
  }
  if (allTypeParameterUsages.size > 0) {
    const seenTypeParameterUsages = /* @__PURE__ */ new Map();
    let i = 0;
    for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) {
      if (curr === scopes[i]) {
        seenTypeParameterUsages.forEach((typeParameter, id) => {
          usagesPerScope[i].typeParameterUsages.set(id, typeParameter);
        });
        i++;
      }
      if (isDeclarationWithTypeParameters(curr)) {
        for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) {
          const typeParameter = checker.getTypeAtLocation(typeParameterDecl);
          if (allTypeParameterUsages.has(typeParameter.id.toString())) {
            seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter);
          }
        }
      }
    }
    Debug.assert(i === scopes.length, "Should have iterated all scopes");
  }
  if (visibleDeclarationsInExtractedRange.length) {
    const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]);
    forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
  }
  for (let i = 0; i < scopes.length; i++) {
    const scopeUsages = usagesPerScope[i];
    if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
      const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
      constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
    }
    if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) {
      functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod));
    }
    let hasWrite = false;
    let readonlyClassPropertyWrite;
    usagesPerScope[i].usages.forEach((value) => {
      if (value.usage === 2 /* Write */) {
        hasWrite = true;
        if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) {
          readonlyClassPropertyWrite = value.symbol.valueDeclaration;
        }
      }
    });
    Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted");
    if (hasWrite && !isReadonlyArray(targetRange.range)) {
      const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
      functionErrorsPerScope[i].push(diag2);
      constantErrorsPerScope[i].push(diag2);
    } else if (readonlyClassPropertyWrite && i > 0) {
      const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
      functionErrorsPerScope[i].push(diag2);
      constantErrorsPerScope[i].push(diag2);
    } else if (firstExposedNonVariableDeclaration) {
      const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
      functionErrorsPerScope[i].push(diag2);
      constantErrorsPerScope[i].push(diag2);
    }
  }
  return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations };
  function isInGenericContext(node) {
    return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0);
  }
  function recordTypeParameterUsages(type) {
    const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true));
    const { visitedTypes } = symbolWalker.walkType(type);
    for (const visitedType of visitedTypes) {
      if (visitedType.isTypeParameter()) {
        allTypeParameterUsages.set(visitedType.id.toString(), visitedType);
      }
    }
  }
  function collectUsages(node, valueUsage = 1 /* Read */) {
    if (inGenericContext) {
      const type = checker.getTypeAtLocation(node);
      recordTypeParameterUsages(type);
    }
    if (isDeclaration(node) && node.symbol) {
      visibleDeclarationsInExtractedRange.push(node);
    }
    if (isAssignmentExpression(node)) {
      collectUsages(node.left, 2 /* Write */);
      collectUsages(node.right);
    } else if (isUnaryExpressionWithWrite(node)) {
      collectUsages(node.operand, 2 /* Write */);
    } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) {
      forEachChild(node, collectUsages);
    } else if (isIdentifier(node)) {
      if (!node.parent) {
        return;
      }
      if (isQualifiedName(node.parent) && node !== node.parent.left) {
        return;
      }
      if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) {
        return;
      }
      recordUsage(
        node,
        valueUsage,
        /*isTypeNode*/
        isPartOfTypeNode(node)
      );
    } else {
      forEachChild(node, collectUsages);
    }
  }
  function recordUsage(n, usage, isTypeNode2) {
    const symbolId = recordUsagebySymbol(n, usage, isTypeNode2);
    if (symbolId) {
      for (let i = 0; i < scopes.length; i++) {
        const substitution = substitutionsPerScope[i].get(symbolId);
        if (substitution) {
          usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution);
        }
      }
    }
  }
  function recordUsagebySymbol(identifier, usage, isTypeName) {
    const symbol = getSymbolReferencedByIdentifier(identifier);
    if (!symbol) {
      return void 0;
    }
    const symbolId = getSymbolId(symbol).toString();
    const lastUsage = seenUsages.get(symbolId);
    if (lastUsage && lastUsage >= usage) {
      return symbolId;
    }
    seenUsages.set(symbolId, usage);
    if (lastUsage) {
      for (const perScope of usagesPerScope) {
        const prevEntry = perScope.usages.get(identifier.text);
        if (prevEntry) {
          perScope.usages.set(identifier.text, { usage, symbol, node: identifier });
        }
      }
      return symbolId;
    }
    const decls = symbol.getDeclarations();
    const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile);
    if (!declInFile) {
      return void 0;
    }
    if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) {
      return void 0;
    }
    if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) {
      const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
      for (const errors of functionErrorsPerScope) {
        errors.push(diag2);
      }
      for (const errors of constantErrorsPerScope) {
        errors.push(diag2);
      }
    }
    for (let i = 0; i < scopes.length; i++) {
      const scope = scopes[i];
      const resolvedSymbol = checker.resolveName(
        symbol.name,
        scope,
        symbol.flags,
        /*excludeGlobals*/
        false
      );
      if (resolvedSymbol === symbol) {
        continue;
      }
      if (!substitutionsPerScope[i].has(symbolId)) {
        const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName);
        if (substitution) {
          substitutionsPerScope[i].set(symbolId, substitution);
        } else if (isTypeName) {
          if (!(symbol.flags & 262144 /* TypeParameter */)) {
            const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
            functionErrorsPerScope[i].push(diag2);
            constantErrorsPerScope[i].push(diag2);
          }
        } else {
          usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier });
        }
      }
    }
    return symbolId;
  }
  function checkForUsedDeclarations(node) {
    if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) {
      return;
    }
    const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node);
    if (sym) {
      const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym);
      if (decl) {
        if (isVariableDeclaration(decl)) {
          const idString = decl.symbol.id.toString();
          if (!exposedVariableSymbolSet.has(idString)) {
            exposedVariableDeclarations.push(decl);
            exposedVariableSymbolSet.set(idString, true);
          }
        } else {
          firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
        }
      }
    }
    forEachChild(node, checkForUsedDeclarations);
  }
  function getSymbolReferencedByIdentifier(identifier) {
    return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier);
  }
  function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) {
    if (!symbol) {
      return void 0;
    }
    const decls = symbol.getDeclarations();
    if (decls && decls.some((d) => d.parent === scopeDecl)) {
      return factory.createIdentifier(symbol.name);
    }
    const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2);
    if (prefix === void 0) {
      return void 0;
    }
    return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name);
  }
}
function getExtractableParent(node) {
  return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent));
}
function isExtractableExpression(node) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 305 /* EnumMember */:
      return false;
  }
  switch (node.kind) {
    case 11 /* StringLiteral */:
      return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */;
    case 229 /* SpreadElement */:
    case 205 /* ObjectBindingPattern */:
    case 207 /* BindingElement */:
      return false;
    case 80 /* Identifier */:
      return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */;
  }
  return true;
}
function isBlockLike(node) {
  switch (node.kind) {
    case 240 /* Block */:
    case 311 /* SourceFile */:
    case 267 /* ModuleBlock */:
    case 295 /* CaseClause */:
      return true;
    default:
      return false;
  }
}
function isInJSXContent(node) {
  return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent));
}
function isStringLiteralJsxAttribute(node) {
  return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent);
}

// src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts
var ts_refactor_generateGetAccessorAndSetAccessor_exports = {};

// src/services/refactors/generateGetAccessorAndSetAccessor.ts
var actionName = "Generate 'get' and 'set' accessors";
var actionDescription = Diagnostics.Generate_get_and_set_accessors.message;
var generateGetSetAction = {
  name: actionName,
  description: actionDescription,
  kind: "refactor.rewrite.property.generateAccessors"
};
registerRefactor(actionName, {
  kinds: [generateGetSetAction.kind],
  getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) {
    if (!context.endPosition)
      return void 0;
    const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition);
    Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info");
    const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2);
    if (!edits)
      return void 0;
    const renameFilename = context.file.fileName;
    const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName;
    const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1;
    const renameLocation = renameLocationOffset + getRenameLocation(
      edits,
      renameFilename,
      nameNeedRename.text,
      /*preferLastLocation*/
      isParameter(info.declaration)
    );
    return { renameFilename, renameLocation, edits };
  },
  getAvailableActions(context) {
    if (!context.endPosition)
      return emptyArray;
    const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked");
    if (!info)
      return emptyArray;
    if (!isRefactorErrorInfo(info)) {
      return [{
        name: actionName,
        description: actionDescription,
        actions: [generateGetSetAction]
      }];
    }
    if (context.preferences.provideRefactorNotApplicableReason) {
      return [{
        name: actionName,
        description: actionDescription,
        actions: [{ ...generateGetSetAction, notApplicableReason: info.error }]
      }];
    }
    return emptyArray;
  }
});

// src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts
var ts_refactor_inferFunctionReturnType_exports = {};

// src/services/refactors/inferFunctionReturnType.ts
var refactorName12 = "Infer function return type";
var refactorDescription6 = Diagnostics.Infer_function_return_type.message;
var inferReturnTypeAction = {
  name: refactorName12,
  description: refactorDescription6,
  kind: "refactor.rewrite.function.returnType"
};
registerRefactor(refactorName12, {
  kinds: [inferReturnTypeAction.kind],
  getEditsForAction: getRefactorEditsToInferReturnType,
  getAvailableActions: getRefactorActionsToInferReturnType
});
function getRefactorEditsToInferReturnType(context) {
  const info = getInfo4(context);
  if (info && !isRefactorErrorInfo(info)) {
    const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(context.file, t, info.declaration, info.returnTypeNode));
    return { renameFilename: void 0, renameLocation: void 0, edits };
  }
  return void 0;
}
function getRefactorActionsToInferReturnType(context) {
  const info = getInfo4(context);
  if (!info)
    return emptyArray;
  if (!isRefactorErrorInfo(info)) {
    return [{
      name: refactorName12,
      description: refactorDescription6,
      actions: [inferReturnTypeAction]
    }];
  }
  if (context.preferences.provideRefactorNotApplicableReason) {
    return [{
      name: refactorName12,
      description: refactorDescription6,
      actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }]
    }];
  }
  return emptyArray;
}
function doChange7(sourceFile, changes, declaration, typeNode) {
  const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile);
  const needParens = isArrowFunction(declaration) && closeParen === void 0;
  const endNode2 = needParens ? first(declaration.parameters) : closeParen;
  if (endNode2) {
    if (needParens) {
      changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */));
      changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */));
    }
    changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " });
  }
}
function getInfo4(context) {
  if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind))
    return;
  const token = getTokenAtPosition(context.file, context.startPosition);
  const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n));
  if (!declaration || !declaration.body || declaration.type) {
    return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) };
  }
  const typeChecker = context.program.getTypeChecker();
  const returnType = tryGetReturnType(typeChecker, declaration);
  if (!returnType) {
    return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) };
  }
  const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */);
  if (returnTypeNode) {
    return { declaration, returnTypeNode };
  }
}
function isConvertibleDeclaration(node) {
  switch (node.kind) {
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
    case 173 /* MethodDeclaration */:
      return true;
    default:
      return false;
  }
}
function tryGetReturnType(typeChecker, node) {
  if (typeChecker.isImplementationOfOverload(node)) {
    const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures();
    if (signatures.length > 1) {
      return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType()));
    }
  }
  const signature = typeChecker.getSignatureFromDeclaration(node);
  if (signature) {
    return typeChecker.getReturnTypeOfSignature(signature);
  }
}

// src/services/classifier2020.ts
var TokenEncodingConsts = /* @__PURE__ */ ((TokenEncodingConsts2) => {
  TokenEncodingConsts2[TokenEncodingConsts2["typeOffset"] = 8] = "typeOffset";
  TokenEncodingConsts2[TokenEncodingConsts2["modifierMask"] = 255] = "modifierMask";
  return TokenEncodingConsts2;
})(TokenEncodingConsts || {});
var TokenType = /* @__PURE__ */ ((TokenType2) => {
  TokenType2[TokenType2["class"] = 0] = "class";
  TokenType2[TokenType2["enum"] = 1] = "enum";
  TokenType2[TokenType2["interface"] = 2] = "interface";
  TokenType2[TokenType2["namespace"] = 3] = "namespace";
  TokenType2[TokenType2["typeParameter"] = 4] = "typeParameter";
  TokenType2[TokenType2["type"] = 5] = "type";
  TokenType2[TokenType2["parameter"] = 6] = "parameter";
  TokenType2[TokenType2["variable"] = 7] = "variable";
  TokenType2[TokenType2["enumMember"] = 8] = "enumMember";
  TokenType2[TokenType2["property"] = 9] = "property";
  TokenType2[TokenType2["function"] = 10] = "function";
  TokenType2[TokenType2["member"] = 11] = "member";
  return TokenType2;
})(TokenType || {});
var TokenModifier = /* @__PURE__ */ ((TokenModifier2) => {
  TokenModifier2[TokenModifier2["declaration"] = 0] = "declaration";
  TokenModifier2[TokenModifier2["static"] = 1] = "static";
  TokenModifier2[TokenModifier2["async"] = 2] = "async";
  TokenModifier2[TokenModifier2["readonly"] = 3] = "readonly";
  TokenModifier2[TokenModifier2["defaultLibrary"] = 4] = "defaultLibrary";
  TokenModifier2[TokenModifier2["local"] = 5] = "local";
  return TokenModifier2;
})(TokenModifier || {});
function getSemanticClassifications2(program, cancellationToken, sourceFile, span) {
  const classifications = getEncodedSemanticClassifications2(program, cancellationToken, sourceFile, span);
  Debug.assert(classifications.spans.length % 3 === 0);
  const dense = classifications.spans;
  const result = [];
  for (let i = 0; i < dense.length; i += 3) {
    result.push({
      textSpan: createTextSpan(dense[i], dense[i + 1]),
      classificationType: dense[i + 2]
    });
  }
  return result;
}
function getEncodedSemanticClassifications2(program, cancellationToken, sourceFile, span) {
  return {
    spans: getSemanticTokens(program, sourceFile, span, cancellationToken),
    endOfLineState: 0 /* None */
  };
}
function getSemanticTokens(program, sourceFile, span, cancellationToken) {
  const resultTokens = [];
  const collector = (node, typeIdx, modifierSet) => {
    resultTokens.push(node.getStart(sourceFile), node.getWidth(sourceFile), (typeIdx + 1 << 8 /* typeOffset */) + modifierSet);
  };
  if (program && sourceFile) {
    collectTokens(program, sourceFile, span, collector, cancellationToken);
  }
  return resultTokens;
}
function collectTokens(program, sourceFile, span, collector, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  let inJSXElement = false;
  function visit(node) {
    switch (node.kind) {
      case 266 /* ModuleDeclaration */:
      case 262 /* ClassDeclaration */:
      case 263 /* InterfaceDeclaration */:
      case 261 /* FunctionDeclaration */:
      case 230 /* ClassExpression */:
      case 217 /* FunctionExpression */:
      case 218 /* ArrowFunction */:
        cancellationToken.throwIfCancellationRequested();
    }
    if (!node || !textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) {
      return;
    }
    const prevInJSXElement = inJSXElement;
    if (isJsxElement(node) || isJsxSelfClosingElement(node)) {
      inJSXElement = true;
    }
    if (isJsxExpression(node)) {
      inJSXElement = false;
    }
    if (isIdentifier(node) && !inJSXElement && !inImportClause(node) && !isInfinityOrNaNString(node.escapedText)) {
      let symbol = typeChecker.getSymbolAtLocation(node);
      if (symbol) {
        if (symbol.flags & 2097152 /* Alias */) {
          symbol = typeChecker.getAliasedSymbol(symbol);
        }
        let typeIdx = classifySymbol2(symbol, getMeaningFromLocation(node));
        if (typeIdx !== void 0) {
          let modifierSet = 0;
          if (node.parent) {
            const parentIsDeclaration = isBindingElement(node.parent) || tokenFromDeclarationMapping.get(node.parent.kind) === typeIdx;
            if (parentIsDeclaration && node.parent.name === node) {
              modifierSet = 1 << 0 /* declaration */;
            }
          }
          if (typeIdx === 6 /* parameter */ && isRightSideOfQualifiedNameOrPropertyAccess2(node)) {
            typeIdx = 9 /* property */;
          }
          typeIdx = reclassifyByType(typeChecker, node, typeIdx);
          const decl = symbol.valueDeclaration;
          if (decl) {
            const modifiers = getCombinedModifierFlags(decl);
            const nodeFlags = getCombinedNodeFlags(decl);
            if (modifiers & 32 /* Static */) {
              modifierSet |= 1 << 1 /* static */;
            }
            if (modifiers & 512 /* Async */) {
              modifierSet |= 1 << 2 /* async */;
            }
            if (typeIdx !== 0 /* class */ && typeIdx !== 2 /* interface */) {
              if (modifiers & 64 /* Readonly */ || nodeFlags & 2 /* Const */ || symbol.getFlags() & 8 /* EnumMember */) {
                modifierSet |= 1 << 3 /* readonly */;
              }
            }
            if ((typeIdx === 7 /* variable */ || typeIdx === 10 /* function */) && isLocalDeclaration(decl, sourceFile)) {
              modifierSet |= 1 << 5 /* local */;
            }
            if (program.isSourceFileDefaultLibrary(decl.getSourceFile())) {
              modifierSet |= 1 << 4 /* defaultLibrary */;
            }
          } else if (symbol.declarations && symbol.declarations.some((d) => program.isSourceFileDefaultLibrary(d.getSourceFile()))) {
            modifierSet |= 1 << 4 /* defaultLibrary */;
          }
          collector(node, typeIdx, modifierSet);
        }
      }
    }
    forEachChild(node, visit);
    inJSXElement = prevInJSXElement;
  }
  visit(sourceFile);
}
function classifySymbol2(symbol, meaning) {
  const flags = symbol.getFlags();
  if (flags & 32 /* Class */) {
    return 0 /* class */;
  } else if (flags & 384 /* Enum */) {
    return 1 /* enum */;
  } else if (flags & 524288 /* TypeAlias */) {
    return 5 /* type */;
  } else if (flags & 64 /* Interface */) {
    if (meaning & 2 /* Type */) {
      return 2 /* interface */;
    }
  } else if (flags & 262144 /* TypeParameter */) {
    return 4 /* typeParameter */;
  }
  let decl = symbol.valueDeclaration || symbol.declarations && symbol.declarations[0];
  if (decl && isBindingElement(decl)) {
    decl = getDeclarationForBindingElement(decl);
  }
  return decl && tokenFromDeclarationMapping.get(decl.kind);
}
function reclassifyByType(typeChecker, node, typeIdx) {
  if (typeIdx === 7 /* variable */ || typeIdx === 9 /* property */ || typeIdx === 6 /* parameter */) {
    const type = typeChecker.getTypeAtLocation(node);
    if (type) {
      const test = (condition) => {
        return condition(type) || type.isUnion() && type.types.some(condition);
      };
      if (typeIdx !== 6 /* parameter */ && test((t) => t.getConstructSignatures().length > 0)) {
        return 0 /* class */;
      }
      if (test((t) => t.getCallSignatures().length > 0) && !test((t) => t.getProperties().length > 0) || isExpressionInCallExpression(node)) {
        return typeIdx === 9 /* property */ ? 11 /* member */ : 10 /* function */;
      }
    }
  }
  return typeIdx;
}
function isLocalDeclaration(decl, sourceFile) {
  if (isBindingElement(decl)) {
    decl = getDeclarationForBindingElement(decl);
  }
  if (isVariableDeclaration(decl)) {
    return (!isSourceFile(decl.parent.parent.parent) || isCatchClause(decl.parent)) && decl.getSourceFile() === sourceFile;
  } else if (isFunctionDeclaration(decl)) {
    return !isSourceFile(decl.parent) && decl.getSourceFile() === sourceFile;
  }
  return false;
}
function getDeclarationForBindingElement(element) {
  while (true) {
    if (isBindingElement(element.parent.parent)) {
      element = element.parent.parent;
    } else {
      return element.parent.parent;
    }
  }
}
function inImportClause(node) {
  const parent2 = node.parent;
  return parent2 && (isImportClause(parent2) || isImportSpecifier(parent2) || isNamespaceImport(parent2));
}
function isExpressionInCallExpression(node) {
  while (isRightSideOfQualifiedNameOrPropertyAccess2(node)) {
    node = node.parent;
  }
  return isCallExpression(node.parent) && node.parent.expression === node;
}
function isRightSideOfQualifiedNameOrPropertyAccess2(node) {
  return isQualifiedName(node.parent) && node.parent.right === node || isPropertyAccessExpression(node.parent) && node.parent.name === node;
}
var tokenFromDeclarationMapping = /* @__PURE__ */ new Map([
  [259 /* VariableDeclaration */, 7 /* variable */],
  [168 /* Parameter */, 6 /* parameter */],
  [171 /* PropertyDeclaration */, 9 /* property */],
  [266 /* ModuleDeclaration */, 3 /* namespace */],
  [265 /* EnumDeclaration */, 1 /* enum */],
  [305 /* EnumMember */, 8 /* enumMember */],
  [262 /* ClassDeclaration */, 0 /* class */],
  [173 /* MethodDeclaration */, 11 /* member */],
  [261 /* FunctionDeclaration */, 10 /* function */],
  [217 /* FunctionExpression */, 10 /* function */],
  [172 /* MethodSignature */, 11 /* member */],
  [176 /* GetAccessor */, 9 /* property */],
  [177 /* SetAccessor */, 9 /* property */],
  [170 /* PropertySignature */, 9 /* property */],
  [263 /* InterfaceDeclaration */, 2 /* interface */],
  [264 /* TypeAliasDeclaration */, 5 /* type */],
  [167 /* TypeParameter */, 4 /* typeParameter */],
  [302 /* PropertyAssignment */, 9 /* property */],
  [303 /* ShorthandPropertyAssignment */, 9 /* property */]
]);

// src/services/services.ts
var servicesVersion = "0.8";
function createNode(kind, pos, end, parent2) {
  const node = isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 80 /* Identifier */ ? new IdentifierObject(80 /* Identifier */, pos, end) : kind === 81 /* PrivateIdentifier */ ? new PrivateIdentifierObject(81 /* PrivateIdentifier */, pos, end) : new TokenObject(kind, pos, end);
  node.parent = parent2;
  node.flags = parent2.flags & 50720768 /* ContextFlags */;
  return node;
}
var NodeObject = class {
  constructor(kind, pos, end) {
    this.pos = pos;
    this.end = end;
    this.flags = 0 /* None */;
    this.modifierFlagsCache = 0 /* None */;
    this.transformFlags = 0 /* None */;
    this.parent = void 0;
    this.kind = kind;
  }
  assertHasRealPosition(message) {
    Debug.assert(!positionIsSynthesized(this.pos) && !positionIsSynthesized(this.end), message || "Node must have a real position for this operation");
  }
  getSourceFile() {
    return getSourceFileOfNode(this);
  }
  getStart(sourceFile, includeJsDocComment) {
    this.assertHasRealPosition();
    return getTokenPosOfNode(this, sourceFile, includeJsDocComment);
  }
  getFullStart() {
    this.assertHasRealPosition();
    return this.pos;
  }
  getEnd() {
    this.assertHasRealPosition();
    return this.end;
  }
  getWidth(sourceFile) {
    this.assertHasRealPosition();
    return this.getEnd() - this.getStart(sourceFile);
  }
  getFullWidth() {
    this.assertHasRealPosition();
    return this.end - this.pos;
  }
  getLeadingTriviaWidth(sourceFile) {
    this.assertHasRealPosition();
    return this.getStart(sourceFile) - this.pos;
  }
  getFullText(sourceFile) {
    this.assertHasRealPosition();
    return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
  }
  getText(sourceFile) {
    this.assertHasRealPosition();
    if (!sourceFile) {
      sourceFile = this.getSourceFile();
    }
    return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
  }
  getChildCount(sourceFile) {
    return this.getChildren(sourceFile).length;
  }
  getChildAt(index, sourceFile) {
    return this.getChildren(sourceFile)[index];
  }
  getChildren(sourceFile) {
    this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine");
    return this._children || (this._children = createChildren(this, sourceFile));
  }
  getFirstToken(sourceFile) {
    this.assertHasRealPosition();
    const children = this.getChildren(sourceFile);
    if (!children.length) {
      return void 0;
    }
    const child = find(children, (kid) => kid.kind < 315 /* FirstJSDocNode */ || kid.kind > 356 /* LastJSDocNode */);
    return child.kind < 165 /* FirstNode */ ? child : child.getFirstToken(sourceFile);
  }
  getLastToken(sourceFile) {
    this.assertHasRealPosition();
    const children = this.getChildren(sourceFile);
    const child = lastOrUndefined(children);
    if (!child) {
      return void 0;
    }
    return child.kind < 165 /* FirstNode */ ? child : child.getLastToken(sourceFile);
  }
  forEachChild(cbNode, cbNodeArray) {
    return forEachChild(this, cbNode, cbNodeArray);
  }
};
function createChildren(node, sourceFile) {
  if (!isNodeKind(node.kind)) {
    return emptyArray;
  }
  const children = [];
  if (isJSDocCommentContainingNode(node)) {
    node.forEachChild((child) => {
      children.push(child);
    });
    return children;
  }
  scanner.setText((sourceFile || node.getSourceFile()).text);
  let pos = node.pos;
  const processNode = (child) => {
    addSyntheticNodes(children, pos, child.pos, node);
    children.push(child);
    pos = child.end;
  };
  const processNodes = (nodes) => {
    addSyntheticNodes(children, pos, nodes.pos, node);
    children.push(createSyntaxList(nodes, node));
    pos = nodes.end;
  };
  forEach(node.jsDoc, processNode);
  pos = node.pos;
  node.forEachChild(processNode, processNodes);
  addSyntheticNodes(children, pos, node.end, node);
  scanner.setText(void 0);
  return children;
}
function addSyntheticNodes(nodes, pos, end, parent2) {
  scanner.resetTokenState(pos);
  while (pos < end) {
    const token = scanner.scan();
    const textPos = scanner.getTokenEnd();
    if (textPos <= end) {
      if (token === 80 /* Identifier */) {
        if (hasTabstop(parent2)) {
          continue;
        }
        Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent2.kind)} to have an Identifier in its trivia`);
      }
      nodes.push(createNode(token, pos, textPos, parent2));
    }
    pos = textPos;
    if (token === 1 /* EndOfFileToken */) {
      break;
    }
  }
}
function createSyntaxList(nodes, parent2) {
  const list = createNode(357 /* SyntaxList */, nodes.pos, nodes.end, parent2);
  list._children = [];
  let pos = nodes.pos;
  for (const node of nodes) {
    addSyntheticNodes(list._children, pos, node.pos, parent2);
    list._children.push(node);
    pos = node.end;
  }
  addSyntheticNodes(list._children, pos, nodes.end, parent2);
  return list;
}
var TokenOrIdentifierObject = class {
  constructor(pos, end) {
    this.pos = pos;
    this.end = end;
    this.flags = 0 /* None */;
    this.modifierFlagsCache = 0 /* None */;
    this.transformFlags = 0 /* None */;
    this.parent = void 0;
  }
  getSourceFile() {
    return getSourceFileOfNode(this);
  }
  getStart(sourceFile, includeJsDocComment) {
    return getTokenPosOfNode(this, sourceFile, includeJsDocComment);
  }
  getFullStart() {
    return this.pos;
  }
  getEnd() {
    return this.end;
  }
  getWidth(sourceFile) {
    return this.getEnd() - this.getStart(sourceFile);
  }
  getFullWidth() {
    return this.end - this.pos;
  }
  getLeadingTriviaWidth(sourceFile) {
    return this.getStart(sourceFile) - this.pos;
  }
  getFullText(sourceFile) {
    return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
  }
  getText(sourceFile) {
    if (!sourceFile) {
      sourceFile = this.getSourceFile();
    }
    return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
  }
  getChildCount() {
    return this.getChildren().length;
  }
  getChildAt(index) {
    return this.getChildren()[index];
  }
  getChildren() {
    return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || emptyArray : emptyArray;
  }
  getFirstToken() {
    return void 0;
  }
  getLastToken() {
    return void 0;
  }
  forEachChild() {
    return void 0;
  }
};
var SymbolObject = class {
  constructor(flags, name) {
    this.id = 0;
    this.mergeId = 0;
    this.flags = flags;
    this.escapedName = name;
  }
  getFlags() {
    return this.flags;
  }
  get name() {
    return symbolName(this);
  }
  getEscapedName() {
    return this.escapedName;
  }
  getName() {
    return this.name;
  }
  getDeclarations() {
    return this.declarations;
  }
  getDocumentationComment(checker) {
    if (!this.documentationComment) {
      this.documentationComment = emptyArray;
      if (!this.declarations && isTransientSymbol(this) && this.links.target && isTransientSymbol(this.links.target) && this.links.target.links.tupleLabelDeclaration) {
        const labelDecl = this.links.target.links.tupleLabelDeclaration;
        this.documentationComment = getDocumentationComment([labelDecl], checker);
      } else {
        this.documentationComment = getDocumentationComment(this.declarations, checker);
      }
    }
    return this.documentationComment;
  }
  getContextualDocumentationComment(context, checker) {
    if (context) {
      if (isGetAccessor(context)) {
        if (!this.contextualGetAccessorDocumentationComment) {
          this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker);
        }
        if (length(this.contextualGetAccessorDocumentationComment)) {
          return this.contextualGetAccessorDocumentationComment;
        }
      }
      if (isSetAccessor(context)) {
        if (!this.contextualSetAccessorDocumentationComment) {
          this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker);
        }
        if (length(this.contextualSetAccessorDocumentationComment)) {
          return this.contextualSetAccessorDocumentationComment;
        }
      }
    }
    return this.getDocumentationComment(checker);
  }
  getJsDocTags(checker) {
    if (this.tags === void 0) {
      this.tags = getJsDocTagsOfDeclarations(this.declarations, checker);
    }
    return this.tags;
  }
  getContextualJsDocTags(context, checker) {
    if (context) {
      if (isGetAccessor(context)) {
        if (!this.contextualGetAccessorTags) {
          this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isGetAccessor), checker);
        }
        if (length(this.contextualGetAccessorTags)) {
          return this.contextualGetAccessorTags;
        }
      }
      if (isSetAccessor(context)) {
        if (!this.contextualSetAccessorTags) {
          this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isSetAccessor), checker);
        }
        if (length(this.contextualSetAccessorTags)) {
          return this.contextualSetAccessorTags;
        }
      }
    }
    return this.getJsDocTags(checker);
  }
};
var TokenObject = class extends TokenOrIdentifierObject {
  constructor(kind, pos, end) {
    super(pos, end);
    this.kind = kind;
  }
};
var IdentifierObject = class extends TokenOrIdentifierObject {
  constructor(_kind, pos, end) {
    super(pos, end);
    this.kind = 80 /* Identifier */;
  }
  get text() {
    return idText(this);
  }
};
IdentifierObject.prototype.kind = 80 /* Identifier */;
var PrivateIdentifierObject = class extends TokenOrIdentifierObject {
  constructor(_kind, pos, end) {
    super(pos, end);
    this.kind = 81 /* PrivateIdentifier */;
  }
  get text() {
    return idText(this);
  }
};
PrivateIdentifierObject.prototype.kind = 81 /* PrivateIdentifier */;
var TypeObject = class {
  constructor(checker, flags) {
    this.checker = checker;
    this.flags = flags;
  }
  getFlags() {
    return this.flags;
  }
  getSymbol() {
    return this.symbol;
  }
  getProperties() {
    return this.checker.getPropertiesOfType(this);
  }
  getProperty(propertyName) {
    return this.checker.getPropertyOfType(this, propertyName);
  }
  getApparentProperties() {
    return this.checker.getAugmentedPropertiesOfType(this);
  }
  getCallSignatures() {
    return this.checker.getSignaturesOfType(this, 0 /* Call */);
  }
  getConstructSignatures() {
    return this.checker.getSignaturesOfType(this, 1 /* Construct */);
  }
  getStringIndexType() {
    return this.checker.getIndexTypeOfType(this, 0 /* String */);
  }
  getNumberIndexType() {
    return this.checker.getIndexTypeOfType(this, 1 /* Number */);
  }
  getBaseTypes() {
    return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : void 0;
  }
  isNullableType() {
    return this.checker.isNullableType(this);
  }
  getNonNullableType() {
    return this.checker.getNonNullableType(this);
  }
  getNonOptionalType() {
    return this.checker.getNonOptionalType(this);
  }
  getConstraint() {
    return this.checker.getBaseConstraintOfType(this);
  }
  getDefault() {
    return this.checker.getDefaultFromTypeParameter(this);
  }
  isUnion() {
    return !!(this.flags & 1048576 /* Union */);
  }
  isIntersection() {
    return !!(this.flags & 2097152 /* Intersection */);
  }
  isUnionOrIntersection() {
    return !!(this.flags & 3145728 /* UnionOrIntersection */);
  }
  isLiteral() {
    return !!(this.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */));
  }
  isStringLiteral() {
    return !!(this.flags & 128 /* StringLiteral */);
  }
  isNumberLiteral() {
    return !!(this.flags & 256 /* NumberLiteral */);
  }
  isTypeParameter() {
    return !!(this.flags & 262144 /* TypeParameter */);
  }
  isClassOrInterface() {
    return !!(getObjectFlags(this) & 3 /* ClassOrInterface */);
  }
  isClass() {
    return !!(getObjectFlags(this) & 1 /* Class */);
  }
  isIndexType() {
    return !!(this.flags & 4194304 /* Index */);
  }
  /**
   * This polyfills `referenceType.typeArguments` for API consumers
   */
  get typeArguments() {
    if (getObjectFlags(this) & 4 /* Reference */) {
      return this.checker.getTypeArguments(this);
    }
    return void 0;
  }
};
var SignatureObject = class {
  // same
  constructor(checker, flags) {
    this.checker = checker;
    this.flags = flags;
  }
  getDeclaration() {
    return this.declaration;
  }
  getTypeParameters() {
    return this.typeParameters;
  }
  getParameters() {
    return this.parameters;
  }
  getReturnType() {
    return this.checker.getReturnTypeOfSignature(this);
  }
  getTypeParameterAtPosition(pos) {
    const type = this.checker.getParameterType(this, pos);
    if (type.isIndexType() && isThisTypeParameter(type.type)) {
      const constraint = type.type.getConstraint();
      if (constraint) {
        return this.checker.getIndexType(constraint);
      }
    }
    return type;
  }
  getDocumentationComment() {
    return this.documentationComment || (this.documentationComment = getDocumentationComment(singleElementArray(this.declaration), this.checker));
  }
  getJsDocTags() {
    return this.jsDocTags || (this.jsDocTags = getJsDocTagsOfDeclarations(singleElementArray(this.declaration), this.checker));
  }
};
function hasJSDocInheritDocTag(node) {
  return getJSDocTags(node).some((tag) => tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc");
}
function getJsDocTagsOfDeclarations(declarations, checker) {
  if (!declarations)
    return emptyArray;
  let tags = ts_JsDoc_exports.getJsDocTagsFromDeclarations(declarations, checker);
  if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) {
    const seenSymbols = /* @__PURE__ */ new Set();
    for (const declaration of declarations) {
      const inheritedTags = findBaseOfDeclaration(checker, declaration, (symbol) => {
        var _a;
        if (!seenSymbols.has(symbol)) {
          seenSymbols.add(symbol);
          if (declaration.kind === 176 /* GetAccessor */ || declaration.kind === 177 /* SetAccessor */) {
            return symbol.getContextualJsDocTags(declaration, checker);
          }
          return ((_a = symbol.declarations) == null ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : void 0;
        }
      });
      if (inheritedTags) {
        tags = [...inheritedTags, ...tags];
      }
    }
  }
  return tags;
}
function getDocumentationComment(declarations, checker) {
  if (!declarations)
    return emptyArray;
  let doc = ts_JsDoc_exports.getJsDocCommentsFromDeclarations(declarations, checker);
  if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) {
    const seenSymbols = /* @__PURE__ */ new Set();
    for (const declaration of declarations) {
      const inheritedDocs = findBaseOfDeclaration(checker, declaration, (symbol) => {
        if (!seenSymbols.has(symbol)) {
          seenSymbols.add(symbol);
          if (declaration.kind === 176 /* GetAccessor */ || declaration.kind === 177 /* SetAccessor */) {
            return symbol.getContextualDocumentationComment(declaration, checker);
          }
          return symbol.getDocumentationComment(checker);
        }
      });
      if (inheritedDocs)
        doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc);
    }
  }
  return doc;
}
function findBaseOfDeclaration(checker, declaration, cb) {
  var _a;
  const classOrInterfaceDeclaration = ((_a = declaration.parent) == null ? void 0 : _a.kind) === 175 /* Constructor */ ? declaration.parent.parent : declaration.parent;
  if (!classOrInterfaceDeclaration)
    return;
  const isStaticMember = hasStaticModifier(declaration);
  return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), (superTypeNode) => {
    const baseType = checker.getTypeAtLocation(superTypeNode);
    const type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType;
    const symbol = checker.getPropertyOfType(type, declaration.symbol.name);
    return symbol ? cb(symbol) : void 0;
  });
}
var SourceFileObject = class extends NodeObject {
  constructor(kind, pos, end) {
    super(kind, pos, end);
    this.kind = 311 /* SourceFile */;
  }
  update(newText, textChangeRange) {
    return updateSourceFile(this, newText, textChangeRange);
  }
  getLineAndCharacterOfPosition(position) {
    return getLineAndCharacterOfPosition(this, position);
  }
  getLineStarts() {
    return getLineStarts(this);
  }
  getPositionOfLineAndCharacter(line, character, allowEdits) {
    return computePositionOfLineAndCharacter(getLineStarts(this), line, character, this.text, allowEdits);
  }
  getLineEndOfPosition(pos) {
    const { line } = this.getLineAndCharacterOfPosition(pos);
    const lineStarts = this.getLineStarts();
    let lastCharPos;
    if (line + 1 >= lineStarts.length) {
      lastCharPos = this.getEnd();
    }
    if (!lastCharPos) {
      lastCharPos = lineStarts[line + 1] - 1;
    }
    const fullText = this.getFullText();
    return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos;
  }
  getNamedDeclarations() {
    if (!this.namedDeclarations) {
      this.namedDeclarations = this.computeNamedDeclarations();
    }
    return this.namedDeclarations;
  }
  computeNamedDeclarations() {
    const result = createMultiMap();
    this.forEachChild(visit);
    return result;
    function addDeclaration(declaration) {
      const name = getDeclarationName(declaration);
      if (name) {
        result.add(name, declaration);
      }
    }
    function getDeclarations(name) {
      let declarations = result.get(name);
      if (!declarations) {
        result.set(name, declarations = []);
      }
      return declarations;
    }
    function getDeclarationName(declaration) {
      const name = getNonAssignedNameOfDeclaration(declaration);
      return name && (isComputedPropertyName(name) && isPropertyAccessExpression(name.expression) ? name.expression.name.text : isPropertyName(name) ? getNameFromPropertyName(name) : void 0);
    }
    function visit(node) {
      switch (node.kind) {
        case 261 /* FunctionDeclaration */:
        case 217 /* FunctionExpression */:
        case 173 /* MethodDeclaration */:
        case 172 /* MethodSignature */:
          const functionDeclaration = node;
          const declarationName = getDeclarationName(functionDeclaration);
          if (declarationName) {
            const declarations = getDeclarations(declarationName);
            const lastDeclaration = lastOrUndefined(declarations);
            if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
              if (functionDeclaration.body && !lastDeclaration.body) {
                declarations[declarations.length - 1] = functionDeclaration;
              }
            } else {
              declarations.push(functionDeclaration);
            }
          }
          forEachChild(node, visit);
          break;
        case 262 /* ClassDeclaration */:
        case 230 /* ClassExpression */:
        case 263 /* InterfaceDeclaration */:
        case 264 /* TypeAliasDeclaration */:
        case 265 /* EnumDeclaration */:
        case 266 /* ModuleDeclaration */:
        case 270 /* ImportEqualsDeclaration */:
        case 280 /* ExportSpecifier */:
        case 275 /* ImportSpecifier */:
        case 272 /* ImportClause */:
        case 273 /* NamespaceImport */:
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
        case 186 /* TypeLiteral */:
          addDeclaration(node);
          forEachChild(node, visit);
          break;
        case 168 /* Parameter */:
          if (!hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) {
            break;
          }
        case 259 /* VariableDeclaration */:
        case 207 /* BindingElement */: {
          const decl = node;
          if (isBindingPattern(decl.name)) {
            forEachChild(decl.name, visit);
            break;
          }
          if (decl.initializer) {
            visit(decl.initializer);
          }
        }
        case 305 /* EnumMember */:
        case 171 /* PropertyDeclaration */:
        case 170 /* PropertySignature */:
          addDeclaration(node);
          break;
        case 277 /* ExportDeclaration */:
          const exportDeclaration = node;
          if (exportDeclaration.exportClause) {
            if (isNamedExports(exportDeclaration.exportClause)) {
              forEach(exportDeclaration.exportClause.elements, visit);
            } else {
              visit(exportDeclaration.exportClause.name);
            }
          }
          break;
        case 271 /* ImportDeclaration */:
          const importClause = node.importClause;
          if (importClause) {
            if (importClause.name) {
              addDeclaration(importClause.name);
            }
            if (importClause.namedBindings) {
              if (importClause.namedBindings.kind === 273 /* NamespaceImport */) {
                addDeclaration(importClause.namedBindings);
              } else {
                forEach(importClause.namedBindings.elements, visit);
              }
            }
          }
          break;
        case 225 /* BinaryExpression */:
          if (getAssignmentDeclarationKind(node) !== 0 /* None */) {
            addDeclaration(node);
          }
        default:
          forEachChild(node, visit);
      }
    }
  }
};
var SourceMapSourceObject = class {
  constructor(fileName, text, skipTrivia2) {
    this.fileName = fileName;
    this.text = text;
    this.skipTrivia = skipTrivia2;
  }
  getLineAndCharacterOfPosition(pos) {
    return getLineAndCharacterOfPosition(this, pos);
  }
};
function getServicesObjectAllocator() {
  return {
    getNodeConstructor: () => NodeObject,
    getTokenConstructor: () => TokenObject,
    getIdentifierConstructor: () => IdentifierObject,
    getPrivateIdentifierConstructor: () => PrivateIdentifierObject,
    getSourceFileConstructor: () => SourceFileObject,
    getSymbolConstructor: () => SymbolObject,
    getTypeConstructor: () => TypeObject,
    getSignatureConstructor: () => SignatureObject,
    getSourceMapSourceConstructor: () => SourceMapSourceObject
  };
}
function toEditorSettings(optionsAsMap) {
  let allPropertiesAreCamelCased = true;
  for (const key in optionsAsMap) {
    if (hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
      allPropertiesAreCamelCased = false;
      break;
    }
  }
  if (allPropertiesAreCamelCased) {
    return optionsAsMap;
  }
  const settings = {};
  for (const key in optionsAsMap) {
    if (hasProperty(optionsAsMap, key)) {
      const newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
      settings[newKey] = optionsAsMap[key];
    }
  }
  return settings;
}
function isCamelCase(s) {
  return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
}
function displayPartsToString(displayParts) {
  if (displayParts) {
    return map(displayParts, (displayPart2) => displayPart2.text).join("");
  }
  return "";
}
function getDefaultCompilerOptions2() {
  return {
    target: 1 /* ES5 */,
    jsx: 1 /* Preserve */
  };
}
function getSupportedCodeFixes() {
  return ts_codefix_exports.getSupportedErrorCodes();
}
var SyntaxTreeCache = class {
  constructor(host) {
    this.host = host;
  }
  getCurrentSourceFile(fileName) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const scriptSnapshot = this.host.getScriptSnapshot(fileName);
    if (!scriptSnapshot) {
      throw new Error("Could not find file: '" + fileName + "'.");
    }
    const scriptKind = getScriptKind(fileName, this.host);
    const version2 = this.host.getScriptVersion(fileName);
    let sourceFile;
    if (this.currentFileName !== fileName) {
      const options = {
        languageVersion: 99 /* Latest */,
        impliedNodeFormat: getImpliedNodeFormatForFile(
          toPath(fileName, this.host.getCurrentDirectory(), ((_c = (_b = (_a = this.host).getCompilerHost) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.getCanonicalFileName) || hostGetCanonicalFileName(this.host)),
          (_h = (_g = (_f = (_e = (_d = this.host).getCompilerHost) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.getModuleResolutionCache) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getPackageJsonInfoCache(),
          this.host,
          this.host.getCompilationSettings()
        ),
        setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings())
      };
      sourceFile = createLanguageServiceSourceFile(
        fileName,
        scriptSnapshot,
        options,
        version2,
        /*setNodeParents*/
        true,
        scriptKind
      );
    } else if (this.currentFileVersion !== version2) {
      const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot);
      sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version2, editRange);
    }
    if (sourceFile) {
      this.currentFileVersion = version2;
      this.currentFileName = fileName;
      this.currentFileScriptSnapshot = scriptSnapshot;
      this.currentSourceFile = sourceFile;
    }
    return this.currentSourceFile;
  }
};
function setSourceFileFields(sourceFile, scriptSnapshot, version2) {
  sourceFile.version = version2;
  sourceFile.scriptSnapshot = scriptSnapshot;
}
function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTargetOrOptions, version2, setNodeParents, scriptKind) {
  const sourceFile = createSourceFile(fileName, getSnapshotText(scriptSnapshot), scriptTargetOrOptions, setNodeParents, scriptKind);
  setSourceFileFields(sourceFile, scriptSnapshot, version2);
  return sourceFile;
}
function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version2, textChangeRange, aggressiveChecks) {
  if (textChangeRange) {
    if (version2 !== sourceFile.version) {
      let newText;
      const prefix = textChangeRange.span.start !== 0 ? sourceFile.text.substr(0, textChangeRange.span.start) : "";
      const suffix = textSpanEnd(textChangeRange.span) !== sourceFile.text.length ? sourceFile.text.substr(textSpanEnd(textChangeRange.span)) : "";
      if (textChangeRange.newLength === 0) {
        newText = prefix && suffix ? prefix + suffix : prefix || suffix;
      } else {
        const changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength);
        newText = prefix && suffix ? prefix + changedText + suffix : prefix ? prefix + changedText : changedText + suffix;
      }
      const newSourceFile = updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
      setSourceFileFields(newSourceFile, scriptSnapshot, version2);
      newSourceFile.nameTable = void 0;
      if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
        if (sourceFile.scriptSnapshot.dispose) {
          sourceFile.scriptSnapshot.dispose();
        }
        sourceFile.scriptSnapshot = void 0;
      }
      return newSourceFile;
    }
  }
  const options = {
    languageVersion: sourceFile.languageVersion,
    impliedNodeFormat: sourceFile.impliedNodeFormat,
    setExternalModuleIndicator: sourceFile.setExternalModuleIndicator
  };
  return createLanguageServiceSourceFile(
    sourceFile.fileName,
    scriptSnapshot,
    options,
    version2,
    /*setNodeParents*/
    true,
    sourceFile.scriptKind
  );
}
var NoopCancellationToken = {
  isCancellationRequested: returnFalse,
  throwIfCancellationRequested: noop
};
var CancellationTokenObject = class {
  constructor(cancellationToken) {
    this.cancellationToken = cancellationToken;
  }
  isCancellationRequested() {
    return this.cancellationToken.isCancellationRequested();
  }
  throwIfCancellationRequested() {
    var _a;
    if (this.isCancellationRequested()) {
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { kind: "CancellationTokenObject" });
      throw new OperationCanceledException();
    }
  }
};
var ThrottledCancellationToken = class {
  constructor(hostCancellationToken, throttleWaitMilliseconds = 20) {
    this.hostCancellationToken = hostCancellationToken;
    this.throttleWaitMilliseconds = throttleWaitMilliseconds;
    // Store when we last tried to cancel.  Checking cancellation can be expensive (as we have
    // to marshall over to the host layer).  So we only bother actually checking once enough
    // time has passed.
    this.lastCancellationCheckTime = 0;
  }
  isCancellationRequested() {
    const time = timestamp();
    const duration = Math.abs(time - this.lastCancellationCheckTime);
    if (duration >= this.throttleWaitMilliseconds) {
      this.lastCancellationCheckTime = time;
      return this.hostCancellationToken.isCancellationRequested();
    }
    return false;
  }
  throwIfCancellationRequested() {
    var _a;
    if (this.isCancellationRequested()) {
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { kind: "ThrottledCancellationToken" });
      throw new OperationCanceledException();
    }
  }
};
var invalidOperationsInPartialSemanticMode = [
  "getSemanticDiagnostics",
  "getSuggestionDiagnostics",
  "getCompilerOptionsDiagnostics",
  "getSemanticClassifications",
  "getEncodedSemanticClassifications",
  "getCodeFixesAtPosition",
  "getCombinedCodeFix",
  "applyCodeActionCommand",
  "organizeImports",
  "getEditsForFileRename",
  "getEmitOutput",
  "getApplicableRefactors",
  "getEditsForRefactor",
  "prepareCallHierarchy",
  "provideCallHierarchyIncomingCalls",
  "provideCallHierarchyOutgoingCalls",
  "provideInlayHints",
  "getSupportedCodeFixes"
];
var invalidOperationsInSyntacticMode = [
  ...invalidOperationsInPartialSemanticMode,
  "getCompletionsAtPosition",
  "getCompletionEntryDetails",
  "getCompletionEntrySymbol",
  "getSignatureHelpItems",
  "getQuickInfoAtPosition",
  "getDefinitionAtPosition",
  "getDefinitionAndBoundSpan",
  "getImplementationAtPosition",
  "getTypeDefinitionAtPosition",
  "getReferencesAtPosition",
  "findReferences",
  "getDocumentHighlights",
  "getNavigateToItems",
  "getRenameInfo",
  "findRenameLocations",
  "getApplicableRefactors"
];
function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()), syntaxOnlyOrLanguageServiceMode) {
  var _a;
  let languageServiceMode;
  if (syntaxOnlyOrLanguageServiceMode === void 0) {
    languageServiceMode = 0 /* Semantic */;
  } else if (typeof syntaxOnlyOrLanguageServiceMode === "boolean") {
    languageServiceMode = syntaxOnlyOrLanguageServiceMode ? 2 /* Syntactic */ : 0 /* Semantic */;
  } else {
    languageServiceMode = syntaxOnlyOrLanguageServiceMode;
  }
  const syntaxTreeCache = new SyntaxTreeCache(host);
  let program;
  let lastProjectVersion;
  let lastTypesRootVersion = 0;
  const cancellationToken = host.getCancellationToken ? new CancellationTokenObject(host.getCancellationToken()) : NoopCancellationToken;
  const currentDirectory = host.getCurrentDirectory();
  maybeSetLocalizedDiagnosticMessages((_a = host.getLocalizedDiagnosticMessages) == null ? void 0 : _a.bind(host));
  function log(message) {
    if (host.log) {
      host.log(message);
    }
  }
  const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host);
  const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
  const sourceMapper = getSourceMapper({
    useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
    getCurrentDirectory: () => currentDirectory,
    getProgram,
    fileExists: maybeBind(host, host.fileExists),
    readFile: maybeBind(host, host.readFile),
    getDocumentPositionMapper: maybeBind(host, host.getDocumentPositionMapper),
    getSourceFileLike: maybeBind(host, host.getSourceFileLike),
    log
  });
  function getValidSourceFile(fileName) {
    const sourceFile = program.getSourceFile(fileName);
    if (!sourceFile) {
      const error = new Error(`Could not find source file: '${fileName}'.`);
      error.ProgramFiles = program.getSourceFiles().map((f) => f.fileName);
      throw error;
    }
    return sourceFile;
  }
  function synchronizeHostData() {
    var _a2, _b, _c;
    Debug.assert(languageServiceMode !== 2 /* Syntactic */);
    if (host.getProjectVersion) {
      const hostProjectVersion = host.getProjectVersion();
      if (hostProjectVersion) {
        if (lastProjectVersion === hostProjectVersion && !((_a2 = host.hasChangedAutomaticTypeDirectiveNames) == null ? void 0 : _a2.call(host))) {
          return;
        }
        lastProjectVersion = hostProjectVersion;
      }
    }
    const typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
    if (lastTypesRootVersion !== typeRootsVersion) {
      log("TypeRoots version has changed; provide new program");
      program = void 0;
      lastTypesRootVersion = typeRootsVersion;
    }
    const rootFileNames = host.getScriptFileNames().slice();
    const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2();
    const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse;
    const hasInvalidatedLibResolutions = maybeBind(host, host.hasInvalidatedLibResolutions) || returnFalse;
    const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames);
    const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host);
    let parsedCommandLines;
    let compilerHost = {
      getSourceFile: getOrCreateSourceFile,
      getSourceFileByPath: getOrCreateSourceFileByPath,
      getCancellationToken: () => cancellationToken,
      getCanonicalFileName,
      useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
      getNewLine: () => getNewLineCharacter(newSettings),
      getDefaultLibFileName: (options2) => host.getDefaultLibFileName(options2),
      writeFile: noop,
      getCurrentDirectory: () => currentDirectory,
      fileExists: (fileName) => host.fileExists(fileName),
      readFile: (fileName) => host.readFile && host.readFile(fileName),
      getSymlinkCache: maybeBind(host, host.getSymlinkCache),
      realpath: maybeBind(host, host.realpath),
      directoryExists: (directoryName) => {
        return directoryProbablyExists(directoryName, host);
      },
      getDirectories: (path) => {
        return host.getDirectories ? host.getDirectories(path) : [];
      },
      readDirectory: (path, extensions, exclude, include, depth) => {
        Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
        return host.readDirectory(path, extensions, exclude, include, depth);
      },
      onReleaseOldSourceFile,
      onReleaseParsedCommandLine,
      hasInvalidatedResolutions,
      hasInvalidatedLibResolutions,
      hasChangedAutomaticTypeDirectiveNames,
      trace: maybeBind(host, host.trace),
      resolveModuleNames: maybeBind(host, host.resolveModuleNames),
      getModuleResolutionCache: maybeBind(host, host.getModuleResolutionCache),
      createHash: maybeBind(host, host.createHash),
      resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives),
      resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals),
      resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences),
      resolveLibrary: maybeBind(host, host.resolveLibrary),
      useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect),
      getParsedCommandLine
    };
    const originalGetSourceFile = compilerHost.getSourceFile;
    const { getSourceFileWithCache } = changeCompilerHostLikeToUseCache(
      compilerHost,
      (fileName) => toPath(fileName, currentDirectory, getCanonicalFileName),
      (...args) => originalGetSourceFile.call(compilerHost, ...args)
    );
    compilerHost.getSourceFile = getSourceFileWithCache;
    (_c = host.setCompilerHost) == null ? void 0 : _c.call(host, compilerHost);
    const parseConfigHost = {
      useCaseSensitiveFileNames,
      fileExists: (fileName) => compilerHost.fileExists(fileName),
      readFile: (fileName) => compilerHost.readFile(fileName),
      readDirectory: (...args) => compilerHost.readDirectory(...args),
      trace: compilerHost.trace,
      getCurrentDirectory: compilerHost.getCurrentDirectory,
      onUnRecoverableConfigFileDiagnostic: noop
    };
    const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
    let releasedScriptKinds = /* @__PURE__ */ new Set();
    if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) {
      compilerHost = void 0;
      parsedCommandLines = void 0;
      releasedScriptKinds = void 0;
      return;
    }
    const options = {
      rootNames: rootFileNames,
      options: newSettings,
      host: compilerHost,
      oldProgram: program,
      projectReferences
    };
    program = createProgram(options);
    compilerHost = void 0;
    parsedCommandLines = void 0;
    releasedScriptKinds = void 0;
    sourceMapper.clearCache();
    program.getTypeChecker();
    return;
    function getParsedCommandLine(fileName) {
      const path = toPath(fileName, currentDirectory, getCanonicalFileName);
      const existing = parsedCommandLines == null ? void 0 : parsedCommandLines.get(path);
      if (existing !== void 0)
        return existing || void 0;
      const result = host.getParsedCommandLine ? host.getParsedCommandLine(fileName) : getParsedCommandLineOfConfigFileUsingSourceFile(fileName);
      (parsedCommandLines || (parsedCommandLines = /* @__PURE__ */ new Map())).set(path, result || false);
      return result;
    }
    function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) {
      const result = getOrCreateSourceFile(configFileName, 100 /* JSON */);
      if (!result)
        return void 0;
      result.path = toPath(configFileName, currentDirectory, getCanonicalFileName);
      result.resolvedPath = result.path;
      result.originalFileName = result.fileName;
      return parseJsonSourceFileConfigFileContent(
        result,
        parseConfigHost,
        getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory),
        /*existingOptions*/
        void 0,
        getNormalizedAbsolutePath(configFileName, currentDirectory)
      );
    }
    function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) {
      var _a3;
      if (host.getParsedCommandLine) {
        (_a3 = host.onReleaseParsedCommandLine) == null ? void 0 : _a3.call(host, configFileName, oldResolvedRef, oldOptions);
      } else if (oldResolvedRef) {
        onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions);
      }
    }
    function onReleaseOldSourceFile(oldSourceFile, oldOptions) {
      const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions);
      documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat);
    }
    function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) {
      return getOrCreateSourceFileByPath(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile);
    }
    function getOrCreateSourceFileByPath(fileName, path, languageVersionOrOptions, _onError, shouldCreateNewSourceFile) {
      Debug.assert(compilerHost, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
      const scriptSnapshot = host.getScriptSnapshot(fileName);
      if (!scriptSnapshot) {
        return void 0;
      }
      const scriptKind = getScriptKind(fileName, host);
      const scriptVersion = host.getScriptVersion(fileName);
      if (!shouldCreateNewSourceFile) {
        const oldSourceFile = program && program.getSourceFileByPath(path);
        if (oldSourceFile) {
          if (scriptKind === oldSourceFile.scriptKind || releasedScriptKinds.has(oldSourceFile.resolvedPath)) {
            return documentRegistry.updateDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions);
          } else {
            documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat);
            releasedScriptKinds.add(oldSourceFile.resolvedPath);
          }
        }
      }
      return documentRegistry.acquireDocumentWithKey(fileName, path, host, documentRegistryBucketKey, scriptSnapshot, scriptVersion, scriptKind, languageVersionOrOptions);
    }
  }
  function getProgram() {
    if (languageServiceMode === 2 /* Syntactic */) {
      Debug.assert(program === void 0);
      return void 0;
    }
    synchronizeHostData();
    return program;
  }
  function getAutoImportProvider() {
    var _a2;
    return (_a2 = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host);
  }
  function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) {
    const checker = program.getTypeChecker();
    const symbol = getSymbolForProgram();
    if (!symbol)
      return false;
    for (const referencedSymbol of referencedSymbols) {
      for (const ref of referencedSymbol.references) {
        const refNode = getNodeForSpan(ref);
        Debug.assertIsDefined(refNode);
        if (knownSymbolSpans.has(ref) || ts_FindAllReferences_exports.isDeclarationOfSymbol(refNode, symbol)) {
          knownSymbolSpans.add(ref);
          ref.isDefinition = true;
          const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists));
          if (mappedSpan) {
            knownSymbolSpans.add(mappedSpan);
          }
        } else {
          ref.isDefinition = false;
        }
      }
    }
    return true;
    function getSymbolForProgram() {
      for (const referencedSymbol of referencedSymbols) {
        for (const ref of referencedSymbol.references) {
          if (knownSymbolSpans.has(ref)) {
            const refNode = getNodeForSpan(ref);
            Debug.assertIsDefined(refNode);
            return checker.getSymbolAtLocation(refNode);
          }
          const mappedSpan = getMappedDocumentSpan(ref, sourceMapper, maybeBind(host, host.fileExists));
          if (mappedSpan && knownSymbolSpans.has(mappedSpan)) {
            const refNode = getNodeForSpan(mappedSpan);
            if (refNode) {
              return checker.getSymbolAtLocation(refNode);
            }
          }
        }
      }
      return void 0;
    }
    function getNodeForSpan(docSpan) {
      const sourceFile = program.getSourceFile(docSpan.fileName);
      if (!sourceFile)
        return void 0;
      const rawNode = getTouchingPropertyName(sourceFile, docSpan.textSpan.start);
      const adjustedNode = ts_FindAllReferences_exports.Core.getAdjustedNode(rawNode, { use: ts_FindAllReferences_exports.FindReferencesUse.References });
      return adjustedNode;
    }
  }
  function cleanupSemanticCache() {
    program = void 0;
  }
  function dispose() {
    if (program) {
      const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions());
      forEach(program.getSourceFiles(), (f) => documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat));
      program = void 0;
    }
    host = void 0;
  }
  function getSyntacticDiagnostics(fileName) {
    synchronizeHostData();
    return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice();
  }
  function getSemanticDiagnostics(fileName) {
    synchronizeHostData();
    const targetSourceFile = getValidSourceFile(fileName);
    const semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
    if (!getEmitDeclarations(program.getCompilerOptions())) {
      return semanticDiagnostics.slice();
    }
    const declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
    return [...semanticDiagnostics, ...declarationDiagnostics];
  }
  function getSuggestionDiagnostics(fileName) {
    synchronizeHostData();
    return computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken);
  }
  function getCompilerOptionsDiagnostics() {
    synchronizeHostData();
    return [...program.getOptionsDiagnostics(cancellationToken), ...program.getGlobalDiagnostics(cancellationToken)];
  }
  function getCompletionsAtPosition2(fileName, position, options = emptyOptions, formattingSettings) {
    const fullPreferences = {
      ...identity(options),
      // avoid excess property check
      includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports,
      includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions
    };
    synchronizeHostData();
    return ts_Completions_exports.getCompletionsAtPosition(
      host,
      program,
      log,
      getValidSourceFile(fileName),
      position,
      fullPreferences,
      options.triggerCharacter,
      options.triggerKind,
      cancellationToken,
      formattingSettings && ts_formatting_exports.getFormatContext(formattingSettings, host),
      options.includeSymbol
    );
  }
  function getCompletionEntryDetails2(fileName, position, name, formattingOptions, source, preferences = emptyOptions, data) {
    synchronizeHostData();
    return ts_Completions_exports.getCompletionEntryDetails(
      program,
      log,
      getValidSourceFile(fileName),
      position,
      { name, source, data },
      host,
      formattingOptions && ts_formatting_exports.getFormatContext(formattingOptions, host),
      // TODO: GH#18217
      preferences,
      cancellationToken
    );
  }
  function getCompletionEntrySymbol2(fileName, position, name, source, preferences = emptyOptions) {
    synchronizeHostData();
    return ts_Completions_exports.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name, source }, host, preferences);
  }
  function getQuickInfoAtPosition(fileName, position) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const node = getTouchingPropertyName(sourceFile, position);
    if (node === sourceFile) {
      return void 0;
    }
    const typeChecker = program.getTypeChecker();
    const nodeForQuickInfo = getNodeForQuickInfo(node);
    const symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker);
    if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
      const type = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : void 0;
      return type && {
        kind: "" /* unknown */,
        kindModifiers: "" /* none */,
        textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile),
        displayParts: typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => typeToDisplayParts(typeChecker2, type, getContainerNode(nodeForQuickInfo))),
        documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : void 0,
        tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : void 0
      };
    }
    const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken(
      cancellationToken,
      (typeChecker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)
    );
    return {
      kind: symbolKind,
      kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol),
      textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile),
      displayParts,
      documentation,
      tags
    };
  }
  function getNodeForQuickInfo(node) {
    if (isNewExpression(node.parent) && node.pos === node.parent.pos) {
      return node.parent.expression;
    }
    if (isNamedTupleMember(node.parent) && node.pos === node.parent.pos) {
      return node.parent;
    }
    if (isImportMeta(node.parent) && node.parent.name === node) {
      return node.parent;
    }
    if (isJsxNamespacedName(node.parent)) {
      return node.parent;
    }
    return node;
  }
  function shouldGetType(sourceFile, node, position) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return !isLabelName(node) && !isTagName(node) && !isConstTypeReference(node.parent);
      case 210 /* PropertyAccessExpression */:
      case 165 /* QualifiedName */:
        return !isInComment(sourceFile, position);
      case 110 /* ThisKeyword */:
      case 196 /* ThisType */:
      case 108 /* SuperKeyword */:
      case 201 /* NamedTupleMember */:
        return true;
      case 235 /* MetaProperty */:
        return isImportMeta(node);
      default:
        return false;
    }
  }
  function getDefinitionAtPosition2(fileName, position, searchOtherFilesOnly, stopAtAlias) {
    synchronizeHostData();
    return ts_GoToDefinition_exports.getDefinitionAtPosition(program, getValidSourceFile(fileName), position, searchOtherFilesOnly, stopAtAlias);
  }
  function getDefinitionAndBoundSpan2(fileName, position) {
    synchronizeHostData();
    return ts_GoToDefinition_exports.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position);
  }
  function getTypeDefinitionAtPosition2(fileName, position) {
    synchronizeHostData();
    return ts_GoToDefinition_exports.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
  }
  function getImplementationAtPosition(fileName, position) {
    synchronizeHostData();
    return ts_FindAllReferences_exports.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
  }
  function getDocumentHighlights(fileName, position, filesToSearch) {
    const normalizedFileName = normalizePath(fileName);
    Debug.assert(filesToSearch.some((f) => normalizePath(f) === normalizedFileName));
    synchronizeHostData();
    const sourceFilesToSearch = mapDefined(filesToSearch, (fileName2) => program.getSourceFile(fileName2));
    const sourceFile = getValidSourceFile(fileName);
    return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
  }
  function findRenameLocations(fileName, position, findInStrings, findInComments, preferences) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position));
    if (!ts_Rename_exports.nodeIsEligibleForRename(node))
      return void 0;
    if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) {
      const { openingElement, closingElement } = node.parent.parent;
      return [openingElement, closingElement].map((node2) => {
        const textSpan = createTextSpanFromNode(node2.tagName, sourceFile);
        return {
          fileName: sourceFile.fileName,
          textSpan,
          ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, node2.parent)
        };
      });
    } else {
      const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions);
      const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename;
      return getReferencesWorker2(
        node,
        position,
        { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename },
        (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)
      );
    }
  }
  function getReferencesAtPosition(fileName, position) {
    synchronizeHostData();
    return getReferencesWorker2(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry);
  }
  function getReferencesWorker2(node, position, options, cb) {
    synchronizeHostData();
    const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles();
    return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb);
  }
  function findReferences(fileName, position) {
    synchronizeHostData();
    return ts_FindAllReferences_exports.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
  }
  function getFileReferences(fileName) {
    synchronizeHostData();
    return ts_FindAllReferences_exports.Core.getReferencesForFileName(fileName, program, program.getSourceFiles()).map(ts_FindAllReferences_exports.toReferenceEntry);
  }
  function getNavigateToItems2(searchValue, maxResultCount, fileName, excludeDtsFiles = false) {
    synchronizeHostData();
    const sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
    return getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
  }
  function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const customTransformers = host.getCustomTransformers && host.getCustomTransformers();
    return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit);
  }
  function getSignatureHelpItems2(fileName, position, { triggerReason } = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    return ts_SignatureHelp_exports.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
  }
  function getNonBoundSourceFile(fileName) {
    return syntaxTreeCache.getCurrentSourceFile(fileName);
  }
  function getNameOrDottedNameSpan(fileName, startPos, _endPos) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const node = getTouchingPropertyName(sourceFile, startPos);
    if (node === sourceFile) {
      return void 0;
    }
    switch (node.kind) {
      case 210 /* PropertyAccessExpression */:
      case 165 /* QualifiedName */:
      case 11 /* StringLiteral */:
      case 97 /* FalseKeyword */:
      case 112 /* TrueKeyword */:
      case 106 /* NullKeyword */:
      case 108 /* SuperKeyword */:
      case 110 /* ThisKeyword */:
      case 196 /* ThisType */:
      case 80 /* Identifier */:
        break;
      default:
        return void 0;
    }
    let nodeForStartPos = node;
    while (true) {
      if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) {
        nodeForStartPos = nodeForStartPos.parent;
      } else if (isNameOfModuleDeclaration(nodeForStartPos)) {
        if (nodeForStartPos.parent.parent.kind === 266 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
          nodeForStartPos = nodeForStartPos.parent.parent.name;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    return createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd());
  }
  function getBreakpointStatementAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    return ts_BreakpointResolver_exports.spanInSourceFileAtLocation(sourceFile, position);
  }
  function getNavigationBarItems2(fileName) {
    return getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
  }
  function getNavigationTree2(fileName) {
    return getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
  }
  function getSemanticClassifications3(fileName, span, format) {
    synchronizeHostData();
    const responseFormat = format || "original" /* Original */;
    if (responseFormat === "2020" /* TwentyTwenty */) {
      return getSemanticClassifications2(program, cancellationToken, getValidSourceFile(fileName), span);
    } else {
      return getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
    }
  }
  function getEncodedSemanticClassifications3(fileName, span, format) {
    synchronizeHostData();
    const responseFormat = format || "original" /* Original */;
    if (responseFormat === "original" /* Original */) {
      return getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
    } else {
      return getEncodedSemanticClassifications2(program, cancellationToken, getValidSourceFile(fileName), span);
    }
  }
  function getSyntacticClassifications2(fileName, span) {
    return getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
  }
  function getEncodedSyntacticClassifications2(fileName, span) {
    return getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
  }
  function getOutliningSpans(fileName) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    return ts_OutliningElementsCollector_exports.collectElements(sourceFile, cancellationToken);
  }
  const braceMatching = new Map(Object.entries({
    [19 /* OpenBraceToken */]: 20 /* CloseBraceToken */,
    [21 /* OpenParenToken */]: 22 /* CloseParenToken */,
    [23 /* OpenBracketToken */]: 24 /* CloseBracketToken */,
    [32 /* GreaterThanToken */]: 30 /* LessThanToken */
  }));
  braceMatching.forEach((value, key) => braceMatching.set(value.toString(), Number(key)));
  function getBraceMatchingAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const token = getTouchingToken(sourceFile, position);
    const matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : void 0;
    const match = matchKind && findChildOfKind(token.parent, matchKind, sourceFile);
    return match ? [createTextSpanFromNode(token, sourceFile), createTextSpanFromNode(match, sourceFile)].sort((a, b) => a.start - b.start) : emptyArray;
  }
  function getIndentationAtPosition(fileName, position, editorOptions) {
    let start2 = timestamp();
    const settings = toEditorSettings(editorOptions);
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    log("getIndentationAtPosition: getCurrentSourceFile: " + (timestamp() - start2));
    start2 = timestamp();
    const result = ts_formatting_exports.SmartIndenter.getIndentation(position, sourceFile, settings);
    log("getIndentationAtPosition: computeIndentation  : " + (timestamp() - start2));
    return result;
  }
  function getFormattingEditsForRange(fileName, start2, end, options) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    return ts_formatting_exports.formatSelection(start2, end, sourceFile, ts_formatting_exports.getFormatContext(toEditorSettings(options), host));
  }
  function getFormattingEditsForDocument(fileName, options) {
    return ts_formatting_exports.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts_formatting_exports.getFormatContext(toEditorSettings(options), host));
  }
  function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const formatContext = ts_formatting_exports.getFormatContext(toEditorSettings(options), host);
    if (!isInComment(sourceFile, position)) {
      switch (key) {
        case "{":
          return ts_formatting_exports.formatOnOpeningCurly(position, sourceFile, formatContext);
        case "}":
          return ts_formatting_exports.formatOnClosingCurly(position, sourceFile, formatContext);
        case ";":
          return ts_formatting_exports.formatOnSemicolon(position, sourceFile, formatContext);
        case "\n":
          return ts_formatting_exports.formatOnEnter(position, sourceFile, formatContext);
      }
    }
    return [];
  }
  function getCodeFixesAtPosition(fileName, start2, end, errorCodes64, formatOptions, preferences = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const span = createTextSpanFromBounds(start2, end);
    const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host);
    return flatMap(deduplicate(errorCodes64, equateValues, compareValues), (errorCode) => {
      cancellationToken.throwIfCancellationRequested();
      return ts_codefix_exports.getFixes({ errorCode, sourceFile, span, program, host, cancellationToken, formatContext, preferences });
    });
  }
  function getCombinedCodeFix(scope, fixId52, formatOptions, preferences = emptyOptions) {
    synchronizeHostData();
    Debug.assert(scope.type === "file");
    const sourceFile = getValidSourceFile(scope.fileName);
    const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host);
    return ts_codefix_exports.getAllFixes({ fixId: fixId52, sourceFile, program, host, cancellationToken, formatContext, preferences });
  }
  function organizeImports2(args, formatOptions, preferences = emptyOptions) {
    synchronizeHostData();
    Debug.assert(args.type === "file");
    const sourceFile = getValidSourceFile(args.fileName);
    const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host);
    const mode = args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */);
    return ts_OrganizeImports_exports.organizeImports(sourceFile, formatContext, host, program, preferences, mode);
  }
  function getEditsForFileRename2(oldFilePath, newFilePath, formatOptions, preferences = emptyOptions) {
    return getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts_formatting_exports.getFormatContext(formatOptions, host), preferences, sourceMapper);
  }
  function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) {
    const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName;
    return isArray(action) ? Promise.all(action.map((a) => applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action);
  }
  function applySingleCodeActionCommand(action) {
    const getPath = (path) => toPath(path, currentDirectory, getCanonicalFileName);
    Debug.assertEqual(action.type, "install package");
    return host.installPackage ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`");
  }
  function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) {
    const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0;
    return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options);
  }
  function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
    if (openingBrace === 60 /* lessThan */) {
      return false;
    }
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    if (isInString(sourceFile, position)) {
      return false;
    }
    if (isInsideJsxElementOrAttribute(sourceFile, position)) {
      return openingBrace === 123 /* openBrace */;
    }
    if (isInTemplateString(sourceFile, position)) {
      return false;
    }
    switch (openingBrace) {
      case 39 /* singleQuote */:
      case 34 /* doubleQuote */:
      case 96 /* backtick */:
        return !isInComment(sourceFile, position);
    }
    return true;
  }
  function getJsxClosingTagAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const token = findPrecedingToken(position, sourceFile);
    if (!token)
      return void 0;
    const element = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningElement(token.parent) ? token.parent.parent : isJsxText(token) && isJsxElement(token.parent) ? token.parent : void 0;
    if (element && isUnclosedTag(element)) {
      return { newText: `</${element.openingElement.tagName.getText(sourceFile)}>` };
    }
    const fragment = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningFragment(token.parent) ? token.parent.parent : isJsxText(token) && isJsxFragment(token.parent) ? token.parent : void 0;
    if (fragment && isUnclosedFragment(fragment)) {
      return { newText: "</>" };
    }
  }
  function getLinkedEditingRangeAtPosition(fileName, position) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const token = findPrecedingToken(position, sourceFile);
    if (!token || token.parent.kind === 311 /* SourceFile */)
      return void 0;
    const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*";
    if (isJsxFragment(token.parent.parent)) {
      const openFragment = token.parent.parent.openingFragment;
      const closeFragment = token.parent.parent.closingFragment;
      if (containsParseError(openFragment) || containsParseError(closeFragment))
        return void 0;
      const openPos = openFragment.getStart(sourceFile) + 1;
      const closePos = closeFragment.getStart(sourceFile) + 2;
      if (position !== openPos && position !== closePos)
        return void 0;
      return {
        ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }],
        wordPattern: jsxTagWordPattern
      };
    } else {
      const tag = findAncestor(
        token.parent,
        (n) => {
          if (isJsxOpeningElement(n) || isJsxClosingElement(n)) {
            return true;
          }
          return false;
        }
      );
      if (!tag)
        return void 0;
      Debug.assert(isJsxOpeningElement(tag) || isJsxClosingElement(tag), "tag should be opening or closing element");
      const openTag = tag.parent.openingElement;
      const closeTag = tag.parent.closingElement;
      const openTagStart = openTag.tagName.getStart(sourceFile);
      const openTagEnd = openTag.tagName.end;
      const closeTagStart = closeTag.tagName.getStart(sourceFile);
      const closeTagEnd = closeTag.tagName.end;
      if (!(openTagStart <= position && position <= openTagEnd || closeTagStart <= position && position <= closeTagEnd))
        return void 0;
      const openingTagText = openTag.tagName.getText(sourceFile);
      if (openingTagText !== closeTag.tagName.getText(sourceFile))
        return void 0;
      return {
        ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }],
        wordPattern: jsxTagWordPattern
      };
    }
  }
  function getLinesForRange(sourceFile, textRange) {
    return {
      lineStarts: sourceFile.getLineStarts(),
      firstLine: sourceFile.getLineAndCharacterOfPosition(textRange.pos).line,
      lastLine: sourceFile.getLineAndCharacterOfPosition(textRange.end).line
    };
  }
  function toggleLineComment(fileName, textRange, insertComment) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const textChanges2 = [];
    const { lineStarts, firstLine, lastLine } = getLinesForRange(sourceFile, textRange);
    let isCommenting = insertComment || false;
    let leftMostPosition = Number.MAX_VALUE;
    const lineTextStarts = /* @__PURE__ */ new Map();
    const firstNonWhitespaceCharacterRegex = new RegExp(/\S/);
    const isJsx = isInsideJsxElement(sourceFile, lineStarts[firstLine]);
    const openComment = isJsx ? "{/*" : "//";
    for (let i = firstLine; i <= lastLine; i++) {
      const lineText = sourceFile.text.substring(lineStarts[i], sourceFile.getLineEndOfPosition(lineStarts[i]));
      const regExec = firstNonWhitespaceCharacterRegex.exec(lineText);
      if (regExec) {
        leftMostPosition = Math.min(leftMostPosition, regExec.index);
        lineTextStarts.set(i.toString(), regExec.index);
        if (lineText.substr(regExec.index, openComment.length) !== openComment) {
          isCommenting = insertComment === void 0 || insertComment;
        }
      }
    }
    for (let i = firstLine; i <= lastLine; i++) {
      if (firstLine !== lastLine && lineStarts[i] === textRange.end) {
        continue;
      }
      const lineTextStart = lineTextStarts.get(i.toString());
      if (lineTextStart !== void 0) {
        if (isJsx) {
          textChanges2.push.apply(textChanges2, toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx));
        } else if (isCommenting) {
          textChanges2.push({
            newText: openComment,
            span: {
              length: 0,
              start: lineStarts[i] + leftMostPosition
            }
          });
        } else if (sourceFile.text.substr(lineStarts[i] + lineTextStart, openComment.length) === openComment) {
          textChanges2.push({
            newText: "",
            span: {
              length: openComment.length,
              start: lineStarts[i] + lineTextStart
            }
          });
        }
      }
    }
    return textChanges2;
  }
  function toggleMultilineComment(fileName, textRange, insertComment, isInsideJsx) {
    var _a2;
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const textChanges2 = [];
    const { text } = sourceFile;
    let hasComment = false;
    let isCommenting = insertComment || false;
    const positions = [];
    let { pos } = textRange;
    const isJsx = isInsideJsx !== void 0 ? isInsideJsx : isInsideJsxElement(sourceFile, pos);
    const openMultiline = isJsx ? "{/*" : "/*";
    const closeMultiline = isJsx ? "*/}" : "*/";
    const openMultilineRegex = isJsx ? "\\{\\/\\*" : "\\/\\*";
    const closeMultilineRegex = isJsx ? "\\*\\/\\}" : "\\*\\/";
    while (pos <= textRange.end) {
      const offset = text.substr(pos, openMultiline.length) === openMultiline ? openMultiline.length : 0;
      const commentRange = isInComment(sourceFile, pos + offset);
      if (commentRange) {
        if (isJsx) {
          commentRange.pos--;
          commentRange.end++;
        }
        positions.push(commentRange.pos);
        if (commentRange.kind === 3 /* MultiLineCommentTrivia */) {
          positions.push(commentRange.end);
        }
        hasComment = true;
        pos = commentRange.end + 1;
      } else {
        const newPos = text.substring(pos, textRange.end).search(`(${openMultilineRegex})|(${closeMultilineRegex})`);
        isCommenting = insertComment !== void 0 ? insertComment : isCommenting || !isTextWhiteSpaceLike(text, pos, newPos === -1 ? textRange.end : pos + newPos);
        pos = newPos === -1 ? textRange.end + 1 : pos + newPos + closeMultiline.length;
      }
    }
    if (isCommenting || !hasComment) {
      if (((_a2 = isInComment(sourceFile, textRange.pos)) == null ? void 0 : _a2.kind) !== 2 /* SingleLineCommentTrivia */) {
        insertSorted(positions, textRange.pos, compareValues);
      }
      insertSorted(positions, textRange.end, compareValues);
      const firstPos = positions[0];
      if (text.substr(firstPos, openMultiline.length) !== openMultiline) {
        textChanges2.push({
          newText: openMultiline,
          span: {
            length: 0,
            start: firstPos
          }
        });
      }
      for (let i = 1; i < positions.length - 1; i++) {
        if (text.substr(positions[i] - closeMultiline.length, closeMultiline.length) !== closeMultiline) {
          textChanges2.push({
            newText: closeMultiline,
            span: {
              length: 0,
              start: positions[i]
            }
          });
        }
        if (text.substr(positions[i], openMultiline.length) !== openMultiline) {
          textChanges2.push({
            newText: openMultiline,
            span: {
              length: 0,
              start: positions[i]
            }
          });
        }
      }
      if (textChanges2.length % 2 !== 0) {
        textChanges2.push({
          newText: closeMultiline,
          span: {
            length: 0,
            start: positions[positions.length - 1]
          }
        });
      }
    } else {
      for (const pos2 of positions) {
        const from = pos2 - closeMultiline.length > 0 ? pos2 - closeMultiline.length : 0;
        const offset = text.substr(from, closeMultiline.length) === closeMultiline ? closeMultiline.length : 0;
        textChanges2.push({
          newText: "",
          span: {
            length: openMultiline.length,
            start: pos2 - offset
          }
        });
      }
    }
    return textChanges2;
  }
  function commentSelection(fileName, textRange) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const { firstLine, lastLine } = getLinesForRange(sourceFile, textRange);
    return firstLine === lastLine && textRange.pos !== textRange.end ? toggleMultilineComment(
      fileName,
      textRange,
      /*insertComment*/
      true
    ) : toggleLineComment(
      fileName,
      textRange,
      /*insertComment*/
      true
    );
  }
  function uncommentSelection(fileName, textRange) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const textChanges2 = [];
    const { pos } = textRange;
    let { end } = textRange;
    if (pos === end) {
      end += isInsideJsxElement(sourceFile, pos) ? 2 : 1;
    }
    for (let i = pos; i <= end; i++) {
      const commentRange = isInComment(sourceFile, i);
      if (commentRange) {
        switch (commentRange.kind) {
          case 2 /* SingleLineCommentTrivia */:
            textChanges2.push.apply(textChanges2, toggleLineComment(
              fileName,
              { end: commentRange.end, pos: commentRange.pos + 1 },
              /*insertComment*/
              false
            ));
            break;
          case 3 /* MultiLineCommentTrivia */:
            textChanges2.push.apply(textChanges2, toggleMultilineComment(
              fileName,
              { end: commentRange.end, pos: commentRange.pos + 1 },
              /*insertComment*/
              false
            ));
        }
        i = commentRange.end + 1;
      }
    }
    return textChanges2;
  }
  function isUnclosedTag({ openingElement, closingElement, parent: parent2 }) {
    return !tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || isJsxElement(parent2) && tagNamesAreEquivalent(openingElement.tagName, parent2.openingElement.tagName) && isUnclosedTag(parent2);
  }
  function isUnclosedFragment({ closingFragment, parent: parent2 }) {
    return !!(closingFragment.flags & 131072 /* ThisNodeHasError */) || isJsxFragment(parent2) && isUnclosedFragment(parent2);
  }
  function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
    const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
    const range = ts_formatting_exports.getRangeOfEnclosingComment(sourceFile, position);
    return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? createTextSpanFromRange(range) : void 0;
  }
  function getTodoComments(fileName, descriptors) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    cancellationToken.throwIfCancellationRequested();
    const fileContents = sourceFile.text;
    const result = [];
    if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) {
      const regExp = getTodoCommentsRegExp();
      let matchArray;
      while (matchArray = regExp.exec(fileContents)) {
        cancellationToken.throwIfCancellationRequested();
        const firstDescriptorCaptureIndex = 3;
        Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
        const preamble = matchArray[1];
        const matchPosition = matchArray.index + preamble.length;
        if (!isInComment(sourceFile, matchPosition)) {
          continue;
        }
        let descriptor;
        for (let i = 0; i < descriptors.length; i++) {
          if (matchArray[i + firstDescriptorCaptureIndex]) {
            descriptor = descriptors[i];
          }
        }
        if (descriptor === void 0)
          return Debug.fail();
        if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
          continue;
        }
        const message = matchArray[2];
        result.push({ descriptor, message, position: matchPosition });
      }
    }
    return result;
    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
    function getTodoCommentsRegExp() {
      const singleLineCommentStart = /(?:\/\/+\s*)/.source;
      const multiLineCommentStart = /(?:\/\*+\s*)/.source;
      const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
      const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
      const literals = "(?:" + map(descriptors, (d) => "(" + escapeRegExp(d.text) + ")").join("|") + ")";
      const endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
      const messageRemainder = /(?:.*?)/.source;
      const messagePortion = "(" + literals + messageRemainder + ")";
      const regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
      return new RegExp(regExpString, "gim");
    }
    function isLetterOrDigit(char) {
      return char >= 97 /* a */ && char <= 122 /* z */ || char >= 65 /* A */ && char <= 90 /* Z */ || char >= 48 /* _0 */ && char <= 57 /* _9 */;
    }
    function isNodeModulesFile(path) {
      return stringContains(path, "/node_modules/");
    }
  }
  function getRenameInfo2(fileName, position, preferences) {
    synchronizeHostData();
    return ts_Rename_exports.getRenameInfo(program, getValidSourceFile(fileName), position, preferences || {});
  }
  function getRefactorContext(file, positionOrRange, preferences, formatOptions, triggerReason, kind) {
    const [startPosition, endPosition] = typeof positionOrRange === "number" ? [positionOrRange, void 0] : [positionOrRange.pos, positionOrRange.end];
    return {
      file,
      startPosition,
      endPosition,
      program: getProgram(),
      host,
      formatContext: ts_formatting_exports.getFormatContext(formatOptions, host),
      // TODO: GH#18217
      cancellationToken,
      preferences,
      triggerReason,
      kind
    };
  }
  function getInlayHintsContext(file, span, preferences) {
    return {
      file,
      program: getProgram(),
      host,
      span,
      preferences,
      cancellationToken
    };
  }
  function getSmartSelectionRange2(fileName, position) {
    return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName));
  }
  function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind, includeInteractiveActions) {
    synchronizeHostData();
    const file = getValidSourceFile(fileName);
    return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions);
  }
  function getMoveToRefactoringFileSuggestions(fileName, positionOrRange, preferences = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const allFiles = Debug.checkDefined(program.getSourceFiles());
    const extension = extensionFromPath(fileName);
    const files = mapDefined(allFiles, (file) => !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0);
    const newFileName = createNewFileName(sourceFile, program, getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions), host);
    return { newFileName, files };
  }
  function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions, interactiveRefactorArguments) {
    synchronizeHostData();
    const file = getValidSourceFile(fileName);
    return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2, interactiveRefactorArguments);
  }
  function toLineColumnOffset(fileName, position) {
    if (position === 0) {
      return { line: 0, character: 0 };
    }
    return sourceMapper.toLineColumnOffset(fileName, position);
  }
  function prepareCallHierarchy(fileName, position) {
    synchronizeHostData();
    const declarations = ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, getTouchingPropertyName(getValidSourceFile(fileName), position));
    return declarations && mapOneOrMany(declarations, (declaration) => ts_CallHierarchy_exports.createCallHierarchyItem(program, declaration));
  }
  function provideCallHierarchyIncomingCalls(fileName, position) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position)));
    return declaration ? ts_CallHierarchy_exports.getIncomingCalls(program, declaration, cancellationToken) : [];
  }
  function provideCallHierarchyOutgoingCalls(fileName, position) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    const declaration = firstOrOnly(ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : getTouchingPropertyName(sourceFile, position)));
    return declaration ? ts_CallHierarchy_exports.getOutgoingCalls(program, declaration) : [];
  }
  function provideInlayHints2(fileName, span, preferences = emptyOptions) {
    synchronizeHostData();
    const sourceFile = getValidSourceFile(fileName);
    return ts_InlayHints_exports.provideInlayHints(getInlayHintsContext(sourceFile, span, preferences));
  }
  const ls = {
    dispose,
    cleanupSemanticCache,
    getSyntacticDiagnostics,
    getSemanticDiagnostics,
    getSuggestionDiagnostics,
    getCompilerOptionsDiagnostics,
    getSyntacticClassifications: getSyntacticClassifications2,
    getSemanticClassifications: getSemanticClassifications3,
    getEncodedSyntacticClassifications: getEncodedSyntacticClassifications2,
    getEncodedSemanticClassifications: getEncodedSemanticClassifications3,
    getCompletionsAtPosition: getCompletionsAtPosition2,
    getCompletionEntryDetails: getCompletionEntryDetails2,
    getCompletionEntrySymbol: getCompletionEntrySymbol2,
    getSignatureHelpItems: getSignatureHelpItems2,
    getQuickInfoAtPosition,
    getDefinitionAtPosition: getDefinitionAtPosition2,
    getDefinitionAndBoundSpan: getDefinitionAndBoundSpan2,
    getImplementationAtPosition,
    getTypeDefinitionAtPosition: getTypeDefinitionAtPosition2,
    getReferencesAtPosition,
    findReferences,
    getFileReferences,
    getDocumentHighlights,
    getNameOrDottedNameSpan,
    getBreakpointStatementAtPosition,
    getNavigateToItems: getNavigateToItems2,
    getRenameInfo: getRenameInfo2,
    getSmartSelectionRange: getSmartSelectionRange2,
    findRenameLocations,
    getNavigationBarItems: getNavigationBarItems2,
    getNavigationTree: getNavigationTree2,
    getOutliningSpans,
    getTodoComments,
    getBraceMatchingAtPosition,
    getIndentationAtPosition,
    getFormattingEditsForRange,
    getFormattingEditsForDocument,
    getFormattingEditsAfterKeystroke,
    getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition2,
    isValidBraceCompletionAtPosition,
    getJsxClosingTagAtPosition,
    getLinkedEditingRangeAtPosition,
    getSpanOfEnclosingComment,
    getCodeFixesAtPosition,
    getCombinedCodeFix,
    applyCodeActionCommand,
    organizeImports: organizeImports2,
    getEditsForFileRename: getEditsForFileRename2,
    getEmitOutput,
    getNonBoundSourceFile,
    getProgram,
    getCurrentProgram: () => program,
    getAutoImportProvider,
    updateIsDefinitionOfReferencedSymbols,
    getApplicableRefactors: getApplicableRefactors2,
    getEditsForRefactor: getEditsForRefactor2,
    getMoveToRefactoringFileSuggestions,
    toLineColumnOffset,
    getSourceMapper: () => sourceMapper,
    clearSourceMapperCache: () => sourceMapper.clearCache(),
    prepareCallHierarchy,
    provideCallHierarchyIncomingCalls,
    provideCallHierarchyOutgoingCalls,
    toggleLineComment,
    toggleMultilineComment,
    commentSelection,
    uncommentSelection,
    provideInlayHints: provideInlayHints2,
    getSupportedCodeFixes
  };
  switch (languageServiceMode) {
    case 0 /* Semantic */:
      break;
    case 1 /* PartialSemantic */:
      invalidOperationsInPartialSemanticMode.forEach(
        (key) => ls[key] = () => {
          throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.PartialSemantic`);
        }
      );
      break;
    case 2 /* Syntactic */:
      invalidOperationsInSyntacticMode.forEach(
        (key) => ls[key] = () => {
          throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.Syntactic`);
        }
      );
      break;
    default:
      Debug.assertNever(languageServiceMode);
  }
  return ls;
}
function getNameTable(sourceFile) {
  if (!sourceFile.nameTable) {
    initializeNameTable(sourceFile);
  }
  return sourceFile.nameTable;
}
function initializeNameTable(sourceFile) {
  const nameTable = sourceFile.nameTable = /* @__PURE__ */ new Map();
  sourceFile.forEachChild(function walk(node) {
    if (isIdentifier(node) && !isTagName(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) {
      const text = getEscapedTextOfIdentifierOrLiteral(node);
      nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1);
    } else if (isPrivateIdentifier(node)) {
      const text = node.escapedText;
      nameTable.set(text, nameTable.get(text) === void 0 ? node.pos : -1);
    }
    forEachChild(node, walk);
    if (hasJSDocNodes(node)) {
      for (const jsDoc of node.jsDoc) {
        forEachChild(jsDoc, walk);
      }
    }
  });
}
function literalIsName(node) {
  return isDeclarationName(node) || node.parent.kind === 282 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || isLiteralComputedPropertyDeclarationName(node);
}
function getContainingObjectLiteralElement(node) {
  const element = getContainingObjectLiteralElementWorker(node);
  return element && (isObjectLiteralExpression(element.parent) || isJsxAttributes(element.parent)) ? element : void 0;
}
function getContainingObjectLiteralElementWorker(node) {
  switch (node.kind) {
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 9 /* NumericLiteral */:
      if (node.parent.kind === 166 /* ComputedPropertyName */) {
        return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : void 0;
      }
    case 80 /* Identifier */:
      return isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 209 /* ObjectLiteralExpression */ || node.parent.parent.kind === 291 /* JsxAttributes */) && node.parent.name === node ? node.parent : void 0;
  }
  return void 0;
}
function getSymbolAtLocationForQuickInfo(node, checker) {
  const object = getContainingObjectLiteralElement(node);
  if (object) {
    const contextualType = checker.getContextualType(object.parent);
    const properties = contextualType && getPropertySymbolsFromContextualType(
      object,
      checker,
      contextualType,
      /*unionSymbolOk*/
      false
    );
    if (properties && properties.length === 1) {
      return first(properties);
    }
  }
  return checker.getSymbolAtLocation(node);
}
function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) {
  const name = getNameFromPropertyName(node.name);
  if (!name)
    return emptyArray;
  if (!contextualType.isUnion()) {
    const symbol = contextualType.getProperty(name);
    return symbol ? [symbol] : emptyArray;
  }
  const discriminatedPropertySymbols = mapDefined(contextualType.types, (t) => (isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? void 0 : t.getProperty(name));
  if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
    const symbol = contextualType.getProperty(name);
    if (symbol)
      return [symbol];
  }
  if (discriminatedPropertySymbols.length === 0) {
    return mapDefined(contextualType.types, (t) => t.getProperty(name));
  }
  return discriminatedPropertySymbols;
}
function isArgumentOfElementAccessExpression(node) {
  return node && node.parent && node.parent.kind === 211 /* ElementAccessExpression */ && node.parent.argumentExpression === node;
}
function getDefaultLibFilePath(options) {
  if (sys) {
    return combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options));
  }
  throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
}
setObjectAllocator(getServicesObjectAllocator());

// src/services/transform.ts
function transform(source, transformers, compilerOptions) {
  const diagnostics = [];
  compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics);
  const nodes = isArray(source) ? source : [source];
  const result = transformNodes(
    /*resolver*/
    void 0,
    /*host*/
    void 0,
    factory,
    compilerOptions,
    nodes,
    transformers,
    /*allowDtsFiles*/
    true
  );
  result.diagnostics = concatenate(result.diagnostics, diagnostics);
  return result;
}

// src/services/shims.ts
var debugObjectHost = function() {
  return this;
}();
function logInternalError(logger, err) {
  if (logger) {
    logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
  }
}
var ScriptSnapshotShimAdapter = class {
  constructor(scriptSnapshotShim) {
    this.scriptSnapshotShim = scriptSnapshotShim;
  }
  getText(start2, end) {
    return this.scriptSnapshotShim.getText(start2, end);
  }
  getLength() {
    return this.scriptSnapshotShim.getLength();
  }
  getChangeRange(oldSnapshot) {
    const oldSnapshotShim = oldSnapshot;
    const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
    if (encoded === null) {
      return null;
    }
    const decoded = JSON.parse(encoded);
    return createTextChangeRange(
      createTextSpan(decoded.span.start, decoded.span.length),
      decoded.newLength
    );
  }
  dispose() {
    if ("dispose" in this.scriptSnapshotShim) {
      this.scriptSnapshotShim.dispose();
    }
  }
};
var LanguageServiceShimHostAdapter = class {
  constructor(shimHost) {
    this.shimHost = shimHost;
    this.loggingEnabled = false;
    this.tracingEnabled = false;
    if ("getModuleResolutionsForFile" in this.shimHost) {
      this.resolveModuleNames = (moduleNames, containingFile) => {
        const resolutionsInFile = JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile));
        return map(moduleNames, (name) => {
          const result = getProperty(resolutionsInFile, name);
          return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : void 0;
        });
      };
    }
    if ("directoryExists" in this.shimHost) {
      this.directoryExists = (directoryName) => this.shimHost.directoryExists(directoryName);
    }
    if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
      this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile) => {
        const typeDirectivesForFile = JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile));
        return map(typeDirectiveNames, (name) => getProperty(typeDirectivesForFile, isString(name) ? name : toFileNameLowerCase(name.fileName)));
      };
    }
  }
  log(s) {
    if (this.loggingEnabled) {
      this.shimHost.log(s);
    }
  }
  trace(s) {
    if (this.tracingEnabled) {
      this.shimHost.trace(s);
    }
  }
  error(s) {
    this.shimHost.error(s);
  }
  getProjectVersion() {
    if (!this.shimHost.getProjectVersion) {
      return void 0;
    }
    return this.shimHost.getProjectVersion();
  }
  getTypeRootsVersion() {
    if (!this.shimHost.getTypeRootsVersion) {
      return 0;
    }
    return this.shimHost.getTypeRootsVersion();
  }
  useCaseSensitiveFileNames() {
    return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
  }
  getCompilationSettings() {
    const settingsJson = this.shimHost.getCompilationSettings();
    if (settingsJson === null || settingsJson === "") {
      throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
    }
    const compilerOptions = JSON.parse(settingsJson);
    compilerOptions.allowNonTsExtensions = true;
    return compilerOptions;
  }
  getScriptFileNames() {
    const encoded = this.shimHost.getScriptFileNames();
    return JSON.parse(encoded);
  }
  getScriptSnapshot(fileName) {
    const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
    return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
  }
  getScriptKind(fileName) {
    if ("getScriptKind" in this.shimHost) {
      return this.shimHost.getScriptKind(fileName);
    } else {
      return 0 /* Unknown */;
    }
  }
  getScriptVersion(fileName) {
    return this.shimHost.getScriptVersion(fileName);
  }
  getLocalizedDiagnosticMessages() {
    const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
    if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
      return null;
    }
    try {
      return JSON.parse(diagnosticMessagesJson);
    } catch (e) {
      this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
      return null;
    }
  }
  getCancellationToken() {
    const hostCancellationToken = this.shimHost.getCancellationToken();
    return new ThrottledCancellationToken(hostCancellationToken);
  }
  getCurrentDirectory() {
    return this.shimHost.getCurrentDirectory();
  }
  getDirectories(path) {
    return JSON.parse(this.shimHost.getDirectories(path));
  }
  getDefaultLibFileName(options) {
    return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
  }
  readDirectory(path, extensions, exclude, include, depth) {
    const pattern = getFileMatcherPatterns(
      path,
      exclude,
      include,
      this.shimHost.useCaseSensitiveFileNames(),
      this.shimHost.getCurrentDirectory()
    );
    return JSON.parse(this.shimHost.readDirectory(
      path,
      JSON.stringify(extensions),
      JSON.stringify(pattern.basePaths),
      pattern.excludePattern,
      pattern.includeFilePattern,
      pattern.includeDirectoryPattern,
      depth
    ));
  }
  readFile(path, encoding) {
    return this.shimHost.readFile(path, encoding);
  }
  fileExists(path) {
    return this.shimHost.fileExists(path);
  }
};
var CoreServicesShimHostAdapter = class {
  constructor(shimHost) {
    this.shimHost = shimHost;
    this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
    if ("directoryExists" in this.shimHost) {
      this.directoryExists = (directoryName) => this.shimHost.directoryExists(directoryName);
    } else {
      this.directoryExists = void 0;
    }
    if ("realpath" in this.shimHost) {
      this.realpath = (path) => this.shimHost.realpath(path);
    } else {
      this.realpath = void 0;
    }
  }
  readDirectory(rootDir, extensions, exclude, include, depth) {
    const pattern = getFileMatcherPatterns(
      rootDir,
      exclude,
      include,
      this.shimHost.useCaseSensitiveFileNames(),
      this.shimHost.getCurrentDirectory()
    );
    return JSON.parse(this.shimHost.readDirectory(
      rootDir,
      JSON.stringify(extensions),
      JSON.stringify(pattern.basePaths),
      pattern.excludePattern,
      pattern.includeFilePattern,
      pattern.includeDirectoryPattern,
      depth
    ));
  }
  fileExists(fileName) {
    return this.shimHost.fileExists(fileName);
  }
  readFile(fileName) {
    return this.shimHost.readFile(fileName);
  }
  getDirectories(path) {
    return JSON.parse(this.shimHost.getDirectories(path));
  }
};
function simpleForwardCall(logger, actionDescription2, action, logPerformance) {
  let start2;
  if (logPerformance) {
    logger.log(actionDescription2);
    start2 = timestamp();
  }
  const result = action();
  if (logPerformance) {
    const end = timestamp();
    logger.log(`${actionDescription2} completed in ${end - start2} msec`);
    if (isString(result)) {
      let str = result;
      if (str.length > 128) {
        str = str.substring(0, 128) + "...";
      }
      logger.log(`  result.length=${str.length}, result='${JSON.stringify(str)}'`);
    }
  }
  return result;
}
function forwardJSONCall(logger, actionDescription2, action, logPerformance) {
  return forwardCall(
    logger,
    actionDescription2,
    /*returnJson*/
    true,
    action,
    logPerformance
  );
}
function forwardCall(logger, actionDescription2, returnJson, action, logPerformance) {
  try {
    const result = simpleForwardCall(logger, actionDescription2, action, logPerformance);
    return returnJson ? JSON.stringify({ result }) : result;
  } catch (err) {
    if (err instanceof OperationCanceledException) {
      return JSON.stringify({ canceled: true });
    }
    logInternalError(logger, err);
    err.description = actionDescription2;
    return JSON.stringify({ error: err });
  }
}
var ShimBase = class {
  constructor(factory2) {
    this.factory = factory2;
    factory2.registerShim(this);
  }
  dispose(_dummy) {
    this.factory.unregisterShim(this);
  }
};
function realizeDiagnostics(diagnostics, newLine) {
  return diagnostics.map((d) => realizeDiagnostic(d, newLine));
}
function realizeDiagnostic(diagnostic, newLine) {
  return {
    message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
    start: diagnostic.start,
    // TODO: GH#18217
    length: diagnostic.length,
    // TODO: GH#18217
    category: diagnosticCategoryName(diagnostic),
    code: diagnostic.code,
    reportsUnnecessary: diagnostic.reportsUnnecessary,
    reportsDeprecated: diagnostic.reportsDeprecated
  };
}
var LanguageServiceShimObject = class extends ShimBase {
  constructor(factory2, host, languageService) {
    super(factory2);
    this.host = host;
    this.languageService = languageService;
    this.logPerformance = false;
    this.logger = this.host;
  }
  forwardJSONCall(actionDescription2, action) {
    return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance);
  }
  /// DISPOSE
  /**
   * Ensure (almost) deterministic release of internal Javascript resources when
   * some external native objects holds onto us (e.g. Com/Interop).
   */
  dispose(dummy) {
    this.logger.log("dispose()");
    this.languageService.dispose();
    this.languageService = null;
    if (debugObjectHost && debugObjectHost.CollectGarbage) {
      debugObjectHost.CollectGarbage();
      this.logger.log("CollectGarbage()");
    }
    this.logger = null;
    super.dispose(dummy);
  }
  /// REFRESH
  /**
   * Update the list of scripts known to the compiler
   */
  refresh(throwOnError) {
    this.forwardJSONCall(
      `refresh(${throwOnError})`,
      () => null
      // eslint-disable-line no-null/no-null
    );
  }
  cleanupSemanticCache() {
    this.forwardJSONCall(
      "cleanupSemanticCache()",
      () => {
        this.languageService.cleanupSemanticCache();
        return null;
      }
    );
  }
  realizeDiagnostics(diagnostics) {
    const newLine = getNewLineOrDefaultFromHost(
      this.host,
      /*formatSettings*/
      void 0
    );
    return realizeDiagnostics(diagnostics, newLine);
  }
  getSyntacticClassifications(fileName, start2, length2) {
    return this.forwardJSONCall(
      `getSyntacticClassifications('${fileName}', ${start2}, ${length2})`,
      () => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start2, length2))
    );
  }
  getSemanticClassifications(fileName, start2, length2) {
    return this.forwardJSONCall(
      `getSemanticClassifications('${fileName}', ${start2}, ${length2})`,
      () => this.languageService.getSemanticClassifications(fileName, createTextSpan(start2, length2))
    );
  }
  getEncodedSyntacticClassifications(fileName, start2, length2) {
    return this.forwardJSONCall(
      `getEncodedSyntacticClassifications('${fileName}', ${start2}, ${length2})`,
      // directly serialize the spans out to a string.  This is much faster to decode
      // on the managed side versus a full JSON array.
      () => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start2, length2)))
    );
  }
  getEncodedSemanticClassifications(fileName, start2, length2) {
    return this.forwardJSONCall(
      `getEncodedSemanticClassifications('${fileName}', ${start2}, ${length2})`,
      // directly serialize the spans out to a string.  This is much faster to decode
      // on the managed side versus a full JSON array.
      () => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start2, length2)))
    );
  }
  getSyntacticDiagnostics(fileName) {
    return this.forwardJSONCall(
      `getSyntacticDiagnostics('${fileName}')`,
      () => {
        const diagnostics = this.languageService.getSyntacticDiagnostics(fileName);
        return this.realizeDiagnostics(diagnostics);
      }
    );
  }
  getSemanticDiagnostics(fileName) {
    return this.forwardJSONCall(
      `getSemanticDiagnostics('${fileName}')`,
      () => {
        const diagnostics = this.languageService.getSemanticDiagnostics(fileName);
        return this.realizeDiagnostics(diagnostics);
      }
    );
  }
  getSuggestionDiagnostics(fileName) {
    return this.forwardJSONCall(`getSuggestionDiagnostics('${fileName}')`, () => this.realizeDiagnostics(this.languageService.getSuggestionDiagnostics(fileName)));
  }
  getCompilerOptionsDiagnostics() {
    return this.forwardJSONCall(
      "getCompilerOptionsDiagnostics()",
      () => {
        const diagnostics = this.languageService.getCompilerOptionsDiagnostics();
        return this.realizeDiagnostics(diagnostics);
      }
    );
  }
  /// QUICKINFO
  /**
   * Computes a string representation of the type at the requested position
   * in the active file.
   */
  getQuickInfoAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getQuickInfoAtPosition('${fileName}', ${position})`,
      () => this.languageService.getQuickInfoAtPosition(fileName, position)
    );
  }
  /// NAMEORDOTTEDNAMESPAN
  /**
   * Computes span information of the name or dotted name at the requested position
   * in the active file.
   */
  getNameOrDottedNameSpan(fileName, startPos, endPos) {
    return this.forwardJSONCall(
      `getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`,
      () => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos)
    );
  }
  /**
   * STATEMENTSPAN
   * Computes span information of statement at the requested position in the active file.
   */
  getBreakpointStatementAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getBreakpointStatementAtPosition('${fileName}', ${position})`,
      () => this.languageService.getBreakpointStatementAtPosition(fileName, position)
    );
  }
  /// SIGNATUREHELP
  getSignatureHelpItems(fileName, position, options) {
    return this.forwardJSONCall(
      `getSignatureHelpItems('${fileName}', ${position})`,
      () => this.languageService.getSignatureHelpItems(fileName, position, options)
    );
  }
  /// GOTO DEFINITION
  /**
   * Computes the definition location and file for the symbol
   * at the requested position.
   */
  getDefinitionAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getDefinitionAtPosition('${fileName}', ${position})`,
      () => this.languageService.getDefinitionAtPosition(fileName, position)
    );
  }
  /**
   * Computes the definition location and file for the symbol
   * at the requested position.
   */
  getDefinitionAndBoundSpan(fileName, position) {
    return this.forwardJSONCall(
      `getDefinitionAndBoundSpan('${fileName}', ${position})`,
      () => this.languageService.getDefinitionAndBoundSpan(fileName, position)
    );
  }
  /// GOTO Type
  /**
   * Computes the definition location of the type of the symbol
   * at the requested position.
   */
  getTypeDefinitionAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getTypeDefinitionAtPosition('${fileName}', ${position})`,
      () => this.languageService.getTypeDefinitionAtPosition(fileName, position)
    );
  }
  /// GOTO Implementation
  /**
   * Computes the implementation location of the symbol
   * at the requested position.
   */
  getImplementationAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getImplementationAtPosition('${fileName}', ${position})`,
      () => this.languageService.getImplementationAtPosition(fileName, position)
    );
  }
  getRenameInfo(fileName, position, preferences) {
    return this.forwardJSONCall(
      `getRenameInfo('${fileName}', ${position})`,
      () => this.languageService.getRenameInfo(fileName, position, preferences)
    );
  }
  getSmartSelectionRange(fileName, position) {
    return this.forwardJSONCall(
      `getSmartSelectionRange('${fileName}', ${position})`,
      () => this.languageService.getSmartSelectionRange(fileName, position)
    );
  }
  findRenameLocations(fileName, position, findInStrings, findInComments, preferences) {
    return this.forwardJSONCall(
      `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`,
      () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences)
    );
  }
  /// GET BRACE MATCHING
  getBraceMatchingAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getBraceMatchingAtPosition('${fileName}', ${position})`,
      () => this.languageService.getBraceMatchingAtPosition(fileName, position)
    );
  }
  isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
    return this.forwardJSONCall(
      `isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`,
      () => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace)
    );
  }
  getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
    return this.forwardJSONCall(
      `getSpanOfEnclosingComment('${fileName}', ${position})`,
      () => this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine)
    );
  }
  /// GET SMART INDENT
  getIndentationAtPosition(fileName, position, options) {
    return this.forwardJSONCall(
      `getIndentationAtPosition('${fileName}', ${position})`,
      () => {
        const localOptions = JSON.parse(options);
        return this.languageService.getIndentationAtPosition(fileName, position, localOptions);
      }
    );
  }
  /// GET REFERENCES
  getReferencesAtPosition(fileName, position) {
    return this.forwardJSONCall(
      `getReferencesAtPosition('${fileName}', ${position})`,
      () => this.languageService.getReferencesAtPosition(fileName, position)
    );
  }
  findReferences(fileName, position) {
    return this.forwardJSONCall(
      `findReferences('${fileName}', ${position})`,
      () => this.languageService.findReferences(fileName, position)
    );
  }
  getFileReferences(fileName) {
    return this.forwardJSONCall(
      `getFileReferences('${fileName})`,
      () => this.languageService.getFileReferences(fileName)
    );
  }
  getDocumentHighlights(fileName, position, filesToSearch) {
    return this.forwardJSONCall(
      `getDocumentHighlights('${fileName}', ${position})`,
      () => {
        const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
        const normalizedName = toFileNameLowerCase(normalizeSlashes(fileName));
        return filter(results, (r) => toFileNameLowerCase(normalizeSlashes(r.fileName)) === normalizedName);
      }
    );
  }
  /// COMPLETION LISTS
  /**
   * Get a string based representation of the completions
   * to provide at the given source position and providing a member completion
   * list if requested.
   */
  getCompletionsAtPosition(fileName, position, preferences, formattingSettings) {
    return this.forwardJSONCall(
      `getCompletionsAtPosition('${fileName}', ${position}, ${preferences}, ${formattingSettings})`,
      () => this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings)
    );
  }
  /** Get a string based representation of a completion list entry details */
  getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data) {
    return this.forwardJSONCall(
      `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`,
      () => {
        const localOptions = formatOptions === void 0 ? void 0 : JSON.parse(formatOptions);
        return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data);
      }
    );
  }
  getFormattingEditsForRange(fileName, start2, end, options) {
    return this.forwardJSONCall(
      `getFormattingEditsForRange('${fileName}', ${start2}, ${end})`,
      () => {
        const localOptions = JSON.parse(options);
        return this.languageService.getFormattingEditsForRange(fileName, start2, end, localOptions);
      }
    );
  }
  getFormattingEditsForDocument(fileName, options) {
    return this.forwardJSONCall(
      `getFormattingEditsForDocument('${fileName}')`,
      () => {
        const localOptions = JSON.parse(options);
        return this.languageService.getFormattingEditsForDocument(fileName, localOptions);
      }
    );
  }
  getFormattingEditsAfterKeystroke(fileName, position, key, options) {
    return this.forwardJSONCall(
      `getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`,
      () => {
        const localOptions = JSON.parse(options);
        return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
      }
    );
  }
  getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) {
    return this.forwardJSONCall(
      `getDocCommentTemplateAtPosition('${fileName}', ${position})`,
      () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions)
    );
  }
  /// NAVIGATE TO
  /** Return a list of symbols that are interesting to navigate to */
  getNavigateToItems(searchValue, maxResultCount, fileName) {
    return this.forwardJSONCall(
      `getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`,
      () => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName)
    );
  }
  getNavigationBarItems(fileName) {
    return this.forwardJSONCall(
      `getNavigationBarItems('${fileName}')`,
      () => this.languageService.getNavigationBarItems(fileName)
    );
  }
  getNavigationTree(fileName) {
    return this.forwardJSONCall(
      `getNavigationTree('${fileName}')`,
      () => this.languageService.getNavigationTree(fileName)
    );
  }
  getOutliningSpans(fileName) {
    return this.forwardJSONCall(
      `getOutliningSpans('${fileName}')`,
      () => this.languageService.getOutliningSpans(fileName)
    );
  }
  getTodoComments(fileName, descriptors) {
    return this.forwardJSONCall(
      `getTodoComments('${fileName}')`,
      () => this.languageService.getTodoComments(fileName, JSON.parse(descriptors))
    );
  }
  /// CALL HIERARCHY
  prepareCallHierarchy(fileName, position) {
    return this.forwardJSONCall(
      `prepareCallHierarchy('${fileName}', ${position})`,
      () => this.languageService.prepareCallHierarchy(fileName, position)
    );
  }
  provideCallHierarchyIncomingCalls(fileName, position) {
    return this.forwardJSONCall(
      `provideCallHierarchyIncomingCalls('${fileName}', ${position})`,
      () => this.languageService.provideCallHierarchyIncomingCalls(fileName, position)
    );
  }
  provideCallHierarchyOutgoingCalls(fileName, position) {
    return this.forwardJSONCall(
      `provideCallHierarchyOutgoingCalls('${fileName}', ${position})`,
      () => this.languageService.provideCallHierarchyOutgoingCalls(fileName, position)
    );
  }
  provideInlayHints(fileName, span, preference) {
    return this.forwardJSONCall(
      `provideInlayHints('${fileName}', '${JSON.stringify(span)}', ${JSON.stringify(preference)})`,
      () => this.languageService.provideInlayHints(fileName, span, preference)
    );
  }
  /// Emit
  getEmitOutput(fileName) {
    return this.forwardJSONCall(
      `getEmitOutput('${fileName}')`,
      () => {
        const { diagnostics, ...rest } = this.languageService.getEmitOutput(fileName);
        return { ...rest, diagnostics: this.realizeDiagnostics(diagnostics) };
      }
    );
  }
  getEmitOutputObject(fileName) {
    return forwardCall(
      this.logger,
      `getEmitOutput('${fileName}')`,
      /*returnJson*/
      false,
      () => this.languageService.getEmitOutput(fileName),
      this.logPerformance
    );
  }
  toggleLineComment(fileName, textRange) {
    return this.forwardJSONCall(
      `toggleLineComment('${fileName}', '${JSON.stringify(textRange)}')`,
      () => this.languageService.toggleLineComment(fileName, textRange)
    );
  }
  toggleMultilineComment(fileName, textRange) {
    return this.forwardJSONCall(
      `toggleMultilineComment('${fileName}', '${JSON.stringify(textRange)}')`,
      () => this.languageService.toggleMultilineComment(fileName, textRange)
    );
  }
  commentSelection(fileName, textRange) {
    return this.forwardJSONCall(
      `commentSelection('${fileName}', '${JSON.stringify(textRange)}')`,
      () => this.languageService.commentSelection(fileName, textRange)
    );
  }
  uncommentSelection(fileName, textRange) {
    return this.forwardJSONCall(
      `uncommentSelection('${fileName}', '${JSON.stringify(textRange)}')`,
      () => this.languageService.uncommentSelection(fileName, textRange)
    );
  }
};
function convertClassifications(classifications) {
  return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
}
var ClassifierShimObject = class extends ShimBase {
  constructor(factory2, logger) {
    super(factory2);
    this.logger = logger;
    this.logPerformance = false;
    this.classifier = createClassifier();
  }
  getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent = false) {
    return forwardJSONCall(
      this.logger,
      "getEncodedLexicalClassifications",
      () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)),
      this.logPerformance
    );
  }
  /// COLORIZATION
  getClassificationsForLine(text, lexState, classifyKeywordsInGenerics = false) {
    const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
    let result = "";
    for (const item of classification.entries) {
      result += item.length + "\n";
      result += item.classification + "\n";
    }
    result += classification.finalLexState;
    return result;
  }
};
var CoreServicesShimObject = class extends ShimBase {
  constructor(factory2, logger, host) {
    super(factory2);
    this.logger = logger;
    this.host = host;
    this.logPerformance = false;
  }
  forwardJSONCall(actionDescription2, action) {
    return forwardJSONCall(this.logger, actionDescription2, action, this.logPerformance);
  }
  resolveModuleName(fileName, moduleName, compilerOptionsJson) {
    return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => {
      const compilerOptions = JSON.parse(compilerOptionsJson);
      const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
      let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : void 0;
      if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) {
        resolvedFileName = void 0;
      }
      return {
        resolvedFileName,
        failedLookupLocations: result.failedLookupLocations,
        affectingLocations: result.affectingLocations
      };
    });
  }
  resolveTypeReferenceDirective(fileName, typeReferenceDirective, compilerOptionsJson) {
    return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => {
      const compilerOptions = JSON.parse(compilerOptionsJson);
      const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host);
      return {
        resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : void 0,
        primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
        failedLookupLocations: result.failedLookupLocations
      };
    });
  }
  getPreProcessedFileInfo(fileName, sourceTextSnapshot) {
    return this.forwardJSONCall(
      `getPreProcessedFileInfo('${fileName}')`,
      () => {
        const result = preProcessFile(
          getSnapshotText(sourceTextSnapshot),
          /*readImportFiles*/
          true,
          /*detectJavaScriptImports*/
          true
        );
        return {
          referencedFiles: this.convertFileReferences(result.referencedFiles),
          importedFiles: this.convertFileReferences(result.importedFiles),
          ambientExternalModules: result.ambientExternalModules,
          isLibFile: result.isLibFile,
          typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives),
          libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives)
        };
      }
    );
  }
  getAutomaticTypeDirectiveNames(compilerOptionsJson) {
    return this.forwardJSONCall(
      `getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`,
      () => {
        const compilerOptions = JSON.parse(compilerOptionsJson);
        return getAutomaticTypeDirectiveNames(compilerOptions, this.host);
      }
    );
  }
  convertFileReferences(refs) {
    if (!refs) {
      return void 0;
    }
    const result = [];
    for (const ref of refs) {
      result.push({
        path: normalizeSlashes(ref.fileName),
        position: ref.pos,
        length: ref.end - ref.pos
      });
    }
    return result;
  }
  getTSConfigFileInfo(fileName, sourceTextSnapshot) {
    return this.forwardJSONCall(
      `getTSConfigFileInfo('${fileName}')`,
      () => {
        const result = parseJsonText(fileName, getSnapshotText(sourceTextSnapshot));
        const normalizedFileName = normalizeSlashes(fileName);
        const configFile = parseJsonSourceFileConfigFileContent(
          result,
          this.host,
          getDirectoryPath(normalizedFileName),
          /*existingOptions*/
          {},
          normalizedFileName
        );
        return {
          options: configFile.options,
          typeAcquisition: configFile.typeAcquisition,
          files: configFile.fileNames,
          raw: configFile.raw,
          errors: realizeDiagnostics([...result.parseDiagnostics, ...configFile.errors], "\r\n")
        };
      }
    );
  }
  getDefaultCompilationSettings() {
    return this.forwardJSONCall(
      "getDefaultCompilationSettings()",
      () => getDefaultCompilerOptions2()
    );
  }
  discoverTypings(discoverTypingsJson) {
    const getCanonicalFileName = createGetCanonicalFileName(
      /*useCaseSensitiveFileNames*/
      false
    );
    return this.forwardJSONCall("discoverTypings()", () => {
      const info = JSON.parse(discoverTypingsJson);
      if (this.safeList === void 0) {
        this.safeList = ts_JsTyping_exports.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
      }
      return ts_JsTyping_exports.discoverTypings(
        this.host,
        (msg) => this.logger.log(msg),
        info.fileNames,
        toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName),
        this.safeList,
        info.packageNameToTypingLocation,
        info.typeAcquisition,
        info.unresolvedImports,
        info.typesRegistry,
        emptyOptions
      );
    });
  }
};
var TypeScriptServicesFactory = class {
  constructor() {
    this._shims = [];
  }
  /*
   * Returns script API version.
   */
  getServicesVersion() {
    return servicesVersion;
  }
  createLanguageServiceShim(host) {
    try {
      if (this.documentRegistry === void 0) {
        this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
      }
      const hostAdapter = new LanguageServiceShimHostAdapter(host);
      const languageService = createLanguageService(
        hostAdapter,
        this.documentRegistry,
        /*syntaxOnlyOrLanguageServiceMode*/
        false
      );
      return new LanguageServiceShimObject(this, host, languageService);
    } catch (err) {
      logInternalError(host, err);
      throw err;
    }
  }
  createClassifierShim(logger) {
    try {
      return new ClassifierShimObject(this, logger);
    } catch (err) {
      logInternalError(logger, err);
      throw err;
    }
  }
  createCoreServicesShim(host) {
    try {
      const adapter = new CoreServicesShimHostAdapter(host);
      return new CoreServicesShimObject(this, host, adapter);
    } catch (err) {
      logInternalError(host, err);
      throw err;
    }
  }
  close() {
    clear(this._shims);
    this.documentRegistry = void 0;
  }
  registerShim(shim) {
    this._shims.push(shim);
  }
  unregisterShim(shim) {
    for (let i = 0; i < this._shims.length; i++) {
      if (this._shims[i] === shim) {
        delete this._shims[i];
        return;
      }
    }
    throw new Error("Invalid operation");
  }
};

// src/services/_namespaces/ts.BreakpointResolver.ts
var ts_BreakpointResolver_exports = {};
__export(ts_BreakpointResolver_exports, {
  spanInSourceFileAtLocation: () => spanInSourceFileAtLocation
});

// src/services/breakpoints.ts
function spanInSourceFileAtLocation(sourceFile, position) {
  if (sourceFile.isDeclarationFile) {
    return void 0;
  }
  let tokenAtLocation = getTokenAtPosition(sourceFile, position);
  const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
  if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
    const preceding = findPrecedingToken(tokenAtLocation.pos, sourceFile);
    if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) {
      return void 0;
    }
    tokenAtLocation = preceding;
  }
  if (tokenAtLocation.flags & 16777216 /* Ambient */) {
    return void 0;
  }
  return spanInNode(tokenAtLocation);
  function textSpan(startNode2, endNode2) {
    const lastDecorator = canHaveDecorators(startNode2) ? findLast(startNode2.modifiers, isDecorator) : void 0;
    const start2 = lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : startNode2.getStart(sourceFile);
    return createTextSpanFromBounds(start2, (endNode2 || startNode2).getEnd());
  }
  function textSpanEndingAtNextToken(startNode2, previousTokenToFindNextEndToken) {
    return textSpan(startNode2, findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
  }
  function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
    if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
      return spanInNode(node);
    }
    return spanInNode(otherwiseOnNode);
  }
  function spanInNodeArray(nodeArray, node, match) {
    if (nodeArray) {
      const index = nodeArray.indexOf(node);
      if (index >= 0) {
        let start2 = index;
        let end = index + 1;
        while (start2 > 0 && match(nodeArray[start2 - 1]))
          start2--;
        while (end < nodeArray.length && match(nodeArray[end]))
          end++;
        return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray[start2].pos), nodeArray[end - 1].end);
      }
    }
    return textSpan(node);
  }
  function spanInPreviousNode(node) {
    return spanInNode(findPrecedingToken(node.pos, sourceFile));
  }
  function spanInNextNode(node) {
    return spanInNode(findNextToken(node, node.parent, sourceFile));
  }
  function spanInNode(node) {
    if (node) {
      const { parent: parent2 } = node;
      switch (node.kind) {
        case 242 /* VariableStatement */:
          return spanInVariableDeclaration(node.declarationList.declarations[0]);
        case 259 /* VariableDeclaration */:
        case 171 /* PropertyDeclaration */:
        case 170 /* PropertySignature */:
          return spanInVariableDeclaration(node);
        case 168 /* Parameter */:
          return spanInParameterDeclaration(node);
        case 261 /* FunctionDeclaration */:
        case 173 /* MethodDeclaration */:
        case 172 /* MethodSignature */:
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
        case 175 /* Constructor */:
        case 217 /* FunctionExpression */:
        case 218 /* ArrowFunction */:
          return spanInFunctionDeclaration(node);
        case 240 /* Block */:
          if (isFunctionBlock(node)) {
            return spanInFunctionBlock(node);
          }
        case 267 /* ModuleBlock */:
          return spanInBlock(node);
        case 298 /* CatchClause */:
          return spanInBlock(node.block);
        case 243 /* ExpressionStatement */:
          return textSpan(node.expression);
        case 252 /* ReturnStatement */:
          return textSpan(node.getChildAt(0), node.expression);
        case 246 /* WhileStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 245 /* DoStatement */:
          return spanInNode(node.statement);
        case 258 /* DebuggerStatement */:
          return textSpan(node.getChildAt(0));
        case 244 /* IfStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 255 /* LabeledStatement */:
          return spanInNode(node.statement);
        case 251 /* BreakStatement */:
        case 250 /* ContinueStatement */:
          return textSpan(node.getChildAt(0), node.label);
        case 247 /* ForStatement */:
          return spanInForStatement(node);
        case 248 /* ForInStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 249 /* ForOfStatement */:
          return spanInInitializerOfForLike(node);
        case 254 /* SwitchStatement */:
          return textSpanEndingAtNextToken(node, node.expression);
        case 295 /* CaseClause */:
        case 296 /* DefaultClause */:
          return spanInNode(node.statements[0]);
        case 257 /* TryStatement */:
          return spanInBlock(node.tryBlock);
        case 256 /* ThrowStatement */:
          return textSpan(node, node.expression);
        case 276 /* ExportAssignment */:
          return textSpan(node, node.expression);
        case 270 /* ImportEqualsDeclaration */:
          return textSpan(node, node.moduleReference);
        case 271 /* ImportDeclaration */:
          return textSpan(node, node.moduleSpecifier);
        case 277 /* ExportDeclaration */:
          return textSpan(node, node.moduleSpecifier);
        case 266 /* ModuleDeclaration */:
          if (getModuleInstanceState(node) !== 1 /* Instantiated */) {
            return void 0;
          }
        case 262 /* ClassDeclaration */:
        case 265 /* EnumDeclaration */:
        case 305 /* EnumMember */:
        case 207 /* BindingElement */:
          return textSpan(node);
        case 253 /* WithStatement */:
          return spanInNode(node.statement);
        case 169 /* Decorator */:
          return spanInNodeArray(parent2.modifiers, node, isDecorator);
        case 205 /* ObjectBindingPattern */:
        case 206 /* ArrayBindingPattern */:
          return spanInBindingPattern(node);
        case 263 /* InterfaceDeclaration */:
        case 264 /* TypeAliasDeclaration */:
          return void 0;
        case 27 /* SemicolonToken */:
        case 1 /* EndOfFileToken */:
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile));
        case 28 /* CommaToken */:
          return spanInPreviousNode(node);
        case 19 /* OpenBraceToken */:
          return spanInOpenBraceToken(node);
        case 20 /* CloseBraceToken */:
          return spanInCloseBraceToken(node);
        case 24 /* CloseBracketToken */:
          return spanInCloseBracketToken(node);
        case 21 /* OpenParenToken */:
          return spanInOpenParenToken(node);
        case 22 /* CloseParenToken */:
          return spanInCloseParenToken(node);
        case 59 /* ColonToken */:
          return spanInColonToken(node);
        case 32 /* GreaterThanToken */:
        case 30 /* LessThanToken */:
          return spanInGreaterThanOrLessThanToken(node);
        case 117 /* WhileKeyword */:
          return spanInWhileKeyword(node);
        case 93 /* ElseKeyword */:
        case 85 /* CatchKeyword */:
        case 98 /* FinallyKeyword */:
          return spanInNextNode(node);
        case 164 /* OfKeyword */:
          return spanInOfKeyword(node);
        default:
          if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
            return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node);
          }
          if ((node.kind === 80 /* Identifier */ || node.kind === 229 /* SpreadElement */ || node.kind === 302 /* PropertyAssignment */ || node.kind === 303 /* ShorthandPropertyAssignment */) && isArrayLiteralOrObjectLiteralDestructuringPattern(parent2)) {
            return textSpan(node);
          }
          if (node.kind === 225 /* BinaryExpression */) {
            const { left, operatorToken } = node;
            if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
              return spanInArrayLiteralOrObjectLiteralDestructuringPattern(
                left
              );
            }
            if (operatorToken.kind === 64 /* EqualsToken */ && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
              return textSpan(node);
            }
            if (operatorToken.kind === 28 /* CommaToken */) {
              return spanInNode(left);
            }
          }
          if (isExpressionNode(node)) {
            switch (parent2.kind) {
              case 245 /* DoStatement */:
                return spanInPreviousNode(node);
              case 169 /* Decorator */:
                return spanInNode(node.parent);
              case 247 /* ForStatement */:
              case 249 /* ForOfStatement */:
                return textSpan(node);
              case 225 /* BinaryExpression */:
                if (node.parent.operatorToken.kind === 28 /* CommaToken */) {
                  return textSpan(node);
                }
                break;
              case 218 /* ArrowFunction */:
                if (node.parent.body === node) {
                  return textSpan(node);
                }
                break;
            }
          }
          switch (node.parent.kind) {
            case 302 /* PropertyAssignment */:
              if (node.parent.name === node && !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
                return spanInNode(node.parent.initializer);
              }
              break;
            case 215 /* TypeAssertionExpression */:
              if (node.parent.type === node) {
                return spanInNextNode(node.parent.type);
              }
              break;
            case 259 /* VariableDeclaration */:
            case 168 /* Parameter */: {
              const { initializer, type } = node.parent;
              if (initializer === node || type === node || isAssignmentOperator(node.kind)) {
                return spanInPreviousNode(node);
              }
              break;
            }
            case 225 /* BinaryExpression */: {
              const { left } = node.parent;
              if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
                return spanInPreviousNode(node);
              }
              break;
            }
            default:
              if (isFunctionLike(node.parent) && node.parent.type === node) {
                return spanInPreviousNode(node);
              }
          }
          return spanInNode(node.parent);
      }
    }
    function textSpanFromVariableDeclaration(variableDeclaration) {
      if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
        return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
      } else {
        return textSpan(variableDeclaration);
      }
    }
    function spanInVariableDeclaration(variableDeclaration) {
      if (variableDeclaration.parent.parent.kind === 248 /* ForInStatement */) {
        return spanInNode(variableDeclaration.parent.parent);
      }
      const parent2 = variableDeclaration.parent;
      if (isBindingPattern(variableDeclaration.name)) {
        return spanInBindingPattern(variableDeclaration.name);
      }
      if (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer || hasSyntacticModifier(variableDeclaration, 1 /* Export */) || parent2.parent.kind === 249 /* ForOfStatement */) {
        return textSpanFromVariableDeclaration(variableDeclaration);
      }
      if (isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] !== variableDeclaration) {
        return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
      }
    }
    function canHaveSpanInParameterDeclaration(parameter) {
      return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 4 /* Public */ | 8 /* Private */);
    }
    function spanInParameterDeclaration(parameter) {
      if (isBindingPattern(parameter.name)) {
        return spanInBindingPattern(parameter.name);
      } else if (canHaveSpanInParameterDeclaration(parameter)) {
        return textSpan(parameter);
      } else {
        const functionDeclaration = parameter.parent;
        const indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
        Debug.assert(indexOfParameter !== -1);
        if (indexOfParameter !== 0) {
          return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
        } else {
          return spanInNode(functionDeclaration.body);
        }
      }
    }
    function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
      return hasSyntacticModifier(functionDeclaration, 1 /* Export */) || functionDeclaration.parent.kind === 262 /* ClassDeclaration */ && functionDeclaration.kind !== 175 /* Constructor */;
    }
    function spanInFunctionDeclaration(functionDeclaration) {
      if (!functionDeclaration.body) {
        return void 0;
      }
      if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
        return textSpan(functionDeclaration);
      }
      return spanInNode(functionDeclaration.body);
    }
    function spanInFunctionBlock(block) {
      const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
      if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
        return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
      }
      return spanInNode(nodeForSpanInBlock);
    }
    function spanInBlock(block) {
      switch (block.parent.kind) {
        case 266 /* ModuleDeclaration */:
          if (getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
            return void 0;
          }
        case 246 /* WhileStatement */:
        case 244 /* IfStatement */:
        case 248 /* ForInStatement */:
          return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
        case 247 /* ForStatement */:
        case 249 /* ForOfStatement */:
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
      }
      return spanInNode(block.statements[0]);
    }
    function spanInInitializerOfForLike(forLikeStatement) {
      if (forLikeStatement.initializer.kind === 260 /* VariableDeclarationList */) {
        const variableDeclarationList = forLikeStatement.initializer;
        if (variableDeclarationList.declarations.length > 0) {
          return spanInNode(variableDeclarationList.declarations[0]);
        }
      } else {
        return spanInNode(forLikeStatement.initializer);
      }
    }
    function spanInForStatement(forStatement) {
      if (forStatement.initializer) {
        return spanInInitializerOfForLike(forStatement);
      }
      if (forStatement.condition) {
        return textSpan(forStatement.condition);
      }
      if (forStatement.incrementor) {
        return textSpan(forStatement.incrementor);
      }
    }
    function spanInBindingPattern(bindingPattern) {
      const firstBindingElement = forEach(
        bindingPattern.elements,
        (element) => element.kind !== 231 /* OmittedExpression */ ? element : void 0
      );
      if (firstBindingElement) {
        return spanInNode(firstBindingElement);
      }
      if (bindingPattern.parent.kind === 207 /* BindingElement */) {
        return textSpan(bindingPattern.parent);
      }
      return textSpanFromVariableDeclaration(bindingPattern.parent);
    }
    function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node2) {
      Debug.assert(node2.kind !== 206 /* ArrayBindingPattern */ && node2.kind !== 205 /* ObjectBindingPattern */);
      const elements = node2.kind === 208 /* ArrayLiteralExpression */ ? node2.elements : node2.properties;
      const firstBindingElement = forEach(
        elements,
        (element) => element.kind !== 231 /* OmittedExpression */ ? element : void 0
      );
      if (firstBindingElement) {
        return spanInNode(firstBindingElement);
      }
      return textSpan(node2.parent.kind === 225 /* BinaryExpression */ ? node2.parent : node2);
    }
    function spanInOpenBraceToken(node2) {
      switch (node2.parent.kind) {
        case 265 /* EnumDeclaration */:
          const enumDeclaration = node2.parent;
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
        case 262 /* ClassDeclaration */:
          const classDeclaration = node2.parent;
          return spanInNodeIfStartsOnSameLine(findPrecedingToken(node2.pos, sourceFile, node2.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
        case 268 /* CaseBlock */:
          return spanInNodeIfStartsOnSameLine(node2.parent.parent, node2.parent.clauses[0]);
      }
      return spanInNode(node2.parent);
    }
    function spanInCloseBraceToken(node2) {
      switch (node2.parent.kind) {
        case 267 /* ModuleBlock */:
          if (getModuleInstanceState(node2.parent.parent) !== 1 /* Instantiated */) {
            return void 0;
          }
        case 265 /* EnumDeclaration */:
        case 262 /* ClassDeclaration */:
          return textSpan(node2);
        case 240 /* Block */:
          if (isFunctionBlock(node2.parent)) {
            return textSpan(node2);
          }
        case 298 /* CatchClause */:
          return spanInNode(lastOrUndefined(node2.parent.statements));
        case 268 /* CaseBlock */:
          const caseBlock = node2.parent;
          const lastClause = lastOrUndefined(caseBlock.clauses);
          if (lastClause) {
            return spanInNode(lastOrUndefined(lastClause.statements));
          }
          return void 0;
        case 205 /* ObjectBindingPattern */:
          const bindingPattern = node2.parent;
          return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern);
        default:
          if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) {
            const objectLiteral = node2.parent;
            return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral);
          }
          return spanInNode(node2.parent);
      }
    }
    function spanInCloseBracketToken(node2) {
      switch (node2.parent.kind) {
        case 206 /* ArrayBindingPattern */:
          const bindingPattern = node2.parent;
          return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern);
        default:
          if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) {
            const arrayLiteral = node2.parent;
            return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
          }
          return spanInNode(node2.parent);
      }
    }
    function spanInOpenParenToken(node2) {
      if (node2.parent.kind === 245 /* DoStatement */ || // Go to while keyword and do action instead
      node2.parent.kind === 212 /* CallExpression */ || node2.parent.kind === 213 /* NewExpression */) {
        return spanInPreviousNode(node2);
      }
      if (node2.parent.kind === 216 /* ParenthesizedExpression */) {
        return spanInNextNode(node2);
      }
      return spanInNode(node2.parent);
    }
    function spanInCloseParenToken(node2) {
      switch (node2.parent.kind) {
        case 217 /* FunctionExpression */:
        case 261 /* FunctionDeclaration */:
        case 218 /* ArrowFunction */:
        case 173 /* MethodDeclaration */:
        case 172 /* MethodSignature */:
        case 176 /* GetAccessor */:
        case 177 /* SetAccessor */:
        case 175 /* Constructor */:
        case 246 /* WhileStatement */:
        case 245 /* DoStatement */:
        case 247 /* ForStatement */:
        case 249 /* ForOfStatement */:
        case 212 /* CallExpression */:
        case 213 /* NewExpression */:
        case 216 /* ParenthesizedExpression */:
          return spanInPreviousNode(node2);
        default:
          return spanInNode(node2.parent);
      }
    }
    function spanInColonToken(node2) {
      if (isFunctionLike(node2.parent) || node2.parent.kind === 302 /* PropertyAssignment */ || node2.parent.kind === 168 /* Parameter */) {
        return spanInPreviousNode(node2);
      }
      return spanInNode(node2.parent);
    }
    function spanInGreaterThanOrLessThanToken(node2) {
      if (node2.parent.kind === 215 /* TypeAssertionExpression */) {
        return spanInNextNode(node2);
      }
      return spanInNode(node2.parent);
    }
    function spanInWhileKeyword(node2) {
      if (node2.parent.kind === 245 /* DoStatement */) {
        return textSpanEndingAtNextToken(node2, node2.parent.expression);
      }
      return spanInNode(node2.parent);
    }
    function spanInOfKeyword(node2) {
      if (node2.parent.kind === 249 /* ForOfStatement */) {
        return spanInNextNode(node2);
      }
      return spanInNode(node2.parent);
    }
  }
}

// src/services/_namespaces/ts.CallHierarchy.ts
var ts_CallHierarchy_exports = {};
__export(ts_CallHierarchy_exports, {
  createCallHierarchyItem: () => createCallHierarchyItem,
  getIncomingCalls: () => getIncomingCalls,
  getOutgoingCalls: () => getOutgoingCalls,
  resolveCallHierarchyDeclaration: () => resolveCallHierarchyDeclaration
});

// src/services/callHierarchy.ts
function isNamedExpression(node) {
  return (isFunctionExpression(node) || isClassExpression(node)) && isNamedDeclaration(node);
}
function isConstNamedExpression(node) {
  return (isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)) && isVariableDeclaration(node.parent) && node === node.parent.initializer && isIdentifier(node.parent.name) && !!(getCombinedNodeFlags(node.parent) & 2 /* Const */);
}
function isPossibleCallHierarchyDeclaration(node) {
  return isSourceFile(node) || isModuleDeclaration(node) || isFunctionDeclaration(node) || isFunctionExpression(node) || isClassDeclaration(node) || isClassExpression(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node);
}
function isValidCallHierarchyDeclaration(node) {
  return isSourceFile(node) || isModuleDeclaration(node) && isIdentifier(node.name) || isFunctionDeclaration(node) || isClassDeclaration(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node) || isNamedExpression(node) || isConstNamedExpression(node);
}
function getCallHierarchyDeclarationReferenceNode(node) {
  if (isSourceFile(node))
    return node;
  if (isNamedDeclaration(node))
    return node.name;
  if (isConstNamedExpression(node))
    return node.parent.name;
  return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier3));
}
function isDefaultModifier3(node) {
  return node.kind === 90 /* DefaultKeyword */;
}
function getSymbolOfCallHierarchyDeclaration(typeChecker, node) {
  const location = getCallHierarchyDeclarationReferenceNode(node);
  return location && typeChecker.getSymbolAtLocation(location);
}
function getCallHierarchyItemName(program, node) {
  if (isSourceFile(node)) {
    return { text: node.fileName, pos: 0, end: 0 };
  }
  if ((isFunctionDeclaration(node) || isClassDeclaration(node)) && !isNamedDeclaration(node)) {
    const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier3);
    if (defaultModifier) {
      return { text: "default", pos: defaultModifier.getStart(), end: defaultModifier.getEnd() };
    }
  }
  if (isClassStaticBlockDeclaration(node)) {
    const sourceFile = node.getSourceFile();
    const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(node).pos);
    const end = pos + 6;
    const typeChecker = program.getTypeChecker();
    const symbol = typeChecker.getSymbolAtLocation(node.parent);
    const prefix = symbol ? `${typeChecker.symbolToString(symbol, node.parent)} ` : "";
    return { text: `${prefix}static {}`, pos, end };
  }
  const declName = isConstNamedExpression(node) ? node.parent.name : Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
  let text = isIdentifier(declName) ? idText(declName) : isStringOrNumericLiteralLike(declName) ? declName.text : isComputedPropertyName(declName) ? isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : void 0 : void 0;
  if (text === void 0) {
    const typeChecker = program.getTypeChecker();
    const symbol = typeChecker.getSymbolAtLocation(declName);
    if (symbol) {
      text = typeChecker.symbolToString(symbol, node);
    }
  }
  if (text === void 0) {
    const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon();
    text = usingSingleLineStringWriter((writer) => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer));
  }
  return { text, pos: declName.getStart(), end: declName.getEnd() };
}
function getCallHierarchItemContainerName(node) {
  var _a, _b;
  if (isConstNamedExpression(node)) {
    if (isModuleBlock(node.parent.parent.parent.parent) && isIdentifier(node.parent.parent.parent.parent.parent.name)) {
      return node.parent.parent.parent.parent.parent.name.getText();
    }
    return;
  }
  switch (node.kind) {
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 173 /* MethodDeclaration */:
      if (node.parent.kind === 209 /* ObjectLiteralExpression */) {
        return (_a = getAssignedName(node.parent)) == null ? void 0 : _a.getText();
      }
      return (_b = getNameOfDeclaration(node.parent)) == null ? void 0 : _b.getText();
    case 261 /* FunctionDeclaration */:
    case 262 /* ClassDeclaration */:
    case 266 /* ModuleDeclaration */:
      if (isModuleBlock(node.parent) && isIdentifier(node.parent.parent.name)) {
        return node.parent.parent.name.getText();
      }
  }
}
function findImplementation(typeChecker, node) {
  if (node.body) {
    return node;
  }
  if (isConstructorDeclaration(node)) {
    return getFirstConstructorWithBody(node.parent);
  }
  if (isFunctionDeclaration(node) || isMethodDeclaration(node)) {
    const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
    if (symbol && symbol.valueDeclaration && isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) {
      return symbol.valueDeclaration;
    }
    return void 0;
  }
  return node;
}
function findAllInitialDeclarations(typeChecker, node) {
  const symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
  let declarations;
  if (symbol && symbol.declarations) {
    const indices = indicesOf(symbol.declarations);
    const keys = map(symbol.declarations, (decl) => ({ file: decl.getSourceFile().fileName, pos: decl.pos }));
    indices.sort((a, b) => compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos);
    const sortedDeclarations = map(indices, (i) => symbol.declarations[i]);
    let lastDecl;
    for (const decl of sortedDeclarations) {
      if (isValidCallHierarchyDeclaration(decl)) {
        if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) {
          declarations = append(declarations, decl);
        }
        lastDecl = decl;
      }
    }
  }
  return declarations;
}
function findImplementationOrAllInitialDeclarations(typeChecker, node) {
  if (isClassStaticBlockDeclaration(node)) {
    return node;
  }
  if (isFunctionLikeDeclaration(node)) {
    return findImplementation(typeChecker, node) ?? findAllInitialDeclarations(typeChecker, node) ?? node;
  }
  return findAllInitialDeclarations(typeChecker, node) ?? node;
}
function resolveCallHierarchyDeclaration(program, location) {
  const typeChecker = program.getTypeChecker();
  let followingSymbol = false;
  while (true) {
    if (isValidCallHierarchyDeclaration(location)) {
      return findImplementationOrAllInitialDeclarations(typeChecker, location);
    }
    if (isPossibleCallHierarchyDeclaration(location)) {
      const ancestor = findAncestor(location, isValidCallHierarchyDeclaration);
      return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
    }
    if (isDeclarationName(location)) {
      if (isValidCallHierarchyDeclaration(location.parent)) {
        return findImplementationOrAllInitialDeclarations(typeChecker, location.parent);
      }
      if (isPossibleCallHierarchyDeclaration(location.parent)) {
        const ancestor = findAncestor(location.parent, isValidCallHierarchyDeclaration);
        return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
      }
      if (isVariableDeclaration(location.parent) && location.parent.initializer && isConstNamedExpression(location.parent.initializer)) {
        return location.parent.initializer;
      }
      return void 0;
    }
    if (isConstructorDeclaration(location)) {
      if (isValidCallHierarchyDeclaration(location.parent)) {
        return location.parent;
      }
      return void 0;
    }
    if (location.kind === 126 /* StaticKeyword */ && isClassStaticBlockDeclaration(location.parent)) {
      location = location.parent;
      continue;
    }
    if (isVariableDeclaration(location) && location.initializer && isConstNamedExpression(location.initializer)) {
      return location.initializer;
    }
    if (!followingSymbol) {
      let symbol = typeChecker.getSymbolAtLocation(location);
      if (symbol) {
        if (symbol.flags & 2097152 /* Alias */) {
          symbol = typeChecker.getAliasedSymbol(symbol);
        }
        if (symbol.valueDeclaration) {
          followingSymbol = true;
          location = symbol.valueDeclaration;
          continue;
        }
      }
    }
    return void 0;
  }
}
function createCallHierarchyItem(program, node) {
  const sourceFile = node.getSourceFile();
  const name = getCallHierarchyItemName(program, node);
  const containerName = getCallHierarchItemContainerName(node);
  const kind = getNodeKind(node);
  const kindModifiers = getNodeModifiers(node);
  const span = createTextSpanFromBounds(skipTrivia(
    sourceFile.text,
    node.getFullStart(),
    /*stopAfterLineBreak*/
    false,
    /*stopAtComments*/
    true
  ), node.getEnd());
  const selectionSpan = createTextSpanFromBounds(name.pos, name.end);
  return { file: sourceFile.fileName, kind, kindModifiers, name: name.text, containerName, span, selectionSpan };
}
function isDefined(x) {
  return x !== void 0;
}
function convertEntryToCallSite(entry) {
  if (entry.kind === ts_FindAllReferences_exports.EntryKind.Node) {
    const { node } = entry;
    if (isCallOrNewExpressionTarget(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isTaggedTemplateTag(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isDecoratorTarget(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isJsxOpeningLikeElementTagName(
      node,
      /*includeElementAccess*/
      true,
      /*skipPastOuterExpressions*/
      true
    ) || isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node)) {
      const sourceFile = node.getSourceFile();
      const ancestor = findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile;
      return { declaration: ancestor, range: createTextRangeFromNode(node, sourceFile) };
    }
  }
}
function getCallSiteGroupKey(entry) {
  return getNodeId(entry.declaration);
}
function createCallHierarchyIncomingCall(from, fromSpans) {
  return { from, fromSpans };
}
function convertCallSiteGroupToIncomingCall(program, entries) {
  return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry) => createTextSpanFromRange(entry.range)));
}
function getIncomingCalls(program, declaration, cancellationToken) {
  if (isSourceFile(declaration) || isModuleDeclaration(declaration) || isClassStaticBlockDeclaration(declaration)) {
    return [];
  }
  const location = getCallHierarchyDeclarationReferenceNode(declaration);
  const calls = filter(ts_FindAllReferences_exports.findReferenceOrRenameEntries(
    program,
    cancellationToken,
    program.getSourceFiles(),
    location,
    /*position*/
    0,
    { use: ts_FindAllReferences_exports.FindReferencesUse.References },
    convertEntryToCallSite
  ), isDefined);
  return calls ? group(calls, getCallSiteGroupKey, (entries) => convertCallSiteGroupToIncomingCall(program, entries)) : [];
}
function createCallSiteCollector(program, callSites) {
  function recordCallSite(node) {
    const target = isTaggedTemplateExpression(node) ? node.tag : isJsxOpeningLikeElement(node) ? node.tagName : isAccessExpression(node) ? node : isClassStaticBlockDeclaration(node) ? node : node.expression;
    const declaration = resolveCallHierarchyDeclaration(program, target);
    if (declaration) {
      const range = createTextRangeFromNode(target, node.getSourceFile());
      if (isArray(declaration)) {
        for (const decl of declaration) {
          callSites.push({ declaration: decl, range });
        }
      } else {
        callSites.push({ declaration, range });
      }
    }
  }
  function collect(node) {
    if (!node)
      return;
    if (node.flags & 16777216 /* Ambient */) {
      return;
    }
    if (isValidCallHierarchyDeclaration(node)) {
      if (isClassLike(node)) {
        for (const member of node.members) {
          if (member.name && isComputedPropertyName(member.name)) {
            collect(member.name.expression);
          }
        }
      }
      return;
    }
    switch (node.kind) {
      case 80 /* Identifier */:
      case 270 /* ImportEqualsDeclaration */:
      case 271 /* ImportDeclaration */:
      case 277 /* ExportDeclaration */:
      case 263 /* InterfaceDeclaration */:
      case 264 /* TypeAliasDeclaration */:
        return;
      case 174 /* ClassStaticBlockDeclaration */:
        recordCallSite(node);
        return;
      case 215 /* TypeAssertionExpression */:
      case 233 /* AsExpression */:
        collect(node.expression);
        return;
      case 259 /* VariableDeclaration */:
      case 168 /* Parameter */:
        collect(node.name);
        collect(node.initializer);
        return;
      case 212 /* CallExpression */:
        recordCallSite(node);
        collect(node.expression);
        forEach(node.arguments, collect);
        return;
      case 213 /* NewExpression */:
        recordCallSite(node);
        collect(node.expression);
        forEach(node.arguments, collect);
        return;
      case 214 /* TaggedTemplateExpression */:
        recordCallSite(node);
        collect(node.tag);
        collect(node.template);
        return;
      case 285 /* JsxOpeningElement */:
      case 284 /* JsxSelfClosingElement */:
        recordCallSite(node);
        collect(node.tagName);
        collect(node.attributes);
        return;
      case 169 /* Decorator */:
        recordCallSite(node);
        collect(node.expression);
        return;
      case 210 /* PropertyAccessExpression */:
      case 211 /* ElementAccessExpression */:
        recordCallSite(node);
        forEachChild(node, collect);
        break;
      case 237 /* SatisfiesExpression */:
        collect(node.expression);
        return;
    }
    if (isPartOfTypeNode(node)) {
      return;
    }
    forEachChild(node, collect);
  }
  return collect;
}
function collectCallSitesOfSourceFile(node, collect) {
  forEach(node.statements, collect);
}
function collectCallSitesOfModuleDeclaration(node, collect) {
  if (!hasSyntacticModifier(node, 2 /* Ambient */) && node.body && isModuleBlock(node.body)) {
    forEach(node.body.statements, collect);
  }
}
function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) {
  const implementation = findImplementation(typeChecker, node);
  if (implementation) {
    forEach(implementation.parameters, collect);
    collect(implementation.body);
  }
}
function collectCallSitesOfClassStaticBlockDeclaration(node, collect) {
  collect(node.body);
}
function collectCallSitesOfClassLikeDeclaration(node, collect) {
  forEach(node.modifiers, collect);
  const heritage = getClassExtendsHeritageElement(node);
  if (heritage) {
    collect(heritage.expression);
  }
  for (const member of node.members) {
    if (canHaveModifiers(member)) {
      forEach(member.modifiers, collect);
    }
    if (isPropertyDeclaration(member)) {
      collect(member.initializer);
    } else if (isConstructorDeclaration(member) && member.body) {
      forEach(member.parameters, collect);
      collect(member.body);
    } else if (isClassStaticBlockDeclaration(member)) {
      collect(member);
    }
  }
}
function collectCallSites(program, node) {
  const callSites = [];
  const collect = createCallSiteCollector(program, callSites);
  switch (node.kind) {
    case 311 /* SourceFile */:
      collectCallSitesOfSourceFile(node, collect);
      break;
    case 266 /* ModuleDeclaration */:
      collectCallSitesOfModuleDeclaration(node, collect);
      break;
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
    case 173 /* MethodDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
      collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect);
      break;
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
      collectCallSitesOfClassLikeDeclaration(node, collect);
      break;
    case 174 /* ClassStaticBlockDeclaration */:
      collectCallSitesOfClassStaticBlockDeclaration(node, collect);
      break;
    default:
      Debug.assertNever(node);
  }
  return callSites;
}
function createCallHierarchyOutgoingCall(to, fromSpans) {
  return { to, fromSpans };
}
function convertCallSiteGroupToOutgoingCall(program, entries) {
  return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry) => createTextSpanFromRange(entry.range)));
}
function getOutgoingCalls(program, declaration) {
  if (declaration.flags & 16777216 /* Ambient */ || isMethodSignature(declaration)) {
    return [];
  }
  return group(collectCallSites(program, declaration), getCallSiteGroupKey, (entries) => convertCallSiteGroupToOutgoingCall(program, entries));
}

// src/services/_namespaces/ts.classifier.ts
var ts_classifier_exports = {};
__export(ts_classifier_exports, {
  v2020: () => ts_classifier_v2020_exports
});

// src/services/_namespaces/ts.classifier.v2020.ts
var ts_classifier_v2020_exports = {};
__export(ts_classifier_v2020_exports, {
  TokenEncodingConsts: () => TokenEncodingConsts,
  TokenModifier: () => TokenModifier,
  TokenType: () => TokenType,
  getEncodedSemanticClassifications: () => getEncodedSemanticClassifications2,
  getSemanticClassifications: () => getSemanticClassifications2
});

// src/services/_namespaces/ts.codefix.ts
var ts_codefix_exports = {};
__export(ts_codefix_exports, {
  PreserveOptionalFlags: () => PreserveOptionalFlags,
  addNewNodeForMemberSymbol: () => addNewNodeForMemberSymbol,
  codeFixAll: () => codeFixAll,
  createCodeFixAction: () => createCodeFixAction,
  createCodeFixActionMaybeFixAll: () => createCodeFixActionMaybeFixAll,
  createCodeFixActionWithoutFixAll: () => createCodeFixActionWithoutFixAll,
  createCombinedCodeActions: () => createCombinedCodeActions,
  createFileTextChanges: () => createFileTextChanges,
  createImportAdder: () => createImportAdder,
  createImportSpecifierResolver: () => createImportSpecifierResolver,
  createJsonPropertyAssignment: () => createJsonPropertyAssignment,
  createMissingMemberNodes: () => createMissingMemberNodes,
  createSignatureDeclarationFromCallExpression: () => createSignatureDeclarationFromCallExpression,
  createSignatureDeclarationFromSignature: () => createSignatureDeclarationFromSignature,
  createStubbedBody: () => createStubbedBody,
  eachDiagnostic: () => eachDiagnostic,
  findAncestorMatchingSpan: () => findAncestorMatchingSpan,
  findJsonProperty: () => findJsonProperty,
  generateAccessorFromProperty: () => generateAccessorFromProperty,
  getAccessorConvertiblePropertyAtPosition: () => getAccessorConvertiblePropertyAtPosition,
  getAllFixes: () => getAllFixes,
  getAllSupers: () => getAllSupers,
  getArgumentTypesAndTypeParameters: () => getArgumentTypesAndTypeParameters,
  getFixes: () => getFixes,
  getImportCompletionAction: () => getImportCompletionAction,
  getImportKind: () => getImportKind,
  getJSDocTypedefNode: () => getJSDocTypedefNode,
  getNoopSymbolTrackerWithResolver: () => getNoopSymbolTrackerWithResolver,
  getPromoteTypeOnlyCompletionAction: () => getPromoteTypeOnlyCompletionAction,
  getSupportedErrorCodes: () => getSupportedErrorCodes,
  importFixName: () => importFixName,
  importSymbols: () => importSymbols,
  moduleSpecifierToValidIdentifier: () => moduleSpecifierToValidIdentifier,
  moduleSymbolToValidIdentifier: () => moduleSymbolToValidIdentifier,
  parameterShouldGetTypeFromJSDoc: () => parameterShouldGetTypeFromJSDoc,
  registerCodeFix: () => registerCodeFix,
  setJsonCompilerOptionValue: () => setJsonCompilerOptionValue,
  setJsonCompilerOptionValues: () => setJsonCompilerOptionValues,
  tryGetAutoImportableReferenceFromTypeNode: () => tryGetAutoImportableReferenceFromTypeNode,
  typeToAutoImportableTypeNode: () => typeToAutoImportableTypeNode
});

// src/services/codeFixProvider.ts
var errorCodeToFixes = createMultiMap();
var fixIdToRegistration = /* @__PURE__ */ new Map();
function createCodeFixActionWithoutFixAll(fixName8, changes, description3) {
  return createCodeFixActionWorker(
    fixName8,
    diagnosticToString(description3),
    changes,
    /*fixId*/
    void 0,
    /*fixAllDescription*/
    void 0
  );
}
function createCodeFixAction(fixName8, changes, description3, fixId52, fixAllDescription, command) {
  return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, diagnosticToString(fixAllDescription), command);
}
function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId52, fixAllDescription, command) {
  return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command);
}
function createCodeFixActionWorker(fixName8, description3, changes, fixId52, fixAllDescription, command) {
  return { fixName: fixName8, description: description3, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 };
}
function registerCodeFix(reg) {
  for (const error of reg.errorCodes) {
    errorCodeToFixesArray = void 0;
    errorCodeToFixes.add(String(error), reg);
  }
  if (reg.fixIds) {
    for (const fixId52 of reg.fixIds) {
      Debug.assert(!fixIdToRegistration.has(fixId52));
      fixIdToRegistration.set(fixId52, reg);
    }
  }
}
var errorCodeToFixesArray;
function getSupportedErrorCodes() {
  return errorCodeToFixesArray ?? (errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys()));
}
function removeFixIdIfFixAllUnavailable(registration, diagnostics) {
  const { errorCodes: errorCodes64 } = registration;
  let maybeFixableDiagnostics = 0;
  for (const diag2 of diagnostics) {
    if (contains(errorCodes64, diag2.code))
      maybeFixableDiagnostics++;
    if (maybeFixableDiagnostics > 1)
      break;
  }
  const fixAllUnavailable = maybeFixableDiagnostics < 2;
  return ({ fixId: fixId52, fixAllDescription, ...action }) => {
    return fixAllUnavailable ? action : { ...action, fixId: fixId52, fixAllDescription };
  };
}
function getFixes(context) {
  const diagnostics = getDiagnostics(context);
  const registrations = errorCodeToFixes.get(String(context.errorCode));
  return flatMap(registrations, (f) => map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)));
}
function getAllFixes(context) {
  return fixIdToRegistration.get(cast(context.fixId, isString)).getAllCodeActions(context);
}
function createCombinedCodeActions(changes, commands) {
  return { changes, commands };
}
function createFileTextChanges(fileName, textChanges2) {
  return { fileName, textChanges: textChanges2 };
}
function codeFixAll(context, errorCodes64, use) {
  const commands = [];
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes64, (diag2) => use(t, diag2, commands)));
  return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands);
}
function eachDiagnostic(context, errorCodes64, cb) {
  for (const diag2 of getDiagnostics(context)) {
    if (contains(errorCodes64, diag2.code)) {
      cb(diag2);
    }
  }
}
function getDiagnostics({ program, sourceFile, cancellationToken }) {
  return [
    ...program.getSemanticDiagnostics(sourceFile, cancellationToken),
    ...program.getSyntacticDiagnostics(sourceFile, cancellationToken),
    ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken)
  ];
}

// src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts
var fixId = "addConvertToUnknownForNonOverlappingTypes";
var errorCodes = [Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code];
registerCodeFix({
  errorCodes,
  getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) {
    const assertion = getAssertion(context.sourceFile, context.span.start);
    if (assertion === void 0)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange(t, context.sourceFile, assertion));
    return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)];
  },
  fixIds: [fixId],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes, (changes, diag2) => {
    const assertion = getAssertion(diag2.file, diag2.start);
    if (assertion) {
      makeChange(changes, diag2.file, assertion);
    }
  })
});
function makeChange(changeTracker, sourceFile, assertion) {
  const replacement = isAsExpression(assertion) ? factory.createAsExpression(assertion.expression, factory.createKeywordTypeNode(159 /* UnknownKeyword */)) : factory.createTypeAssertion(factory.createKeywordTypeNode(159 /* UnknownKeyword */), assertion.expression);
  changeTracker.replaceNode(sourceFile, assertion.expression, replacement);
}
function getAssertion(sourceFile, pos) {
  if (isInJSFile(sourceFile))
    return void 0;
  return findAncestor(getTokenAtPosition(sourceFile, pos), (n) => isAsExpression(n) || isTypeAssertionExpression(n));
}

// src/services/codefixes/addEmptyExportDeclaration.ts
registerCodeFix({
  errorCodes: [
    Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code,
    Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code
  ],
  getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) {
    const { sourceFile } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
      const exportDeclaration = factory.createExportDeclaration(
        /*modifiers*/
        void 0,
        /*isTypeOnly*/
        false,
        factory.createNamedExports([]),
        /*moduleSpecifier*/
        void 0
      );
      changes2.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration);
    });
    return [createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, Diagnostics.Add_export_to_make_this_file_into_a_module)];
  }
});

// src/services/codefixes/addMissingAsync.ts
var fixId2 = "addMissingAsync";
var errorCodes2 = [
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  Diagnostics.Type_0_is_not_comparable_to_type_1.code
];
registerCodeFix({
  fixIds: [fixId2],
  errorCodes: errorCodes2,
  getCodeActions: function getCodeActionsToAddMissingAsync(context) {
    const { sourceFile, errorCode, cancellationToken, program, span } = context;
    const diagnostic = find(program.getTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode));
    const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r) => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
    const decl = getFixableErrorSpanDeclaration(sourceFile, directSpan);
    if (!decl) {
      return;
    }
    const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context, cb);
    return [getFix(context, decl, trackChanges)];
  },
  getAllCodeActions: (context) => {
    const { sourceFile } = context;
    const fixedDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes2, (t, diagnostic) => {
      const span = diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r) => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
      const decl = getFixableErrorSpanDeclaration(sourceFile, span);
      if (!decl) {
        return;
      }
      const trackChanges = (cb) => (cb(t), []);
      return getFix(context, decl, trackChanges, fixedDeclarations);
    });
  }
});
function getFix(context, decl, trackChanges, fixedDeclarations) {
  const changes = trackChanges((t) => makeChange2(t, context.sourceFile, decl, fixedDeclarations));
  return createCodeFixAction(fixId2, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId2, Diagnostics.Add_all_missing_async_modifiers);
}
function makeChange2(changeTracker, sourceFile, insertionSite, fixedDeclarations) {
  if (fixedDeclarations) {
    if (fixedDeclarations.has(getNodeId(insertionSite))) {
      return;
    }
  }
  fixedDeclarations == null ? void 0 : fixedDeclarations.add(getNodeId(insertionSite));
  const cloneWithModifier = factory.updateModifiers(
    getSynthesizedDeepClone(
      insertionSite,
      /*includeTrivia*/
      true
    ),
    factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 512 /* Async */))
  );
  changeTracker.replaceNode(
    sourceFile,
    insertionSite,
    cloneWithModifier
  );
}
function getFixableErrorSpanDeclaration(sourceFile, span) {
  if (!span)
    return void 0;
  const token = getTokenAtPosition(sourceFile, span.start);
  const decl = findAncestor(token, (node) => {
    if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) {
      return "quit";
    }
    return (isArrowFunction(node) || isMethodDeclaration(node) || isFunctionExpression(node) || isFunctionDeclaration(node)) && textSpansEqual(span, createTextSpanFromNode(node, sourceFile));
  });
  return decl;
}
function getIsMatchingAsyncError(span, errorCode) {
  return ({ start: start2, length: length2, relatedInformation, code }) => isNumber(start2) && isNumber(length2) && textSpansEqual({ start: start2, length: length2 }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
}

// src/services/codefixes/addMissingAwait.ts
var fixId3 = "addMissingAwait";
var propertyAccessCode = Diagnostics.Property_0_does_not_exist_on_type_1.code;
var callableConstructableErrorCodes = [
  Diagnostics.This_expression_is_not_callable.code,
  Diagnostics.This_expression_is_not_constructable.code
];
var errorCodes3 = [
  Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
  Diagnostics.Operator_0_cannot_be_applied_to_type_1.code,
  Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code,
  Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code,
  Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code,
  Diagnostics.Type_0_is_not_an_array_type.code,
  Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code,
  Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher.code,
  Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
  Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  propertyAccessCode,
  ...callableConstructableErrorCodes
];
registerCodeFix({
  fixIds: [fixId3],
  errorCodes: errorCodes3,
  getCodeActions: function getCodeActionsToAddMissingAwait(context) {
    const { sourceFile, errorCode, span, cancellationToken, program } = context;
    const expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program);
    if (!expression) {
      return;
    }
    const checker = context.program.getTypeChecker();
    const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context, cb);
    return compact([
      getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges),
      getUseSiteFix(context, expression, errorCode, checker, trackChanges)
    ]);
  },
  getAllCodeActions: (context) => {
    const { sourceFile, program, cancellationToken } = context;
    const checker = context.program.getTypeChecker();
    const fixedDeclarations = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes3, (t, diagnostic) => {
      const expression = getAwaitErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program);
      if (!expression) {
        return;
      }
      const trackChanges = (cb) => (cb(t), []);
      return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations) || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations);
    });
  }
});
function getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) {
  const expression = getFixableErrorSpanExpression(sourceFile, span);
  return expression && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) && isInsideAwaitableBody(expression) ? expression : void 0;
}
function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
  const { sourceFile, program, cancellationToken } = context;
  const awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker);
  if (awaitableInitializers) {
    const initializerChanges = trackChanges((t) => {
      forEach(awaitableInitializers.initializers, ({ expression: expression2 }) => makeChange3(t, errorCode, sourceFile, checker, expression2, fixedDeclarations));
      if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) {
        makeChange3(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
      }
    });
    return createCodeFixActionWithoutFixAll(
      "addMissingAwaitToInitializer",
      initializerChanges,
      awaitableInitializers.initializers.length === 1 ? [Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : Diagnostics.Add_await_to_initializers
    );
  }
}
function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
  const changes = trackChanges((t) => makeChange3(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations));
  return createCodeFixAction(fixId3, changes, Diagnostics.Add_await, fixId3, Diagnostics.Fix_all_expressions_possibly_missing_await);
}
function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) {
  const checker = program.getTypeChecker();
  const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken);
  return some(diagnostics, ({ start: start2, length: length2, relatedInformation, code }) => isNumber(start2) && isNumber(length2) && textSpansEqual({ start: start2, length: length2 }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_forget_to_use_await.code));
}
function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) {
  const identifiers = getIdentifiersFromErrorSpanExpression(expression, checker);
  if (!identifiers) {
    return;
  }
  let isCompleteFix = identifiers.isCompleteFix;
  let initializers;
  for (const identifier of identifiers.identifiers) {
    const symbol = checker.getSymbolAtLocation(identifier);
    if (!symbol) {
      continue;
    }
    const declaration = tryCast(symbol.valueDeclaration, isVariableDeclaration);
    const variableName = declaration && tryCast(declaration.name, isIdentifier);
    const variableStatement = getAncestor(declaration, 242 /* VariableStatement */);
    if (!declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, 1 /* Export */) || !variableName || !isInsideAwaitableBody(declaration.initializer)) {
      isCompleteFix = false;
      continue;
    }
    const diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken);
    const isUsedElsewhere = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, (reference) => {
      return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker);
    });
    if (isUsedElsewhere) {
      isCompleteFix = false;
      continue;
    }
    (initializers || (initializers = [])).push({
      expression: declaration.initializer,
      declarationSymbol: symbol
    });
  }
  return initializers && {
    initializers,
    needsSecondPassForFixAll: !isCompleteFix
  };
}
function getIdentifiersFromErrorSpanExpression(expression, checker) {
  if (isPropertyAccessExpression(expression.parent) && isIdentifier(expression.parent.expression)) {
    return { identifiers: [expression.parent.expression], isCompleteFix: true };
  }
  if (isIdentifier(expression)) {
    return { identifiers: [expression], isCompleteFix: true };
  }
  if (isBinaryExpression(expression)) {
    let sides;
    let isCompleteFix = true;
    for (const side of [expression.left, expression.right]) {
      const type = checker.getTypeAtLocation(side);
      if (checker.getPromisedTypeOfPromise(type)) {
        if (!isIdentifier(side)) {
          isCompleteFix = false;
          continue;
        }
        (sides || (sides = [])).push(side);
      }
    }
    return sides && { identifiers: sides, isCompleteFix };
  }
}
function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) {
  const errorNode = isPropertyAccessExpression(reference.parent) ? reference.parent.name : isBinaryExpression(reference.parent) ? reference.parent : reference;
  const diagnostic = find(diagnostics, (diagnostic2) => diagnostic2.start === errorNode.getStart(sourceFile) && diagnostic2.start + diagnostic2.length === errorNode.getEnd());
  return diagnostic && contains(errorCodes3, diagnostic.code) || // A Promise is usually not correct in a binary expression (it's not valid
  // in an arithmetic expression and an equality comparison seems unusual),
  // but if the other side of the binary expression has an error, the side
  // is typed `any` which will squash the error that would identify this
  // Promise as an invalid operand. So if the whole binary expression is
  // typed `any` as a result, there is a strong likelihood that this Promise
  // is accidentally missing `await`.
  checker.getTypeAtLocation(errorNode).flags & 1 /* Any */;
}
function isInsideAwaitableBody(node) {
  return node.kind & 32768 /* AwaitContext */ || !!findAncestor(node, (ancestor) => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 261 /* FunctionDeclaration */ || ancestor.parent.kind === 217 /* FunctionExpression */ || ancestor.parent.kind === 218 /* ArrowFunction */ || ancestor.parent.kind === 173 /* MethodDeclaration */));
}
function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) {
  if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) {
    const exprType = checker.getTypeAtLocation(insertionSite);
    const asyncIter = checker.getAsyncIterableType();
    if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) {
      const forOf = insertionSite.parent;
      changeTracker.replaceNode(sourceFile, forOf, factory.updateForOfStatement(forOf, factory.createToken(135 /* AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement));
      return;
    }
  }
  if (isBinaryExpression(insertionSite)) {
    for (const side of [insertionSite.left, insertionSite.right]) {
      if (fixedDeclarations && isIdentifier(side)) {
        const symbol = checker.getSymbolAtLocation(side);
        if (symbol && fixedDeclarations.has(getSymbolId(symbol))) {
          continue;
        }
      }
      const type = checker.getTypeAtLocation(side);
      const newNode = checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(side) : side;
      changeTracker.replaceNode(sourceFile, side, newNode);
    }
  } else if (errorCode === propertyAccessCode && isPropertyAccessExpression(insertionSite.parent)) {
    if (fixedDeclarations && isIdentifier(insertionSite.parent.expression)) {
      const symbol = checker.getSymbolAtLocation(insertionSite.parent.expression);
      if (symbol && fixedDeclarations.has(getSymbolId(symbol))) {
        return;
      }
    }
    changeTracker.replaceNode(
      sourceFile,
      insertionSite.parent.expression,
      factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression))
    );
    insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
  } else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) {
    if (fixedDeclarations && isIdentifier(insertionSite)) {
      const symbol = checker.getSymbolAtLocation(insertionSite);
      if (symbol && fixedDeclarations.has(getSymbolId(symbol))) {
        return;
      }
    }
    changeTracker.replaceNode(sourceFile, insertionSite, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite)));
    insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile);
  } else {
    if (fixedDeclarations && isVariableDeclaration(insertionSite.parent) && isIdentifier(insertionSite.parent.name)) {
      const symbol = checker.getSymbolAtLocation(insertionSite.parent.name);
      if (symbol && !tryAddToSet(fixedDeclarations, getSymbolId(symbol))) {
        return;
      }
    }
    changeTracker.replaceNode(sourceFile, insertionSite, factory.createAwaitExpression(insertionSite));
  }
}
function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) {
  const precedingToken = findPrecedingToken(beforeNode.pos, sourceFile);
  if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
    changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";");
  }
}

// src/services/codefixes/addMissingConst.ts
var fixId4 = "addMissingConst";
var errorCodes4 = [
  Diagnostics.Cannot_find_name_0.code,
  Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code
];
registerCodeFix({
  errorCodes: errorCodes4,
  getCodeActions: function getCodeActionsToAddMissingConst(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange4(t, context.sourceFile, context.span.start, context.program));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId4, changes, Diagnostics.Add_const_to_unresolved_variable, fixId4, Diagnostics.Add_const_to_all_unresolved_variables)];
    }
  },
  fixIds: [fixId4],
  getAllCodeActions: (context) => {
    const fixedNodes = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes4, (changes, diag2) => makeChange4(changes, diag2.file, diag2.start, context.program, fixedNodes));
  }
});
function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) {
  const token = getTokenAtPosition(sourceFile, pos);
  const forInitializer = findAncestor(
    token,
    (node) => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"
  );
  if (forInitializer)
    return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes);
  const parent2 = token.parent;
  if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && isExpressionStatement(parent2.parent)) {
    return applyChange(changeTracker, token, sourceFile, fixedNodes);
  }
  if (isArrayLiteralExpression(parent2)) {
    const checker = program.getTypeChecker();
    if (!every(parent2.elements, (element) => arrayElementCouldBeVariableDeclaration(element, checker))) {
      return;
    }
    return applyChange(changeTracker, parent2, sourceFile, fixedNodes);
  }
  const commaExpression = findAncestor(
    token,
    (node) => isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"
  );
  if (commaExpression) {
    const checker = program.getTypeChecker();
    if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) {
      return;
    }
    return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes);
  }
}
function applyChange(changeTracker, initializer, sourceFile, fixedNodes) {
  if (!fixedNodes || tryAddToSet(fixedNodes, initializer)) {
    changeTracker.insertModifierBefore(sourceFile, 87 /* ConstKeyword */, initializer);
  }
}
function isPossiblyPartOfDestructuring(node) {
  switch (node.kind) {
    case 80 /* Identifier */:
    case 208 /* ArrayLiteralExpression */:
    case 209 /* ObjectLiteralExpression */:
    case 302 /* PropertyAssignment */:
    case 303 /* ShorthandPropertyAssignment */:
      return true;
    default:
      return false;
  }
}
function arrayElementCouldBeVariableDeclaration(expression, checker) {
  const identifier = isIdentifier(expression) ? expression : isAssignmentExpression(
    expression,
    /*excludeCompoundAssignment*/
    true
  ) && isIdentifier(expression.left) ? expression.left : void 0;
  return !!identifier && !checker.getSymbolAtLocation(identifier);
}
function isPossiblyPartOfCommaSeperatedInitializer(node) {
  switch (node.kind) {
    case 80 /* Identifier */:
    case 225 /* BinaryExpression */:
    case 28 /* CommaToken */:
      return true;
    default:
      return false;
  }
}
function expressionCouldBeVariableDeclaration(expression, checker) {
  if (!isBinaryExpression(expression)) {
    return false;
  }
  if (expression.operatorToken.kind === 28 /* CommaToken */) {
    return every([expression.left, expression.right], (expression2) => expressionCouldBeVariableDeclaration(expression2, checker));
  }
  return expression.operatorToken.kind === 64 /* EqualsToken */ && isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left);
}

// src/services/codefixes/addMissingDeclareProperty.ts
var fixId5 = "addMissingDeclareProperty";
var errorCodes5 = [
  Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code
];
registerCodeFix({
  errorCodes: errorCodes5,
  getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange5(t, context.sourceFile, context.span.start));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId5, changes, Diagnostics.Prefix_with_declare, fixId5, Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)];
    }
  },
  fixIds: [fixId5],
  getAllCodeActions: (context) => {
    const fixedNodes = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes5, (changes, diag2) => makeChange5(changes, diag2.file, diag2.start, fixedNodes));
  }
});
function makeChange5(changeTracker, sourceFile, pos, fixedNodes) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (!isIdentifier(token)) {
    return;
  }
  const declaration = token.parent;
  if (declaration.kind === 171 /* PropertyDeclaration */ && (!fixedNodes || tryAddToSet(fixedNodes, declaration))) {
    changeTracker.insertModifierBefore(sourceFile, 138 /* DeclareKeyword */, declaration);
  }
}

// src/services/codefixes/addMissingInvocationForDecorator.ts
var fixId6 = "addMissingInvocationForDecorator";
var errorCodes6 = [Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code];
registerCodeFix({
  errorCodes: errorCodes6,
  getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange6(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId6, changes, Diagnostics.Call_decorator_expression, fixId6, Diagnostics.Add_to_all_uncalled_decorators)];
  },
  fixIds: [fixId6],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes6, (changes, diag2) => makeChange6(changes, diag2.file, diag2.start))
});
function makeChange6(changeTracker, sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const decorator = findAncestor(token, isDecorator);
  Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
  const replacement = factory.createCallExpression(
    decorator.expression,
    /*typeArguments*/
    void 0,
    /*argumentsArray*/
    void 0
  );
  changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
}

// src/services/codefixes/addNameToNamelessParameter.ts
var fixId7 = "addNameToNamelessParameter";
var errorCodes7 = [Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
registerCodeFix({
  errorCodes: errorCodes7,
  getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange7(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId7, changes, Diagnostics.Add_parameter_name, fixId7, Diagnostics.Add_names_to_all_parameters_without_names)];
  },
  fixIds: [fixId7],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes7, (changes, diag2) => makeChange7(changes, diag2.file, diag2.start))
});
function makeChange7(changeTracker, sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const param = token.parent;
  if (!isParameter(param)) {
    return Debug.fail("Tried to add a parameter name to a non-parameter: " + Debug.formatSyntaxKind(token.kind));
  }
  const i = param.parent.parameters.indexOf(param);
  Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
  Debug.assert(i > -1, "Parameter not found in parent parameter list.");
  const typeNode = factory.createTypeReferenceNode(
    param.name,
    /*typeArguments*/
    void 0
  );
  const replacement = factory.createParameterDeclaration(
    param.modifiers,
    param.dotDotDotToken,
    "arg" + i,
    param.questionToken,
    param.dotDotDotToken ? factory.createArrayTypeNode(typeNode) : typeNode,
    param.initializer
  );
  changeTracker.replaceNode(sourceFile, param, replacement);
}

// src/services/codefixes/addOptionalPropertyUndefined.ts
var addOptionalPropertyUndefined = "addOptionalPropertyUndefined";
var errorCodes8 = [
  Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code
];
registerCodeFix({
  errorCodes: errorCodes8,
  getCodeActions(context) {
    const typeChecker = context.program.getTypeChecker();
    const toAdd = getPropertiesToAdd(context.sourceFile, context.span, typeChecker);
    if (!toAdd.length) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addUndefinedToOptionalProperty(t, toAdd));
    return [createCodeFixActionWithoutFixAll(addOptionalPropertyUndefined, changes, Diagnostics.Add_undefined_to_optional_property_type)];
  },
  fixIds: [addOptionalPropertyUndefined]
});
function getPropertiesToAdd(file, span, checker) {
  var _a, _b;
  const sourceTarget = getSourceTarget(getFixableErrorSpanExpression(file, span), checker);
  if (!sourceTarget) {
    return emptyArray;
  }
  const { source: sourceNode, target: targetNode } = sourceTarget;
  const target = shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) ? checker.getTypeAtLocation(targetNode.expression) : checker.getTypeAtLocation(targetNode);
  if ((_b = (_a = target.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some((d) => getSourceFileOfNode(d).fileName.match(/\.d\.ts$/))) {
    return emptyArray;
  }
  return checker.getExactOptionalProperties(target);
}
function shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) {
  return isPropertyAccessExpression(targetNode) && !!checker.getExactOptionalProperties(checker.getTypeAtLocation(targetNode.expression)).length && checker.getTypeAtLocation(sourceNode) === checker.getUndefinedType();
}
function getSourceTarget(errorNode, checker) {
  var _a;
  if (!errorNode) {
    return void 0;
  } else if (isBinaryExpression(errorNode.parent) && errorNode.parent.operatorToken.kind === 64 /* EqualsToken */) {
    return { source: errorNode.parent.right, target: errorNode.parent.left };
  } else if (isVariableDeclaration(errorNode.parent) && errorNode.parent.initializer) {
    return { source: errorNode.parent.initializer, target: errorNode.parent.name };
  } else if (isCallExpression(errorNode.parent)) {
    const n = checker.getSymbolAtLocation(errorNode.parent.expression);
    if (!(n == null ? void 0 : n.valueDeclaration) || !isFunctionLikeKind(n.valueDeclaration.kind))
      return void 0;
    if (!isExpression(errorNode))
      return void 0;
    const i = errorNode.parent.arguments.indexOf(errorNode);
    if (i === -1)
      return void 0;
    const name = n.valueDeclaration.parameters[i].name;
    if (isIdentifier(name))
      return { source: errorNode, target: name };
  } else if (isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || isShorthandPropertyAssignment(errorNode.parent)) {
    const parentTarget = getSourceTarget(errorNode.parent.parent, checker);
    if (!parentTarget)
      return void 0;
    const prop = checker.getPropertyOfType(checker.getTypeAtLocation(parentTarget.target), errorNode.parent.name.text);
    const declaration = (_a = prop == null ? void 0 : prop.declarations) == null ? void 0 : _a[0];
    if (!declaration)
      return void 0;
    return {
      source: isPropertyAssignment(errorNode.parent) ? errorNode.parent.initializer : errorNode.parent.name,
      target: declaration
    };
  }
  return void 0;
}
function addUndefinedToOptionalProperty(changes, toAdd) {
  for (const add of toAdd) {
    const d = add.valueDeclaration;
    if (d && (isPropertySignature(d) || isPropertyDeclaration(d)) && d.type) {
      const t = factory.createUnionTypeNode([
        ...d.type.kind === 191 /* UnionType */ ? d.type.types : [d.type],
        factory.createTypeReferenceNode("undefined")
      ]);
      changes.replaceNode(d.getSourceFile(), d.type, t);
    }
  }
}

// src/services/codefixes/annotateWithTypeFromJSDoc.ts
var fixId8 = "annotateWithTypeFromJSDoc";
var errorCodes9 = [Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
registerCodeFix({
  errorCodes: errorCodes9,
  getCodeActions(context) {
    const decl = getDeclaration(context.sourceFile, context.span.start);
    if (!decl)
      return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl));
    return [createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc)];
  },
  fixIds: [fixId8],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes9, (changes, diag2) => {
    const decl = getDeclaration(diag2.file, diag2.start);
    if (decl)
      doChange8(changes, diag2.file, decl);
  })
});
function getDeclaration(file, pos) {
  const name = getTokenAtPosition(file, pos);
  return tryCast(isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
}
function parameterShouldGetTypeFromJSDoc(node) {
  return isDeclarationWithType(node) && hasUsableJSDoc(node);
}
function hasUsableJSDoc(decl) {
  return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl);
}
function doChange8(changes, sourceFile, decl) {
  if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) {
    if (!decl.typeParameters) {
      const typeParameters = getJSDocTypeParameterDeclarations(decl);
      if (typeParameters.length)
        changes.insertTypeParameters(sourceFile, decl, typeParameters);
    }
    const needParens = isArrowFunction(decl) && !findChildOfKind(decl, 21 /* OpenParenToken */, sourceFile);
    if (needParens)
      changes.insertNodeBefore(sourceFile, first(decl.parameters), factory.createToken(21 /* OpenParenToken */));
    for (const param of decl.parameters) {
      if (!param.type) {
        const paramType = getJSDocType(param);
        if (paramType)
          changes.tryInsertTypeAnnotation(sourceFile, param, visitNode(paramType, transformJSDocType, isTypeNode));
      }
    }
    if (needParens)
      changes.insertNodeAfter(sourceFile, last(decl.parameters), factory.createToken(22 /* CloseParenToken */));
    if (!decl.type) {
      const returnType = getJSDocReturnType(decl);
      if (returnType)
        changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(returnType, transformJSDocType, isTypeNode));
    }
  } else {
    const jsdocType = Debug.checkDefined(getJSDocType(decl), "A JSDocType for this declaration should exist");
    Debug.assert(!decl.type, "The JSDocType decl should have a type");
    changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(jsdocType, transformJSDocType, isTypeNode));
  }
}
function isDeclarationWithType(node) {
  return isFunctionLikeDeclaration(node) || node.kind === 259 /* VariableDeclaration */ || node.kind === 170 /* PropertySignature */ || node.kind === 171 /* PropertyDeclaration */;
}
function transformJSDocType(node) {
  switch (node.kind) {
    case 318 /* JSDocAllType */:
    case 319 /* JSDocUnknownType */:
      return factory.createTypeReferenceNode("any", emptyArray);
    case 322 /* JSDocOptionalType */:
      return transformJSDocOptionalType(node);
    case 321 /* JSDocNonNullableType */:
      return transformJSDocType(node.type);
    case 320 /* JSDocNullableType */:
      return transformJSDocNullableType(node);
    case 324 /* JSDocVariadicType */:
      return transformJSDocVariadicType(node);
    case 323 /* JSDocFunctionType */:
      return transformJSDocFunctionType(node);
    case 182 /* TypeReference */:
      return transformJSDocTypeReference(node);
    case 328 /* JSDocTypeLiteral */:
      return transformJSDocTypeLiteral(node);
    default:
      const visited = visitEachChild(node, transformJSDocType, nullTransformationContext);
      setEmitFlags(visited, 1 /* SingleLine */);
      return visited;
  }
}
function transformJSDocTypeLiteral(node) {
  const typeNode = factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (tag) => factory.createPropertySignature(
    /*modifiers*/
    void 0,
    isIdentifier(tag.name) ? tag.name : tag.name.right,
    isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(58 /* QuestionToken */) : void 0,
    tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)
  )));
  setEmitFlags(typeNode, 1 /* SingleLine */);
  return typeNode;
}
function transformJSDocOptionalType(node) {
  return factory.createUnionTypeNode([visitNode(node.type, transformJSDocType, isTypeNode), factory.createTypeReferenceNode("undefined", emptyArray)]);
}
function transformJSDocNullableType(node) {
  return factory.createUnionTypeNode([visitNode(node.type, transformJSDocType, isTypeNode), factory.createTypeReferenceNode("null", emptyArray)]);
}
function transformJSDocVariadicType(node) {
  return factory.createArrayTypeNode(visitNode(node.type, transformJSDocType, isTypeNode));
}
function transformJSDocFunctionType(node) {
  return factory.createFunctionTypeNode(emptyArray, node.parameters.map(transformJSDocParameter), node.type ?? factory.createKeywordTypeNode(133 /* AnyKeyword */));
}
function transformJSDocParameter(node) {
  const index = node.parent.parameters.indexOf(node);
  const isRest = node.type.kind === 324 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
  const name = node.name || (isRest ? "rest" : "arg" + index);
  const dotdotdot = isRest ? factory.createToken(26 /* DotDotDotToken */) : node.dotDotDotToken;
  return factory.createParameterDeclaration(node.modifiers, dotdotdot, name, node.questionToken, visitNode(node.type, transformJSDocType, isTypeNode), node.initializer);
}
function transformJSDocTypeReference(node) {
  let name = node.typeName;
  let args = node.typeArguments;
  if (isIdentifier(node.typeName)) {
    if (isJSDocIndexSignature(node)) {
      return transformJSDocIndexSignature(node);
    }
    let text = node.typeName.text;
    switch (node.typeName.text) {
      case "String":
      case "Boolean":
      case "Object":
      case "Number":
        text = text.toLowerCase();
        break;
      case "array":
      case "date":
      case "promise":
        text = text[0].toUpperCase() + text.slice(1);
        break;
    }
    name = factory.createIdentifier(text);
    if ((text === "Array" || text === "Promise") && !node.typeArguments) {
      args = factory.createNodeArray([factory.createTypeReferenceNode("any", emptyArray)]);
    } else {
      args = visitNodes2(node.typeArguments, transformJSDocType, isTypeNode);
    }
  }
  return factory.createTypeReferenceNode(name, args);
}
function transformJSDocIndexSignature(node) {
  const index = factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "n" : "s",
    /*questionToken*/
    void 0,
    factory.createTypeReferenceNode(node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "number" : "string", []),
    /*initializer*/
    void 0
  );
  const indexSignature = factory.createTypeLiteralNode([factory.createIndexSignature(
    /*modifiers*/
    void 0,
    [index],
    node.typeArguments[1]
  )]);
  setEmitFlags(indexSignature, 1 /* SingleLine */);
  return indexSignature;
}

// src/services/codefixes/convertFunctionToEs6Class.ts
var fixId9 = "convertFunctionToEs6Class";
var errorCodes10 = [Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
registerCodeFix({
  errorCodes: errorCodes10,
  getCodeActions(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions()));
    return [createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes)];
  },
  fixIds: [fixId9],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions()))
});
function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) {
  const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position));
  if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
    return void 0;
  }
  const ctorDeclaration = ctorSymbol.valueDeclaration;
  if (isFunctionDeclaration(ctorDeclaration) || isFunctionExpression(ctorDeclaration)) {
    changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunction(ctorDeclaration));
  } else if (isVariableDeclaration(ctorDeclaration)) {
    const classDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
    if (!classDeclaration) {
      return void 0;
    }
    const ancestor = ctorDeclaration.parent.parent;
    if (isVariableDeclarationList(ctorDeclaration.parent) && ctorDeclaration.parent.declarations.length > 1) {
      changes.delete(sourceFile, ctorDeclaration);
      changes.insertNodeAfter(sourceFile, ancestor, classDeclaration);
    } else {
      changes.replaceNode(sourceFile, ancestor, classDeclaration);
    }
  }
  function createClassElementsFromSymbol(symbol) {
    const memberElements = [];
    if (symbol.exports) {
      symbol.exports.forEach((member) => {
        if (member.name === "prototype" && member.declarations) {
          const firstDeclaration = member.declarations[0];
          if (member.declarations.length === 1 && isPropertyAccessExpression(firstDeclaration) && isBinaryExpression(firstDeclaration.parent) && firstDeclaration.parent.operatorToken.kind === 64 /* EqualsToken */ && isObjectLiteralExpression(firstDeclaration.parent.right)) {
            const prototypes = firstDeclaration.parent.right;
            createClassElement(
              prototypes.symbol,
              /*modifiers*/
              void 0,
              memberElements
            );
          }
        } else {
          createClassElement(member, [factory.createToken(126 /* StaticKeyword */)], memberElements);
        }
      });
    }
    if (symbol.members) {
      symbol.members.forEach((member, key) => {
        var _a, _b, _c, _d;
        if (key === "constructor" && member.valueDeclaration) {
          const prototypeAssignment = (_d = (_c = (_b = (_a = symbol.exports) == null ? void 0 : _a.get("prototype")) == null ? void 0 : _b.declarations) == null ? void 0 : _c[0]) == null ? void 0 : _d.parent;
          if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) {
          } else {
            changes.delete(sourceFile, member.valueDeclaration.parent);
          }
          return;
        }
        createClassElement(
          member,
          /*modifiers*/
          void 0,
          memberElements
        );
      });
    }
    return memberElements;
    function shouldConvertDeclaration(_target, source) {
      if (isAccessExpression(_target)) {
        if (isPropertyAccessExpression(_target) && isConstructorAssignment(_target))
          return true;
        return isFunctionLike(source);
      } else {
        return every(_target.properties, (property) => {
          if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property))
            return true;
          if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name)
            return true;
          if (isConstructorAssignment(property))
            return true;
          return false;
        });
      }
    }
    function createClassElement(symbol2, modifiers, members) {
      if (!(symbol2.flags & 8192 /* Method */) && !(symbol2.flags & 4096 /* ObjectLiteral */)) {
        return;
      }
      const memberDeclaration = symbol2.valueDeclaration;
      const assignmentBinaryExpression = memberDeclaration.parent;
      const assignmentExpr = assignmentBinaryExpression.right;
      if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) {
        return;
      }
      if (some(members, (m) => {
        const name = getNameOfDeclaration(m);
        if (name && isIdentifier(name) && idText(name) === symbolName(symbol2)) {
          return true;
        }
        return false;
      })) {
        return;
      }
      const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 243 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
      changes.delete(sourceFile, nodeToDelete);
      if (!assignmentExpr) {
        members.push(factory.createPropertyDeclaration(
          modifiers,
          symbol2.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        ));
        return;
      }
      if (isAccessExpression(memberDeclaration) && (isFunctionExpression(assignmentExpr) || isArrowFunction(assignmentExpr))) {
        const quotePreference = getQuotePreference(sourceFile, preferences);
        const name = tryGetPropertyName(memberDeclaration, compilerOptions, quotePreference);
        if (name) {
          createFunctionLikeExpressionMember(members, assignmentExpr, name);
        }
        return;
      } else if (isObjectLiteralExpression(assignmentExpr)) {
        forEach(
          assignmentExpr.properties,
          (property) => {
            if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) {
              members.push(property);
            }
            if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) {
              createFunctionLikeExpressionMember(members, property.initializer, property.name);
            }
            if (isConstructorAssignment(property))
              return;
            return;
          }
        );
        return;
      } else {
        if (isSourceFileJS(sourceFile))
          return;
        if (!isPropertyAccessExpression(memberDeclaration))
          return;
        const prop = factory.createPropertyDeclaration(
          modifiers,
          memberDeclaration.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          assignmentExpr
        );
        copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
        members.push(prop);
        return;
      }
      function createFunctionLikeExpressionMember(members2, expression, name) {
        if (isFunctionExpression(expression))
          return createFunctionExpressionMember(members2, expression, name);
        else
          return createArrowFunctionExpressionMember(members2, expression, name);
      }
      function createFunctionExpressionMember(members2, functionExpression, name) {
        const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, 134 /* AsyncKeyword */));
        const method = factory.createMethodDeclaration(
          fullModifiers,
          /*asteriskToken*/
          void 0,
          name,
          /*questionToken*/
          void 0,
          /*typeParameters*/
          void 0,
          functionExpression.parameters,
          /*type*/
          void 0,
          functionExpression.body
        );
        copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
        members2.push(method);
        return;
      }
      function createArrowFunctionExpressionMember(members2, arrowFunction, name) {
        const arrowFunctionBody = arrowFunction.body;
        let bodyBlock;
        if (arrowFunctionBody.kind === 240 /* Block */) {
          bodyBlock = arrowFunctionBody;
        } else {
          bodyBlock = factory.createBlock([factory.createReturnStatement(arrowFunctionBody)]);
        }
        const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, 134 /* AsyncKeyword */));
        const method = factory.createMethodDeclaration(
          fullModifiers,
          /*asteriskToken*/
          void 0,
          name,
          /*questionToken*/
          void 0,
          /*typeParameters*/
          void 0,
          arrowFunction.parameters,
          /*type*/
          void 0,
          bodyBlock
        );
        copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
        members2.push(method);
      }
    }
  }
  function createClassFromVariableDeclaration(node) {
    const initializer = node.initializer;
    if (!initializer || !isFunctionExpression(initializer) || !isIdentifier(node.name)) {
      return void 0;
    }
    const memberElements = createClassElementsFromSymbol(node.symbol);
    if (initializer.body) {
      memberElements.unshift(factory.createConstructorDeclaration(
        /*modifiers*/
        void 0,
        initializer.parameters,
        initializer.body
      ));
    }
    const modifiers = getModifierKindFromSource(node.parent.parent, 95 /* ExportKeyword */);
    const cls = factory.createClassDeclaration(
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      /*heritageClauses*/
      void 0,
      memberElements
    );
    return cls;
  }
  function createClassFromFunction(node) {
    const memberElements = createClassElementsFromSymbol(ctorSymbol);
    if (node.body) {
      memberElements.unshift(factory.createConstructorDeclaration(
        /*modifiers*/
        void 0,
        node.parameters,
        node.body
      ));
    }
    const modifiers = getModifierKindFromSource(node, 95 /* ExportKeyword */);
    const cls = factory.createClassDeclaration(
      modifiers,
      node.name,
      /*typeParameters*/
      void 0,
      /*heritageClauses*/
      void 0,
      memberElements
    );
    return cls;
  }
}
function getModifierKindFromSource(source, kind) {
  return canHaveModifiers(source) ? filter(source.modifiers, (modifier) => modifier.kind === kind) : void 0;
}
function isConstructorAssignment(x) {
  if (!x.name)
    return false;
  if (isIdentifier(x.name) && x.name.text === "constructor")
    return true;
  return false;
}
function tryGetPropertyName(node, compilerOptions, quotePreference) {
  if (isPropertyAccessExpression(node)) {
    return node.name;
  }
  const propName = node.argumentExpression;
  if (isNumericLiteral(propName)) {
    return propName;
  }
  if (isStringLiteralLike(propName)) {
    return isIdentifierText(propName.text, getEmitScriptTarget(compilerOptions)) ? factory.createIdentifier(propName.text) : isNoSubstitutionTemplateLiteral(propName) ? factory.createStringLiteral(propName.text, quotePreference === 0 /* Single */) : propName;
  }
  return void 0;
}

// src/services/codefixes/convertToAsyncFunction.ts
var fixId10 = "convertToAsyncFunction";
var errorCodes11 = [Diagnostics.This_may_be_converted_to_an_async_function.code];
var codeActionSucceeded = true;
registerCodeFix({
  errorCodes: errorCodes11,
  getCodeActions(context) {
    codeActionSucceeded = true;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker()));
    return codeActionSucceeded ? [createCodeFixAction(fixId10, changes, Diagnostics.Convert_to_async_function, fixId10, Diagnostics.Convert_all_to_async_functions)] : [];
  },
  fixIds: [fixId10],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker()))
});
function convertToAsyncFunction(changes, sourceFile, position, checker) {
  const tokenAtPosition = getTokenAtPosition(sourceFile, position);
  let functionToConvert;
  if (isIdentifier(tokenAtPosition) && isVariableDeclaration(tokenAtPosition.parent) && tokenAtPosition.parent.initializer && isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
    functionToConvert = tokenAtPosition.parent.initializer;
  } else {
    functionToConvert = tryCast(getContainingFunction(getTokenAtPosition(sourceFile, position)), canBeConvertedToAsync);
  }
  if (!functionToConvert) {
    return;
  }
  const synthNamesMap = /* @__PURE__ */ new Map();
  const isInJavascript = isInJSFile(functionToConvert);
  const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
  const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap);
  if (!returnsPromise(functionToConvertRenamed, checker)) {
    return;
  }
  const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : emptyArray;
  const transformer = { checker, synthNamesMap, setOfExpressionsToReturn, isInJSFile: isInJavascript };
  if (!returnStatements.length) {
    return;
  }
  const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(functionToConvert).pos);
  changes.insertModifierAt(sourceFile, pos, 134 /* AsyncKeyword */, { suffix: " " });
  for (const returnStatement of returnStatements) {
    forEachChild(returnStatement, function visit(node) {
      if (isCallExpression(node)) {
        const newNodes = transformExpression(
          node,
          node,
          transformer,
          /*hasContinuation*/
          false
        );
        if (hasFailed()) {
          return true;
        }
        changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes);
      } else if (!isFunctionLike(node)) {
        forEachChild(node, visit);
        if (hasFailed()) {
          return true;
        }
      }
    });
    if (hasFailed()) {
      return;
    }
  }
}
function getReturnStatementsWithPromiseHandlers(body, checker) {
  const res = [];
  forEachReturnStatement(body, (ret) => {
    if (isReturnStatementWithFixablePromiseHandler(ret, checker))
      res.push(ret);
  });
  return res;
}
function getAllPromiseExpressionsToReturn(func, checker) {
  if (!func.body) {
    return /* @__PURE__ */ new Set();
  }
  const setOfExpressionsToReturn = /* @__PURE__ */ new Set();
  forEachChild(func.body, function visit(node) {
    if (isPromiseReturningCallExpression(node, checker, "then")) {
      setOfExpressionsToReturn.add(getNodeId(node));
      forEach(node.arguments, visit);
    } else if (isPromiseReturningCallExpression(node, checker, "catch") || isPromiseReturningCallExpression(node, checker, "finally")) {
      setOfExpressionsToReturn.add(getNodeId(node));
      forEachChild(node, visit);
    } else if (isPromiseTypedExpression(node, checker)) {
      setOfExpressionsToReturn.add(getNodeId(node));
    } else {
      forEachChild(node, visit);
    }
  });
  return setOfExpressionsToReturn;
}
function isPromiseReturningCallExpression(node, checker, name) {
  if (!isCallExpression(node))
    return false;
  const isExpressionOfName = hasPropertyAccessExpressionWithName(node, name);
  const nodeType = isExpressionOfName && checker.getTypeAtLocation(node);
  return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType));
}
function isReferenceToType(type, target) {
  return (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target;
}
function getExplicitPromisedTypeOfPromiseReturningCallExpression(node, callback, checker) {
  if (node.expression.name.escapedText === "finally") {
    return void 0;
  }
  const promiseType = checker.getTypeAtLocation(node.expression.expression);
  if (isReferenceToType(promiseType, checker.getPromiseType()) || isReferenceToType(promiseType, checker.getPromiseLikeType())) {
    if (node.expression.name.escapedText === "then") {
      if (callback === elementAt(node.arguments, 0)) {
        return elementAt(node.typeArguments, 0);
      } else if (callback === elementAt(node.arguments, 1)) {
        return elementAt(node.typeArguments, 1);
      }
    } else {
      return elementAt(node.typeArguments, 0);
    }
  }
}
function isPromiseTypedExpression(node, checker) {
  if (!isExpression(node))
    return false;
  return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node));
}
function renameCollidingVarNames(nodeToRename, checker, synthNamesMap) {
  const identsToRenameMap = /* @__PURE__ */ new Map();
  const collidingSymbolMap = createMultiMap();
  forEachChild(nodeToRename, function visit(node) {
    if (!isIdentifier(node)) {
      forEachChild(node, visit);
      return;
    }
    const symbol = checker.getSymbolAtLocation(node);
    if (symbol) {
      const type = checker.getTypeAtLocation(node);
      const lastCallSignature = getLastCallSignature(type, checker);
      const symbolIdString = getSymbolId(symbol).toString();
      if (lastCallSignature && !isParameter(node.parent) && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) {
        const firstParameter = firstOrUndefined(lastCallSignature.parameters);
        const ident = (firstParameter == null ? void 0 : firstParameter.valueDeclaration) && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || factory.createUniqueName("result", 16 /* Optimistic */);
        const synthName = getNewNameIfConflict(ident, collidingSymbolMap);
        synthNamesMap.set(symbolIdString, synthName);
        collidingSymbolMap.add(ident.text, symbol);
      } else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent) || isBindingElement(node.parent))) {
        const originalName = node.text;
        const collidingSymbols = collidingSymbolMap.get(originalName);
        if (collidingSymbols && collidingSymbols.some((prevSymbol) => prevSymbol !== symbol)) {
          const newName = getNewNameIfConflict(node, collidingSymbolMap);
          identsToRenameMap.set(symbolIdString, newName.identifier);
          synthNamesMap.set(symbolIdString, newName);
          collidingSymbolMap.add(originalName, symbol);
        } else {
          const identifier = getSynthesizedDeepClone(node);
          synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier));
          collidingSymbolMap.add(originalName, symbol);
        }
      }
    }
  });
  return getSynthesizedDeepCloneWithReplacements(
    nodeToRename,
    /*includeTrivia*/
    true,
    (original) => {
      if (isBindingElement(original) && isIdentifier(original.name) && isObjectBindingPattern(original.parent)) {
        const symbol = checker.getSymbolAtLocation(original.name);
        const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol)));
        if (renameInfo && renameInfo.text !== (original.name || original.propertyName).getText()) {
          return factory.createBindingElement(
            original.dotDotDotToken,
            original.propertyName || original.name,
            renameInfo,
            original.initializer
          );
        }
      } else if (isIdentifier(original)) {
        const symbol = checker.getSymbolAtLocation(original);
        const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol)));
        if (renameInfo) {
          return factory.createIdentifier(renameInfo.text);
        }
      }
    }
  );
}
function getNewNameIfConflict(name, originalNames) {
  const numVarsSameName = (originalNames.get(name.text) || emptyArray).length;
  const identifier = numVarsSameName === 0 ? name : factory.createIdentifier(name.text + "_" + numVarsSameName);
  return createSynthIdentifier(identifier);
}
function hasFailed() {
  return !codeActionSucceeded;
}
function silentFail() {
  codeActionSucceeded = false;
  return emptyArray;
}
function transformExpression(returnContextNode, node, transformer, hasContinuation, continuationArgName) {
  if (isPromiseReturningCallExpression(node, transformer.checker, "then")) {
    return transformThen(node, elementAt(node.arguments, 0), elementAt(node.arguments, 1), transformer, hasContinuation, continuationArgName);
  }
  if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) {
    return transformCatch(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName);
  }
  if (isPromiseReturningCallExpression(node, transformer.checker, "finally")) {
    return transformFinally(node, elementAt(node.arguments, 0), transformer, hasContinuation, continuationArgName);
  }
  if (isPropertyAccessExpression(node)) {
    return transformExpression(returnContextNode, node.expression, transformer, hasContinuation, continuationArgName);
  }
  const nodeType = transformer.checker.getTypeAtLocation(node);
  if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) {
    Debug.assertNode(getOriginalNode(node).parent, isPropertyAccessExpression);
    return transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName);
  }
  return silentFail();
}
function isNullOrUndefined2({ checker }, node) {
  if (node.kind === 106 /* NullKeyword */)
    return true;
  if (isIdentifier(node) && !isGeneratedIdentifier(node) && idText(node) === "undefined") {
    const symbol = checker.getSymbolAtLocation(node);
    return !symbol || checker.isUndefinedSymbol(symbol);
  }
  return false;
}
function createUniqueSynthName(prevArgName) {
  const renamedPrevArg = factory.createUniqueName(prevArgName.identifier.text, 16 /* Optimistic */);
  return createSynthIdentifier(renamedPrevArg);
}
function getPossibleNameForVarDecl(node, transformer, continuationArgName) {
  let possibleNameForVarDecl;
  if (continuationArgName && !shouldReturn(node, transformer)) {
    if (isSynthIdentifier(continuationArgName)) {
      possibleNameForVarDecl = continuationArgName;
      transformer.synthNamesMap.forEach((val, key) => {
        if (val.identifier.text === continuationArgName.identifier.text) {
          const newSynthName = createUniqueSynthName(continuationArgName);
          transformer.synthNamesMap.set(key, newSynthName);
        }
      });
    } else {
      possibleNameForVarDecl = createSynthIdentifier(factory.createUniqueName("result", 16 /* Optimistic */), continuationArgName.types);
    }
    declareSynthIdentifier(possibleNameForVarDecl);
  }
  return possibleNameForVarDecl;
}
function finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName) {
  const statements = [];
  let varDeclIdentifier;
  if (possibleNameForVarDecl && !shouldReturn(node, transformer)) {
    varDeclIdentifier = getSynthesizedDeepClone(declareSynthIdentifier(possibleNameForVarDecl));
    const typeArray = possibleNameForVarDecl.types;
    const unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */);
    const unionTypeNode = transformer.isInJSFile ? void 0 : transformer.checker.typeToTypeNode(
      unionType,
      /*enclosingDeclaration*/
      void 0,
      /*flags*/
      void 0
    );
    const varDecl = [factory.createVariableDeclaration(
      varDeclIdentifier,
      /*exclamationToken*/
      void 0,
      unionTypeNode
    )];
    const varDeclList = factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList(varDecl, 1 /* Let */)
    );
    statements.push(varDeclList);
  }
  statements.push(tryStatement);
  if (continuationArgName && varDeclIdentifier && isSynthBindingPattern(continuationArgName)) {
    statements.push(factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList(
        [
          factory.createVariableDeclaration(
            getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)),
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            varDeclIdentifier
          )
        ],
        2 /* Const */
      )
    ));
  }
  return statements;
}
function transformFinally(node, onFinally, transformer, hasContinuation, continuationArgName) {
  if (!onFinally || isNullOrUndefined2(transformer, onFinally)) {
    return transformExpression(
      /* returnContextNode */
      node,
      node.expression.expression,
      transformer,
      hasContinuation,
      continuationArgName
    );
  }
  const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName);
  const inlinedLeftHandSide = transformExpression(
    /*returnContextNode*/
    node,
    node.expression.expression,
    transformer,
    /*hasContinuation*/
    true,
    possibleNameForVarDecl
  );
  if (hasFailed())
    return silentFail();
  const inlinedCallback = transformCallbackArgument(
    onFinally,
    hasContinuation,
    /*continuationArgName*/
    void 0,
    /*inputArgName*/
    void 0,
    node,
    transformer
  );
  if (hasFailed())
    return silentFail();
  const tryBlock = factory.createBlock(inlinedLeftHandSide);
  const finallyBlock = factory.createBlock(inlinedCallback);
  const tryStatement = factory.createTryStatement(
    tryBlock,
    /*catchClause*/
    void 0,
    finallyBlock
  );
  return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName);
}
function transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName) {
  if (!onRejected || isNullOrUndefined2(transformer, onRejected)) {
    return transformExpression(
      /* returnContextNode */
      node,
      node.expression.expression,
      transformer,
      hasContinuation,
      continuationArgName
    );
  }
  const inputArgName = getArgBindingName(onRejected, transformer);
  const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName);
  const inlinedLeftHandSide = transformExpression(
    /*returnContextNode*/
    node,
    node.expression.expression,
    transformer,
    /*hasContinuation*/
    true,
    possibleNameForVarDecl
  );
  if (hasFailed())
    return silentFail();
  const inlinedCallback = transformCallbackArgument(onRejected, hasContinuation, possibleNameForVarDecl, inputArgName, node, transformer);
  if (hasFailed())
    return silentFail();
  const tryBlock = factory.createBlock(inlinedLeftHandSide);
  const catchClause = factory.createCatchClause(inputArgName && getSynthesizedDeepClone(declareSynthBindingName(inputArgName)), factory.createBlock(inlinedCallback));
  const tryStatement = factory.createTryStatement(
    tryBlock,
    catchClause,
    /*finallyBlock*/
    void 0
  );
  return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName);
}
function transformThen(node, onFulfilled, onRejected, transformer, hasContinuation, continuationArgName) {
  if (!onFulfilled || isNullOrUndefined2(transformer, onFulfilled)) {
    return transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName);
  }
  if (onRejected && !isNullOrUndefined2(transformer, onRejected)) {
    return silentFail();
  }
  const inputArgName = getArgBindingName(onFulfilled, transformer);
  const inlinedLeftHandSide = transformExpression(
    node.expression.expression,
    node.expression.expression,
    transformer,
    /*hasContinuation*/
    true,
    inputArgName
  );
  if (hasFailed())
    return silentFail();
  const inlinedCallback = transformCallbackArgument(onFulfilled, hasContinuation, continuationArgName, inputArgName, node, transformer);
  if (hasFailed())
    return silentFail();
  return concatenate(inlinedLeftHandSide, inlinedCallback);
}
function transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName) {
  if (shouldReturn(returnContextNode, transformer)) {
    let returnValue = getSynthesizedDeepClone(node);
    if (hasContinuation) {
      returnValue = factory.createAwaitExpression(returnValue);
    }
    return [factory.createReturnStatement(returnValue)];
  }
  return createVariableOrAssignmentOrExpressionStatement(
    continuationArgName,
    factory.createAwaitExpression(node),
    /*typeAnnotation*/
    void 0
  );
}
function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) {
  if (!variableName || isEmptyBindingName(variableName)) {
    return [factory.createExpressionStatement(rightHandSide)];
  }
  if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) {
    return [factory.createExpressionStatement(factory.createAssignment(getSynthesizedDeepClone(referenceSynthIdentifier(variableName)), rightHandSide))];
  }
  return [
    factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList(
        [
          factory.createVariableDeclaration(
            getSynthesizedDeepClone(declareSynthBindingName(variableName)),
            /*exclamationToken*/
            void 0,
            typeAnnotation,
            rightHandSide
          )
        ],
        2 /* Const */
      )
    )
  ];
}
function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) {
  if (typeAnnotation && expressionToReturn) {
    const name = factory.createUniqueName("result", 16 /* Optimistic */);
    return [
      ...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation),
      factory.createReturnStatement(name)
    ];
  }
  return [factory.createReturnStatement(expressionToReturn)];
}
function transformCallbackArgument(func, hasContinuation, continuationArgName, inputArgName, parent2, transformer) {
  var _a;
  switch (func.kind) {
    case 106 /* NullKeyword */:
      break;
    case 210 /* PropertyAccessExpression */:
    case 80 /* Identifier */:
      if (!inputArgName) {
        break;
      }
      const synthCall = factory.createCallExpression(
        getSynthesizedDeepClone(func),
        /*typeArguments*/
        void 0,
        isSynthIdentifier(inputArgName) ? [referenceSynthIdentifier(inputArgName)] : []
      );
      if (shouldReturn(parent2, transformer)) {
        return maybeAnnotateAndReturn(synthCall, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker));
      }
      const type = transformer.checker.getTypeAtLocation(func);
      const callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */);
      if (!callSignatures.length) {
        return silentFail();
      }
      const returnType = callSignatures[0].getReturnType();
      const varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(synthCall), getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker));
      if (continuationArgName) {
        continuationArgName.types.push(transformer.checker.getAwaitedType(returnType) || returnType);
      }
      return varDeclOrAssignment;
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */: {
      const funcBody = func.body;
      const returnType2 = (_a = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) == null ? void 0 : _a.getReturnType();
      if (isBlock(funcBody)) {
        let refactoredStmts = [];
        let seenReturnStatement = false;
        for (const statement of funcBody.statements) {
          if (isReturnStatement(statement)) {
            seenReturnStatement = true;
            if (isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) {
              refactoredStmts = refactoredStmts.concat(transformReturnStatementWithFixablePromiseHandler(transformer, statement, hasContinuation, continuationArgName));
            } else {
              const possiblyAwaitedRightHandSide = returnType2 && statement.expression ? getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, statement.expression) : statement.expression;
              refactoredStmts.push(...maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)));
            }
          } else if (hasContinuation && forEachReturnStatement(statement, returnTrue)) {
            return silentFail();
          } else {
            refactoredStmts.push(statement);
          }
        }
        return shouldReturn(parent2, transformer) ? refactoredStmts.map((s) => getSynthesizedDeepClone(s)) : removeReturns(
          refactoredStmts,
          continuationArgName,
          transformer,
          seenReturnStatement
        );
      } else {
        const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? transformReturnStatementWithFixablePromiseHandler(transformer, factory.createReturnStatement(funcBody), hasContinuation, continuationArgName) : emptyArray;
        if (inlinedStatements.length > 0) {
          return inlinedStatements;
        }
        if (returnType2) {
          const possiblyAwaitedRightHandSide = getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, funcBody);
          if (!shouldReturn(parent2, transformer)) {
            const transformedStatement = createVariableOrAssignmentOrExpressionStatement(
              continuationArgName,
              possiblyAwaitedRightHandSide,
              /*typeAnnotation*/
              void 0
            );
            if (continuationArgName) {
              continuationArgName.types.push(transformer.checker.getAwaitedType(returnType2) || returnType2);
            }
            return transformedStatement;
          } else {
            return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker));
          }
        } else {
          return silentFail();
        }
      }
    }
    default:
      return silentFail();
  }
  return emptyArray;
}
function getPossiblyAwaitedRightHandSide(checker, type, expr) {
  const rightHandSide = getSynthesizedDeepClone(expr);
  return !!checker.getPromisedTypeOfPromise(type) ? factory.createAwaitExpression(rightHandSide) : rightHandSide;
}
function getLastCallSignature(type, checker) {
  const callSignatures = checker.getSignaturesOfType(type, 0 /* Call */);
  return lastOrUndefined(callSignatures);
}
function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) {
  const ret = [];
  for (const stmt of stmts) {
    if (isReturnStatement(stmt)) {
      if (stmt.expression) {
        const possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? factory.createAwaitExpression(stmt.expression) : stmt.expression;
        if (prevArgName === void 0) {
          ret.push(factory.createExpressionStatement(possiblyAwaitedExpression));
        } else if (isSynthIdentifier(prevArgName) && prevArgName.hasBeenDeclared) {
          ret.push(factory.createExpressionStatement(factory.createAssignment(referenceSynthIdentifier(prevArgName), possiblyAwaitedExpression)));
        } else {
          ret.push(factory.createVariableStatement(
            /*modifiers*/
            void 0,
            factory.createVariableDeclarationList([factory.createVariableDeclaration(
              declareSynthBindingName(prevArgName),
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              possiblyAwaitedExpression
            )], 2 /* Const */)
          ));
        }
      }
    } else {
      ret.push(getSynthesizedDeepClone(stmt));
    }
  }
  if (!seenReturnStatement && prevArgName !== void 0) {
    ret.push(factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList([factory.createVariableDeclaration(
        declareSynthBindingName(prevArgName),
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        factory.createIdentifier("undefined")
      )], 2 /* Const */)
    ));
  }
  return ret;
}
function transformReturnStatementWithFixablePromiseHandler(transformer, innerRetStmt, hasContinuation, continuationArgName) {
  let innerCbBody = [];
  forEachChild(innerRetStmt, function visit(node) {
    if (isCallExpression(node)) {
      const temp = transformExpression(node, node, transformer, hasContinuation, continuationArgName);
      innerCbBody = innerCbBody.concat(temp);
      if (innerCbBody.length > 0) {
        return;
      }
    } else if (!isFunctionLike(node)) {
      forEachChild(node, visit);
    }
  });
  return innerCbBody;
}
function getArgBindingName(funcNode, transformer) {
  const types = [];
  let name;
  if (isFunctionLikeDeclaration(funcNode)) {
    if (funcNode.parameters.length > 0) {
      const param = funcNode.parameters[0].name;
      name = getMappedBindingNameOrDefault(param);
    }
  } else if (isIdentifier(funcNode)) {
    name = getMapEntryOrDefault(funcNode);
  } else if (isPropertyAccessExpression(funcNode) && isIdentifier(funcNode.name)) {
    name = getMapEntryOrDefault(funcNode.name);
  }
  if (!name || "identifier" in name && name.identifier.text === "undefined") {
    return void 0;
  }
  return name;
  function getMappedBindingNameOrDefault(bindingName) {
    if (isIdentifier(bindingName))
      return getMapEntryOrDefault(bindingName);
    const elements = flatMap(bindingName.elements, (element) => {
      if (isOmittedExpression(element))
        return [];
      return [getMappedBindingNameOrDefault(element.name)];
    });
    return createSynthBindingPattern(bindingName, elements);
  }
  function getMapEntryOrDefault(identifier) {
    const originalNode = getOriginalNode2(identifier);
    const symbol = getSymbol2(originalNode);
    if (!symbol) {
      return createSynthIdentifier(identifier, types);
    }
    const mapEntry = transformer.synthNamesMap.get(getSymbolId(symbol).toString());
    return mapEntry || createSynthIdentifier(identifier, types);
  }
  function getSymbol2(node) {
    var _a;
    return ((_a = tryCast(node, canHaveSymbol)) == null ? void 0 : _a.symbol) ?? transformer.checker.getSymbolAtLocation(node);
  }
  function getOriginalNode2(node) {
    return node.original ? node.original : node;
  }
}
function isEmptyBindingName(bindingName) {
  if (!bindingName) {
    return true;
  }
  if (isSynthIdentifier(bindingName)) {
    return !bindingName.identifier.text;
  }
  return every(bindingName.elements, isEmptyBindingName);
}
function createSynthIdentifier(identifier, types = []) {
  return { kind: 0 /* Identifier */, identifier, types, hasBeenDeclared: false, hasBeenReferenced: false };
}
function createSynthBindingPattern(bindingPattern, elements = emptyArray, types = []) {
  return { kind: 1 /* BindingPattern */, bindingPattern, elements, types };
}
function referenceSynthIdentifier(synthId) {
  synthId.hasBeenReferenced = true;
  return synthId.identifier;
}
function declareSynthBindingName(synthName) {
  return isSynthIdentifier(synthName) ? declareSynthIdentifier(synthName) : declareSynthBindingPattern(synthName);
}
function declareSynthBindingPattern(synthPattern) {
  for (const element of synthPattern.elements) {
    declareSynthBindingName(element);
  }
  return synthPattern.bindingPattern;
}
function declareSynthIdentifier(synthId) {
  synthId.hasBeenDeclared = true;
  return synthId.identifier;
}
function isSynthIdentifier(bindingName) {
  return bindingName.kind === 0 /* Identifier */;
}
function isSynthBindingPattern(bindingName) {
  return bindingName.kind === 1 /* BindingPattern */;
}
function shouldReturn(expression, transformer) {
  return !!expression.original && transformer.setOfExpressionsToReturn.has(getNodeId(expression.original));
}

// src/services/codefixes/convertToEsModule.ts
registerCodeFix({
  errorCodes: [Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code],
  getCodeActions(context) {
    const { sourceFile, program, preferences } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
      const moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes2, getEmitScriptTarget(program.getCompilerOptions()), getQuotePreference(sourceFile, preferences));
      if (moduleExportsChangedToDefault) {
        for (const importingFile of program.getSourceFiles()) {
          fixImportOfModuleExports(importingFile, sourceFile, changes2, getQuotePreference(importingFile, preferences));
        }
      }
    });
    return [createCodeFixActionWithoutFixAll("convertToEsModule", changes, Diagnostics.Convert_to_ES_module)];
  }
});
function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) {
  for (const moduleSpecifier of importingFile.imports) {
    const imported = getResolvedModule(importingFile, moduleSpecifier.text, getModeForUsageLocation(importingFile, moduleSpecifier));
    if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
      continue;
    }
    const importNode = importFromModuleSpecifier(moduleSpecifier);
    switch (importNode.kind) {
      case 270 /* ImportEqualsDeclaration */:
        changes.replaceNode(importingFile, importNode, makeImport(
          importNode.name,
          /*namedImports*/
          void 0,
          moduleSpecifier,
          quotePreference
        ));
        break;
      case 212 /* CallExpression */:
        if (isRequireCall(
          importNode,
          /*requireStringLiteralLikeArgument*/
          false
        )) {
          changes.replaceNode(importingFile, importNode, factory.createPropertyAccessExpression(getSynthesizedDeepClone(importNode), "default"));
        }
        break;
    }
  }
}
function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) {
  const identifiers = { original: collectFreeIdentifiers(sourceFile), additional: /* @__PURE__ */ new Set() };
  const exports = collectExportRenames(sourceFile, checker, identifiers);
  convertExportsAccesses(sourceFile, exports, changes);
  let moduleExportsChangedToDefault = false;
  let useSitesToUnqualify;
  for (const statement of filter(sourceFile.statements, isVariableStatement)) {
    const newUseSites = convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
    if (newUseSites) {
      copyEntries(newUseSites, useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map()));
    }
  }
  for (const statement of filter(sourceFile.statements, (s) => !isVariableStatement(s))) {
    const moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference);
    moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
  }
  useSitesToUnqualify == null ? void 0 : useSitesToUnqualify.forEach((replacement, original) => {
    changes.replaceNode(sourceFile, original, replacement);
  });
  return moduleExportsChangedToDefault;
}
function collectExportRenames(sourceFile, checker, identifiers) {
  const res = /* @__PURE__ */ new Map();
  forEachExportReference(sourceFile, (node) => {
    const { text } = node.name;
    if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) || checker.resolveName(
      text,
      node,
      111551 /* Value */,
      /*excludeGlobals*/
      true
    ))) {
      res.set(text, makeUniqueName(`_${text}`, identifiers));
    }
  });
  return res;
}
function convertExportsAccesses(sourceFile, exports, changes) {
  forEachExportReference(sourceFile, (node, isAssignmentLhs) => {
    if (isAssignmentLhs) {
      return;
    }
    const { text } = node.name;
    changes.replaceNode(sourceFile, node, factory.createIdentifier(exports.get(text) || text));
  });
}
function forEachExportReference(sourceFile, cb) {
  sourceFile.forEachChild(function recur(node) {
    if (isPropertyAccessExpression(node) && isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && isIdentifier(node.name)) {
      const { parent: parent2 } = node;
      cb(node, isBinaryExpression(parent2) && parent2.left === node && parent2.operatorToken.kind === 64 /* EqualsToken */);
    }
    node.forEachChild(recur);
  });
}
function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) {
  switch (statement.kind) {
    case 242 /* VariableStatement */:
      convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
      return false;
    case 243 /* ExpressionStatement */: {
      const { expression } = statement;
      switch (expression.kind) {
        case 212 /* CallExpression */: {
          if (isRequireCall(
            expression,
            /*requireStringLiteralLikeArgument*/
            true
          )) {
            changes.replaceNode(sourceFile, statement, makeImport(
              /*defaultImport*/
              void 0,
              /*namedImports*/
              void 0,
              expression.arguments[0],
              quotePreference
            ));
          }
          return false;
        }
        case 225 /* BinaryExpression */: {
          const { operatorToken } = expression;
          return operatorToken.kind === 64 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify);
        }
      }
    }
    default:
      return false;
  }
}
function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) {
  const { declarationList } = statement;
  let foundImport = false;
  const converted = map(declarationList.declarations, (decl) => {
    const { name, initializer } = decl;
    if (initializer) {
      if (isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
        foundImport = true;
        return convertedImports([]);
      } else if (isRequireCall(
        initializer,
        /*requireStringLiteralLikeArgument*/
        true
      )) {
        foundImport = true;
        return convertSingleImport(name, initializer.arguments[0], checker, identifiers, target, quotePreference);
      } else if (isPropertyAccessExpression(initializer) && isRequireCall(
        initializer.expression,
        /*requireStringLiteralLikeArgument*/
        true
      )) {
        foundImport = true;
        return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference);
      }
    }
    return convertedImports([factory.createVariableStatement(
      /*modifiers*/
      void 0,
      factory.createVariableDeclarationList([decl], declarationList.flags)
    )]);
  });
  if (foundImport) {
    changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, (c) => c.newImports));
    let combinedUseSites;
    forEach(converted, (c) => {
      if (c.useSitesToUnqualify) {
        copyEntries(c.useSitesToUnqualify, combinedUseSites ?? (combinedUseSites = /* @__PURE__ */ new Map()));
      }
    });
    return combinedUseSites;
  }
}
function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
  switch (name.kind) {
    case 205 /* ObjectBindingPattern */:
    case 206 /* ArrayBindingPattern */: {
      const tmp = makeUniqueName(propertyName, identifiers);
      return convertedImports([
        makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference),
        makeConst(
          /*modifiers*/
          void 0,
          name,
          factory.createIdentifier(tmp)
        )
      ]);
    }
    case 80 /* Identifier */:
      return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]);
    default:
      return Debug.assertNever(name, `Convert to ES module got invalid syntax form ${name.kind}`);
  }
}
function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) {
  const { left, right } = assignment;
  if (!isPropertyAccessExpression(left)) {
    return false;
  }
  if (isExportsOrModuleExportsOrAlias(sourceFile, left)) {
    if (isExportsOrModuleExportsOrAlias(sourceFile, right)) {
      changes.delete(sourceFile, assignment.parent);
    } else {
      const replacement = isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right, useSitesToUnqualify) : isRequireCall(
        right,
        /*requireStringLiteralLikeArgument*/
        true
      ) ? convertReExportAll(right.arguments[0], checker) : void 0;
      if (replacement) {
        changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
        return replacement[1];
      } else {
        changes.replaceRangeWithText(sourceFile, createRange(left.getStart(sourceFile), right.pos), "export default");
        return true;
      }
    }
  } else if (isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
    convertNamedExport(sourceFile, assignment, changes, exports);
  }
  return false;
}
function tryChangeModuleExportsObject(object, useSitesToUnqualify) {
  const statements = mapAllOrFail(object.properties, (prop) => {
    switch (prop.kind) {
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
      case 303 /* ShorthandPropertyAssignment */:
      case 304 /* SpreadAssignment */:
        return void 0;
      case 302 /* PropertyAssignment */:
        return !isIdentifier(prop.name) ? void 0 : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify);
      case 173 /* MethodDeclaration */:
        return !isIdentifier(prop.name) ? void 0 : functionExpressionToDeclaration(prop.name.text, [factory.createToken(95 /* ExportKeyword */)], prop, useSitesToUnqualify);
      default:
        Debug.assertNever(prop, `Convert to ES6 got invalid prop kind ${prop.kind}`);
    }
  });
  return statements && [statements, false];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
  const { text } = assignment.left.name;
  const rename = exports.get(text);
  if (rename !== void 0) {
    const newNodes = [
      makeConst(
        /*modifiers*/
        void 0,
        rename,
        assignment.right
      ),
      makeExportDeclaration([factory.createExportSpecifier(
        /*isTypeOnly*/
        false,
        rename,
        text
      )])
    ];
    changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
  } else {
    convertExportsPropertyAssignment(assignment, sourceFile, changes);
  }
}
function convertReExportAll(reExported, checker) {
  const moduleSpecifier = reExported.text;
  const moduleSymbol = checker.getSymbolAtLocation(reExported);
  const exports = moduleSymbol ? moduleSymbol.exports : emptyMap;
  return exports.has("export=" /* ExportEquals */) ? [[reExportDefault(moduleSpecifier)], true] : !exports.has("default" /* Default */) ? [[reExportStar(moduleSpecifier)], false] : (
    // If there's some non-default export, must include both `export *` and `export default`.
    exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]
  );
}
function reExportStar(moduleSpecifier) {
  return makeExportDeclaration(
    /*exportSpecifiers*/
    void 0,
    moduleSpecifier
  );
}
function reExportDefault(moduleSpecifier) {
  return makeExportDeclaration([factory.createExportSpecifier(
    /*isTypeOnly*/
    false,
    /*propertyName*/
    void 0,
    "default"
  )], moduleSpecifier);
}
function convertExportsPropertyAssignment({ left, right, parent: parent2 }, sourceFile, changes) {
  const name = left.name.text;
  if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) {
    changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, factory.createToken(95 /* ExportKeyword */), { suffix: " " });
    if (!right.name)
      changes.insertName(sourceFile, right, name);
    const semi = findChildOfKind(parent2, 27 /* SemicolonToken */, sourceFile);
    if (semi)
      changes.delete(sourceFile, semi);
  } else {
    changes.replaceNodeRangeWithNodes(
      sourceFile,
      left.expression,
      findChildOfKind(left, 25 /* DotToken */, sourceFile),
      [factory.createToken(95 /* ExportKeyword */), factory.createToken(87 /* ConstKeyword */)],
      { joiner: " ", suffix: " " }
    );
  }
}
function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) {
  const modifiers = [factory.createToken(95 /* ExportKeyword */)];
  switch (exported.kind) {
    case 217 /* FunctionExpression */: {
      const { name: expressionName } = exported;
      if (expressionName && expressionName.text !== name) {
        return exportConst();
      }
    }
    case 218 /* ArrowFunction */:
      return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify);
    case 230 /* ClassExpression */:
      return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify);
    default:
      return exportConst();
  }
  function exportConst() {
    return makeConst(modifiers, factory.createIdentifier(name), replaceImportUseSites(exported, useSitesToUnqualify));
  }
}
function replaceImportUseSites(nodeOrNodes, useSitesToUnqualify) {
  if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), (original) => rangeContainsRange(nodeOrNodes, original))) {
    return nodeOrNodes;
  }
  return isArray(nodeOrNodes) ? getSynthesizedDeepClonesWithReplacements(
    nodeOrNodes,
    /*includeTrivia*/
    true,
    replaceNode
  ) : getSynthesizedDeepCloneWithReplacements(
    nodeOrNodes,
    /*includeTrivia*/
    true,
    replaceNode
  );
  function replaceNode(original) {
    if (original.kind === 210 /* PropertyAccessExpression */) {
      const replacement = useSitesToUnqualify.get(original);
      useSitesToUnqualify.delete(original);
      return replacement;
    }
  }
}
function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) {
  switch (name.kind) {
    case 205 /* ObjectBindingPattern */: {
      const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text));
      if (importSpecifiers) {
        return convertedImports([makeImport(
          /*defaultImport*/
          void 0,
          importSpecifiers,
          moduleSpecifier,
          quotePreference
        )]);
      }
    }
    case 206 /* ArrayBindingPattern */: {
      const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
      return convertedImports([
        makeImport(
          factory.createIdentifier(tmp),
          /*namedImports*/
          void 0,
          moduleSpecifier,
          quotePreference
        ),
        makeConst(
          /*modifiers*/
          void 0,
          getSynthesizedDeepClone(name),
          factory.createIdentifier(tmp)
        )
      ]);
    }
    case 80 /* Identifier */:
      return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference);
    default:
      return Debug.assertNever(name, `Convert to ES module got invalid name kind ${name.kind}`);
  }
}
function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) {
  const nameSymbol = checker.getSymbolAtLocation(name);
  const namedBindingsNames = /* @__PURE__ */ new Map();
  let needDefaultImport = false;
  let useSitesToUnqualify;
  for (const use of identifiers.original.get(name.text)) {
    if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
      continue;
    }
    const { parent: parent2 } = use;
    if (isPropertyAccessExpression(parent2)) {
      const { name: { text: propertyName } } = parent2;
      if (propertyName === "default") {
        needDefaultImport = true;
        const importDefaultName = use.getText();
        (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(importDefaultName));
      } else {
        Debug.assert(parent2.expression === use, "Didn't expect expression === use");
        let idName = namedBindingsNames.get(propertyName);
        if (idName === void 0) {
          idName = makeUniqueName(propertyName, identifiers);
          namedBindingsNames.set(propertyName, idName);
        }
        (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(idName));
      }
    } else {
      needDefaultImport = true;
    }
  }
  const namedBindings = namedBindingsNames.size === 0 ? void 0 : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName]) => factory.createImportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName === idName ? void 0 : factory.createIdentifier(propertyName),
    factory.createIdentifier(idName)
  )));
  if (!namedBindings) {
    needDefaultImport = true;
  }
  return convertedImports(
    [makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : void 0, namedBindings, moduleSpecifier, quotePreference)],
    useSitesToUnqualify
  );
}
function makeUniqueName(name, identifiers) {
  while (identifiers.original.has(name) || identifiers.additional.has(name)) {
    name = `_${name}`;
  }
  identifiers.additional.add(name);
  return name;
}
function collectFreeIdentifiers(file) {
  const map2 = createMultiMap();
  forEachFreeIdentifier(file, (id) => map2.add(id.text, id));
  return map2;
}
function forEachFreeIdentifier(node, cb) {
  if (isIdentifier(node) && isFreeIdentifier(node))
    cb(node);
  node.forEachChild((child) => forEachFreeIdentifier(child, cb));
}
function isFreeIdentifier(node) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 210 /* PropertyAccessExpression */:
      return parent2.name !== node;
    case 207 /* BindingElement */:
      return parent2.propertyName !== node;
    case 275 /* ImportSpecifier */:
      return parent2.propertyName !== node;
    default:
      return true;
  }
}
function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) {
  return factory.createFunctionDeclaration(
    concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)),
    getSynthesizedDeepClone(fn.asteriskToken),
    name,
    getSynthesizedDeepClones(fn.typeParameters),
    getSynthesizedDeepClones(fn.parameters),
    getSynthesizedDeepClone(fn.type),
    factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))
  );
}
function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) {
  return factory.createClassDeclaration(
    concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)),
    name,
    getSynthesizedDeepClones(cls.typeParameters),
    getSynthesizedDeepClones(cls.heritageClauses),
    replaceImportUseSites(cls.members, useSitesToUnqualify)
  );
}
function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) {
  return propertyName === "default" ? makeImport(
    factory.createIdentifier(localName),
    /*namedImports*/
    void 0,
    moduleSpecifier,
    quotePreference
  ) : makeImport(
    /*defaultImport*/
    void 0,
    [makeImportSpecifier2(propertyName, localName)],
    moduleSpecifier,
    quotePreference
  );
}
function makeImportSpecifier2(propertyName, name) {
  return factory.createImportSpecifier(
    /*isTypeOnly*/
    false,
    propertyName !== void 0 && propertyName !== name ? factory.createIdentifier(propertyName) : void 0,
    factory.createIdentifier(name)
  );
}
function makeConst(modifiers, name, init) {
  return factory.createVariableStatement(
    modifiers,
    factory.createVariableDeclarationList(
      [factory.createVariableDeclaration(
        name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        init
      )],
      2 /* Const */
    )
  );
}
function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
  return factory.createExportDeclaration(
    /*modifiers*/
    void 0,
    /*isTypeOnly*/
    false,
    exportSpecifiers && factory.createNamedExports(exportSpecifiers),
    moduleSpecifier === void 0 ? void 0 : factory.createStringLiteral(moduleSpecifier)
  );
}
function convertedImports(newImports, useSitesToUnqualify) {
  return {
    newImports,
    useSitesToUnqualify
  };
}

// src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts
var fixId11 = "correctQualifiedNameToIndexedAccessType";
var errorCodes12 = [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.code];
registerCodeFix({
  errorCodes: errorCodes12,
  getCodeActions(context) {
    const qualifiedName = getQualifiedName(context.sourceFile, context.span.start);
    if (!qualifiedName)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName));
    const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`;
    return [createCodeFixAction(fixId11, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types)];
  },
  fixIds: [fixId11],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, diag2) => {
    const q = getQualifiedName(diag2.file, diag2.start);
    if (q) {
      doChange10(changes, diag2.file, q);
    }
  })
});
function getQualifiedName(sourceFile, pos) {
  const qualifiedName = findAncestor(getTokenAtPosition(sourceFile, pos), isQualifiedName);
  Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
  return isIdentifier(qualifiedName.left) ? qualifiedName : void 0;
}
function doChange10(changeTracker, sourceFile, qualifiedName) {
  const rightText = qualifiedName.right.text;
  const replacement = factory.createIndexedAccessTypeNode(
    factory.createTypeReferenceNode(
      qualifiedName.left,
      /*typeArguments*/
      void 0
    ),
    factory.createLiteralTypeNode(factory.createStringLiteral(rightText))
  );
  changeTracker.replaceNode(sourceFile, qualifiedName, replacement);
}

// src/services/codefixes/convertToTypeOnlyExport.ts
var errorCodes13 = [Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code];
var fixId12 = "convertToTypeOnlyExport";
registerCodeFix({
  errorCodes: errorCodes13,
  getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context));
    if (changes.length) {
      return [createCodeFixAction(fixId12, changes, Diagnostics.Convert_to_type_only_export, fixId12, Diagnostics.Convert_all_re_exported_types_to_type_only_exports)];
    }
  },
  fixIds: [fixId12],
  getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) {
    const fixedExportDeclarations = /* @__PURE__ */ new Map();
    return codeFixAll(context, errorCodes13, (changes, diag2) => {
      const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag2, context.sourceFile);
      if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) {
        fixSingleExportDeclaration(changes, exportSpecifier, context);
      }
    });
  }
});
function getExportSpecifierForDiagnosticSpan(span, sourceFile) {
  return tryCast(getTokenAtPosition(sourceFile, span.start).parent, isExportSpecifier);
}
function fixSingleExportDeclaration(changes, exportSpecifier, context) {
  if (!exportSpecifier) {
    return;
  }
  const exportClause = exportSpecifier.parent;
  const exportDeclaration = exportClause.parent;
  const typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context);
  if (typeExportSpecifiers.length === exportClause.elements.length) {
    changes.insertModifierBefore(context.sourceFile, 156 /* TypeKeyword */, exportClause);
  } else {
    const valueExportDeclaration = factory.updateExportDeclaration(
      exportDeclaration,
      exportDeclaration.modifiers,
      /*isTypeOnly*/
      false,
      factory.updateNamedExports(exportClause, filter(exportClause.elements, (e) => !contains(typeExportSpecifiers, e))),
      exportDeclaration.moduleSpecifier,
      /*assertClause*/
      void 0
    );
    const typeExportDeclaration = factory.createExportDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      true,
      factory.createNamedExports(typeExportSpecifiers),
      exportDeclaration.moduleSpecifier,
      /*assertClause*/
      void 0
    );
    changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, {
      leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll,
      trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude
    });
    changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration);
  }
}
function getTypeExportSpecifiers(originExportSpecifier, context) {
  const exportClause = originExportSpecifier.parent;
  if (exportClause.elements.length === 1) {
    return exportClause.elements;
  }
  const diagnostics = getDiagnosticsWithinSpan(
    createTextSpanFromNode(exportClause),
    context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken)
  );
  return filter(exportClause.elements, (element) => {
    var _a;
    return element === originExportSpecifier || ((_a = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a.code) === errorCodes13[0];
  });
}

// src/services/codefixes/convertToTypeOnlyImport.ts
var errorCodes14 = [
  Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code,
  Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code
];
var fixId13 = "convertToTypeOnlyImport";
registerCodeFix({
  errorCodes: errorCodes14,
  getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) {
    const declaration = getDeclaration2(context.sourceFile, context.span.start);
    if (declaration) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration));
      return [createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_import, fixId13, Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports)];
    }
    return void 0;
  },
  fixIds: [fixId13],
  getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) {
    return codeFixAll(context, errorCodes14, (changes, diag2) => {
      const declaration = getDeclaration2(diag2.file, diag2.start);
      if (declaration) {
        doChange11(changes, diag2.file, declaration);
      }
    });
  }
});
function getDeclaration2(sourceFile, pos) {
  const { parent: parent2 } = getTokenAtPosition(sourceFile, pos);
  return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0;
}
function doChange11(changes, sourceFile, declaration) {
  if (isImportSpecifier(declaration)) {
    changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier(
      declaration,
      /*isTypeOnly*/
      true,
      declaration.propertyName,
      declaration.name
    ));
  } else {
    const importClause = declaration.importClause;
    if (importClause.name && importClause.namedBindings) {
      changes.replaceNodeWithNodes(sourceFile, declaration, [
        factory.createImportDeclaration(
          getSynthesizedDeepClones(
            declaration.modifiers,
            /*includeTrivia*/
            true
          ),
          factory.createImportClause(
            /*isTypeOnly*/
            true,
            getSynthesizedDeepClone(
              importClause.name,
              /*includeTrivia*/
              true
            ),
            /*namedBindings*/
            void 0
          ),
          getSynthesizedDeepClone(
            declaration.moduleSpecifier,
            /*includeTrivia*/
            true
          ),
          getSynthesizedDeepClone(
            declaration.assertClause,
            /*includeTrivia*/
            true
          )
        ),
        factory.createImportDeclaration(
          getSynthesizedDeepClones(
            declaration.modifiers,
            /*includeTrivia*/
            true
          ),
          factory.createImportClause(
            /*isTypeOnly*/
            true,
            /*name*/
            void 0,
            getSynthesizedDeepClone(
              importClause.namedBindings,
              /*includeTrivia*/
              true
            )
          ),
          getSynthesizedDeepClone(
            declaration.moduleSpecifier,
            /*includeTrivia*/
            true
          ),
          getSynthesizedDeepClone(
            declaration.assertClause,
            /*includeTrivia*/
            true
          )
        )
      ]);
    } else {
      const importDeclaration = factory.updateImportDeclaration(
        declaration,
        declaration.modifiers,
        factory.updateImportClause(
          importClause,
          /*isTypeOnly*/
          true,
          importClause.name,
          importClause.namedBindings
        ),
        declaration.moduleSpecifier,
        declaration.assertClause
      );
      changes.replaceNode(sourceFile, declaration, importDeclaration);
    }
  }
}

// src/services/codefixes/convertTypedefToType.ts
var fixId14 = "convertTypedefToType";
var errorCodes15 = [Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type.code];
registerCodeFix({
  fixIds: [fixId14],
  errorCodes: errorCodes15,
  getCodeActions(context) {
    const node = getTokenAtPosition(
      context.sourceFile,
      context.span.start
    );
    if (!node)
      return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile));
    if (changes.length > 0) {
      return [
        createCodeFixAction(
          fixId14,
          changes,
          Diagnostics.Convert_typedef_to_TypeScript_type,
          fixId14,
          Diagnostics.Convert_all_typedef_to_TypeScript_types
        )
      ];
    }
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => {
    const node = getTokenAtPosition(diag2.file, diag2.start);
    if (node)
      doChange12(changes, node, diag2.file);
  })
});
function doChange12(changes, node, sourceFile) {
  if (isJSDocTypedefTag(node)) {
    fixSingleTypeDef(changes, node, sourceFile);
  }
}
function fixSingleTypeDef(changes, typeDefNode, sourceFile) {
  if (!typeDefNode)
    return;
  const declaration = createDeclaration(typeDefNode);
  if (!declaration)
    return;
  const comment = typeDefNode.parent;
  changes.replaceNode(
    sourceFile,
    comment,
    declaration
  );
}
function createDeclaration(tag) {
  var _a;
  const { typeExpression } = tag;
  if (!typeExpression)
    return;
  const typeName = (_a = tag.name) == null ? void 0 : _a.getText();
  if (!typeName)
    return;
  if (typeExpression.kind === 328 /* JSDocTypeLiteral */) {
    return createInterfaceForTypeLiteral(typeName, typeExpression);
  }
  if (typeExpression.kind === 315 /* JSDocTypeExpression */) {
    return createTypeAliasForTypeExpression(typeName, typeExpression);
  }
}
function createInterfaceForTypeLiteral(typeName, typeLiteral) {
  const propertySignatures = createSignatureFromTypeLiteral(typeLiteral);
  if (!some(propertySignatures))
    return;
  const interfaceDeclaration = factory.createInterfaceDeclaration(
    /*modifiers*/
    void 0,
    typeName,
    /*typeParameters*/
    void 0,
    /*heritageClauses*/
    void 0,
    propertySignatures
  );
  return interfaceDeclaration;
}
function createTypeAliasForTypeExpression(typeName, typeExpression) {
  const typeReference = getSynthesizedDeepClone(typeExpression.type);
  if (!typeReference)
    return;
  const declaration = factory.createTypeAliasDeclaration(
    /*modifiers*/
    void 0,
    factory.createIdentifier(typeName),
    /*typeParameters*/
    void 0,
    typeReference
  );
  return declaration;
}
function createSignatureFromTypeLiteral(typeLiteral) {
  const propertyTags = typeLiteral.jsDocPropertyTags;
  if (!some(propertyTags))
    return;
  const getSignature = (tag) => {
    var _a;
    const name = getPropertyName(tag);
    const type = (_a = tag.typeExpression) == null ? void 0 : _a.type;
    const isOptional = tag.isBracketed;
    let typeReference;
    if (type && isJSDocTypeLiteral(type)) {
      const signatures = createSignatureFromTypeLiteral(type);
      typeReference = factory.createTypeLiteralNode(signatures);
    } else if (type) {
      typeReference = getSynthesizedDeepClone(type);
    }
    if (typeReference && name) {
      const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0;
      const prop = factory.createPropertySignature(
        /*modifiers*/
        void 0,
        name,
        questionToken,
        typeReference
      );
      return prop;
    }
  };
  const props = mapDefined(propertyTags, getSignature);
  return props;
}
function getPropertyName(tag) {
  return tag.name.kind === 80 /* Identifier */ ? tag.name.text : tag.name.right.text;
}
function getJSDocTypedefNode(node) {
  if (hasJSDocNodes(node)) {
    return forEach(node.jsDoc, (node2) => {
      var _a;
      return (_a = node2.tags) == null ? void 0 : _a.find(isJSDocTypedefTag);
    });
  }
  return void 0;
}

// src/services/codefixes/convertLiteralTypeToMappedType.ts
var fixId15 = "convertLiteralTypeToMappedType";
var errorCodes16 = [Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code];
registerCodeFix({
  errorCodes: errorCodes16,
  getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) {
    const { sourceFile, span } = context;
    const info = getInfo5(sourceFile, span.start);
    if (!info) {
      return void 0;
    }
    const { name, constraint } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, info));
    return [createCodeFixAction(fixId15, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId15, Diagnostics.Convert_all_type_literals_to_mapped_type)];
  },
  fixIds: [fixId15],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes16, (changes, diag2) => {
    const info = getInfo5(diag2.file, diag2.start);
    if (info) {
      doChange13(changes, diag2.file, info);
    }
  })
});
function getInfo5(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(token)) {
    const propertySignature = cast(token.parent.parent, isPropertySignature);
    const propertyName = token.getText(sourceFile);
    return {
      container: cast(propertySignature.parent, isTypeLiteralNode),
      typeNode: propertySignature.type,
      constraint: propertyName,
      name: propertyName === "K" ? "P" : "K"
    };
  }
  return void 0;
}
function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) {
  changes.replaceNode(sourceFile, container, factory.createMappedTypeNode(
    /*readonlyToken*/
    void 0,
    factory.createTypeParameterDeclaration(
      /*modifiers*/
      void 0,
      name,
      factory.createTypeReferenceNode(constraint)
    ),
    /*nameType*/
    void 0,
    /*questionToken*/
    void 0,
    typeNode,
    /*members*/
    void 0
  ));
}

// src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts
var errorCodes17 = [
  Diagnostics.Class_0_incorrectly_implements_interface_1.code,
  Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code
];
var fixId16 = "fixClassIncorrectlyImplementsInterface";
registerCodeFix({
  errorCodes: errorCodes17,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const classDeclaration = getClass(sourceFile, span.start);
    return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), (implementedTypeNode) => {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences));
      return changes.length === 0 ? void 0 : createCodeFixAction(fixId16, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId16, Diagnostics.Implement_all_unimplemented_interfaces);
    });
  },
  fixIds: [fixId16],
  getAllCodeActions(context) {
    const seenClassDeclarations = /* @__PURE__ */ new Map();
    return codeFixAll(context, errorCodes17, (changes, diag2) => {
      const classDeclaration = getClass(diag2.file, diag2.start);
      if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) {
        for (const implementedTypeNode of getEffectiveImplementsTypeNodes(classDeclaration)) {
          addMissingDeclarations(context, implementedTypeNode, diag2.file, classDeclaration, changes, context.preferences);
        }
      }
    });
  }
});
function getClass(sourceFile, pos) {
  return Debug.checkDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
}
function symbolPointsToNonPrivateMember(symbol) {
  return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 8 /* Private */);
}
function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) {
  const checker = context.program.getTypeChecker();
  const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
  const implementedType = checker.getTypeAtLocation(implementedTypeNode);
  const implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
  const nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(and(symbolPointsToNonPrivateMember, (symbol) => !maybeHeritageClauseSymbol.has(symbol.escapedName)));
  const classType = checker.getTypeAtLocation(classDeclaration);
  const constructor = find(classDeclaration.members, (m) => isConstructorDeclaration(m));
  if (!classType.getNumberIndexType()) {
    createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */);
  }
  if (!classType.getStringIndexType()) {
    createMissingIndexSignatureDeclaration(implementedType, 0 /* String */);
  }
  const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host);
  createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, (member) => insertInterfaceMemberNode(sourceFile, classDeclaration, member));
  importAdder.writeFixes(changeTracker);
  function createMissingIndexSignatureDeclaration(type, kind) {
    const indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
    if (indexInfoOfKind) {
      insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(
        indexInfoOfKind,
        classDeclaration,
        /*flags*/
        void 0,
        getNoopSymbolTrackerWithResolver(context)
      ));
    }
  }
  function insertInterfaceMemberNode(sourceFile2, cls, newElement) {
    if (constructor) {
      changeTracker.insertNodeAfter(sourceFile2, constructor, newElement);
    } else {
      changeTracker.insertMemberAtStart(sourceFile2, cls, newElement);
    }
  }
}
function getHeritageClauseSymbolTable(classDeclaration, checker) {
  const heritageClauseNode = getEffectiveBaseTypeNode(classDeclaration);
  if (!heritageClauseNode)
    return createSymbolTable();
  const heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
  const heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType);
  return createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember));
}

// src/services/codefixes/importFixes.ts
var importFixName = "import";
var importFixId = "fixMissingImport";
var errorCodes18 = [
  Diagnostics.Cannot_find_name_0.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
  Diagnostics.Cannot_find_namespace_0.code,
  Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
  Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
  Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code,
  Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code
];
registerCodeFix({
  errorCodes: errorCodes18,
  getCodeActions(context) {
    const { errorCode, preferences, sourceFile, span, program } = context;
    const info = getFixInfos(
      context,
      errorCode,
      span.start,
      /*useAutoImportProvider*/
      true
    );
    if (!info)
      return void 0;
    return info.map(({ fix, symbolName: symbolName2, errorIdentifierText }) => codeActionForFix(
      context,
      sourceFile,
      symbolName2,
      fix,
      /*includeSymbolNameInDescription*/
      symbolName2 !== errorIdentifierText,
      program.getCompilerOptions(),
      preferences
    ));
  },
  fixIds: [importFixId],
  getAllCodeActions: (context) => {
    const { sourceFile, program, preferences, host, cancellationToken } = context;
    const importAdder = createImportAdderWorker(
      sourceFile,
      program,
      /*useAutoImportProvider*/
      true,
      preferences,
      host,
      cancellationToken
    );
    eachDiagnostic(context, errorCodes18, (diag2) => importAdder.addImportFromDiagnostic(diag2, context));
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, importAdder.writeFixes));
  }
});
function createImportAdder(sourceFile, program, preferences, host, cancellationToken) {
  return createImportAdderWorker(
    sourceFile,
    program,
    /*useAutoImportProvider*/
    false,
    preferences,
    host,
    cancellationToken
  );
}
function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host, cancellationToken) {
  const compilerOptions = program.getCompilerOptions();
  const addToNamespace = [];
  const importType = [];
  const addToExisting = /* @__PURE__ */ new Map();
  const newImports = /* @__PURE__ */ new Map();
  return { addImportFromDiagnostic, addImportFromExportedSymbol, writeFixes, hasFixes };
  function addImportFromDiagnostic(diagnostic, context) {
    const info = getFixInfos(context, diagnostic.code, diagnostic.start, useAutoImportProvider);
    if (!info || !info.length)
      return;
    addImport(first(info));
  }
  function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite) {
    const moduleSymbol = Debug.checkDefined(exportedSymbol.parent);
    const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions));
    const checker = program.getTypeChecker();
    const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker));
    const exportInfo = getAllExportInfoForSymbol(
      sourceFile,
      symbol,
      symbolName2,
      moduleSymbol,
      /*preferCapitalized*/
      false,
      program,
      host,
      preferences,
      cancellationToken
    );
    const useRequire = shouldUseRequire(sourceFile, program);
    const fix = getImportFixForSymbol(
      sourceFile,
      Debug.checkDefined(exportInfo),
      program,
      /*position*/
      void 0,
      !!isValidTypeOnlyUseSite,
      useRequire,
      host,
      preferences
    );
    if (fix) {
      addImport({ fix, symbolName: symbolName2, errorIdentifierText: void 0 });
    }
  }
  function addImport(info) {
    var _a, _b;
    const { fix, symbolName: symbolName2 } = info;
    switch (fix.kind) {
      case 0 /* UseNamespace */:
        addToNamespace.push(fix);
        break;
      case 1 /* JsdocTypeImport */:
        importType.push(fix);
        break;
      case 2 /* AddToExisting */: {
        const { importClauseOrBindingPattern, importKind, addAsTypeOnly } = fix;
        const key = String(getNodeId(importClauseOrBindingPattern));
        let entry = addToExisting.get(key);
        if (!entry) {
          addToExisting.set(key, entry = { importClauseOrBindingPattern, defaultImport: void 0, namedImports: /* @__PURE__ */ new Map() });
        }
        if (importKind === 0 /* Named */) {
          const prevValue = entry == null ? void 0 : entry.namedImports.get(symbolName2);
          entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly));
        } else {
          Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName");
          entry.defaultImport = {
            name: symbolName2,
            addAsTypeOnly: reduceAddAsTypeOnlyValues((_a = entry.defaultImport) == null ? void 0 : _a.addAsTypeOnly, addAsTypeOnly)
          };
        }
        break;
      }
      case 3 /* AddNew */: {
        const { moduleSpecifier, importKind, useRequire, addAsTypeOnly } = fix;
        const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly);
        Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module");
        switch (importKind) {
          case 1 /* Default */:
            Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName");
            entry.defaultImport = { name: symbolName2, addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) };
            break;
          case 0 /* Named */:
            const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2);
            entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly));
            break;
          case 3 /* CommonJS */:
          case 2 /* Namespace */:
            Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName");
            entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly };
            break;
        }
        break;
      }
      case 4 /* PromoteTypeOnly */:
        break;
      default:
        Debug.assertNever(fix, `fix wasn't never - got kind ${fix.kind}`);
    }
    function reduceAddAsTypeOnlyValues(prevValue, newValue) {
      return Math.max(prevValue ?? 0, newValue);
    }
    function getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly) {
      const typeOnlyKey = newImportsKey(
        moduleSpecifier,
        /*topLevelTypeOnly*/
        true
      );
      const nonTypeOnlyKey = newImportsKey(
        moduleSpecifier,
        /*topLevelTypeOnly*/
        false
      );
      const typeOnlyEntry = newImports.get(typeOnlyKey);
      const nonTypeOnlyEntry = newImports.get(nonTypeOnlyKey);
      const newEntry = {
        defaultImport: void 0,
        namedImports: void 0,
        namespaceLikeImport: void 0,
        useRequire
      };
      if (importKind === 1 /* Default */ && addAsTypeOnly === 2 /* Required */) {
        if (typeOnlyEntry)
          return typeOnlyEntry;
        newImports.set(typeOnlyKey, newEntry);
        return newEntry;
      }
      if (addAsTypeOnly === 1 /* Allowed */ && (typeOnlyEntry || nonTypeOnlyEntry)) {
        return typeOnlyEntry || nonTypeOnlyEntry;
      }
      if (nonTypeOnlyEntry) {
        return nonTypeOnlyEntry;
      }
      newImports.set(nonTypeOnlyKey, newEntry);
      return newEntry;
    }
    function newImportsKey(moduleSpecifier, topLevelTypeOnly) {
      return `${topLevelTypeOnly ? 1 : 0}|${moduleSpecifier}`;
    }
  }
  function writeFixes(changeTracker) {
    const quotePreference = getQuotePreference(sourceFile, preferences);
    for (const fix of addToNamespace) {
      addNamespaceQualifier(changeTracker, sourceFile, fix);
    }
    for (const fix of importType) {
      addImportType(changeTracker, sourceFile, fix, quotePreference);
    }
    addToExisting.forEach(({ importClauseOrBindingPattern, defaultImport, namedImports }) => {
      doAddExistingFix(
        changeTracker,
        sourceFile,
        importClauseOrBindingPattern,
        defaultImport,
        arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })),
        preferences
      );
    });
    let newDeclarations;
    newImports.forEach(({ useRequire, defaultImport, namedImports, namespaceLikeImport }, key) => {
      const moduleSpecifier = key.slice(2);
      const getDeclarations = useRequire ? getNewRequires : getNewImports;
      const declarations = getDeclarations(
        moduleSpecifier,
        quotePreference,
        defaultImport,
        namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })),
        namespaceLikeImport,
        compilerOptions
      );
      newDeclarations = combine(newDeclarations, declarations);
    });
    if (newDeclarations) {
      insertImports(
        changeTracker,
        sourceFile,
        newDeclarations,
        /*blankLineBetween*/
        true,
        preferences
      );
    }
  }
  function hasFixes() {
    return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0;
  }
}
function createImportSpecifierResolver(importingFile, program, host, preferences) {
  const packageJsonImportFilter = createPackageJsonImportFilter(importingFile, preferences, host);
  const importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions());
  return { getModuleSpecifierForBestExportInfo };
  function getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, fromCacheOnly) {
    const { fixes, computedWithoutCacheCount } = getImportFixes(
      exportInfo,
      position,
      isValidTypeOnlyUseSite,
      /*useRequire*/
      false,
      program,
      importingFile,
      host,
      preferences,
      importMap,
      fromCacheOnly
    );
    const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host);
    return result && { ...result, computedWithoutCacheCount };
  }
}
function getImportCompletionAction(targetSymbol, moduleSymbol, exportMapKey, sourceFile, symbolName2, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) {
  const compilerOptions = program.getCompilerOptions();
  let exportInfos;
  if (exportMapKey) {
    exportInfos = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken).get(sourceFile.path, exportMapKey);
    Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified exportMapKey");
  } else {
    exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name)) ? [getSingleExportInfoForSymbol(targetSymbol, symbolName2, moduleSymbol, program, host)] : getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName2, moduleSymbol, isJsxTagName, program, host, preferences, cancellationToken);
    Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified symbol / moduleSymbol");
  }
  const useRequire = shouldUseRequire(sourceFile, program);
  const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position));
  const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences));
  return {
    moduleSpecifier: fix.moduleSpecifier,
    codeAction: codeFixActionToCodeAction(codeActionForFix(
      { host, formatContext, preferences },
      sourceFile,
      symbolName2,
      fix,
      /*includeSymbolNameInDescription*/
      false,
      compilerOptions,
      preferences
    ))
  };
}
function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) {
  const compilerOptions = program.getCompilerOptions();
  const symbolName2 = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions));
  const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program);
  const includeSymbolNameInDescription = symbolName2 !== symbolToken.text;
  return fix && codeFixActionToCodeAction(codeActionForFix({ host, formatContext, preferences }, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences));
}
function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) {
  const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host);
  return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host);
}
function codeFixActionToCodeAction({ description: description3, changes, commands }) {
  return { description: description3, changes, commands };
}
function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) {
  const getChecker = createGetChecker(program, host);
  return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name) => name === symbolName2, (info) => {
    if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some((i) => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) {
      return info;
    }
  });
}
function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program, host) {
  var _a, _b;
  const compilerOptions = program.getCompilerOptions();
  const mainProgramInfo = getInfoWithChecker(
    program.getTypeChecker(),
    /*isFromPackageJson*/
    false
  );
  if (mainProgramInfo) {
    return mainProgramInfo;
  }
  const autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getTypeChecker();
  return Debug.checkDefined(autoImportProvider && getInfoWithChecker(
    autoImportProvider,
    /*isFromPackageJson*/
    true
  ), `Could not find symbol in specified module for code actions`);
  function getInfoWithChecker(checker, isFromPackageJson) {
    const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions);
    if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) {
      return { symbol: defaultInfo.symbol, moduleSymbol, moduleFileName: void 0, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
    }
    const named = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol);
    if (named && skipAlias(named, checker) === symbol) {
      return { symbol: named, moduleSymbol, moduleFileName: void 0, exportKind: 0 /* Named */, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
    }
  }
}
function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()), fromCacheOnly) {
  const checker = program.getTypeChecker();
  const existingImports = flatMap(exportInfos, importMap.getImportsForExportInfo);
  const useNamespace = usagePosition !== void 0 && tryUseExistingNamespaceImport(existingImports, usagePosition);
  const addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions());
  if (addToExisting) {
    return {
      computedWithoutCacheCount: 0,
      fixes: [...useNamespace ? [useNamespace] : emptyArray, addToExisting]
    };
  }
  const { fixes, computedWithoutCacheCount = 0 } = getFixesForAddImport(
    exportInfos,
    existingImports,
    program,
    sourceFile,
    usagePosition,
    isValidTypeOnlyUseSite,
    useRequire,
    host,
    preferences,
    fromCacheOnly
  );
  return {
    computedWithoutCacheCount,
    fixes: [...useNamespace ? [useNamespace] : emptyArray, ...fixes]
  };
}
function tryUseExistingNamespaceImport(existingImports, position) {
  return firstDefined(existingImports, ({ declaration, importKind }) => {
    var _a;
    if (importKind !== 0 /* Named */)
      return void 0;
    const namespacePrefix = getNamespaceLikeImportText(declaration);
    const moduleSpecifier = namespacePrefix && ((_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text);
    if (moduleSpecifier) {
      return { kind: 0 /* UseNamespace */, namespacePrefix, usagePosition: position, moduleSpecifier };
    }
  });
}
function getNamespaceLikeImportText(declaration) {
  var _a, _b, _c;
  switch (declaration.kind) {
    case 259 /* VariableDeclaration */:
      return (_a = tryCast(declaration.name, isIdentifier)) == null ? void 0 : _a.text;
    case 270 /* ImportEqualsDeclaration */:
      return declaration.name.text;
    case 271 /* ImportDeclaration */:
      return (_c = tryCast((_b = declaration.importClause) == null ? void 0 : _b.namedBindings, isNamespaceImport)) == null ? void 0 : _c.name.text;
    default:
      return Debug.assertNever(declaration);
  }
}
function getAddAsTypeOnly(isValidTypeOnlyUseSite, isForNewImportDeclaration, symbol, targetFlags, checker, compilerOptions) {
  if (!isValidTypeOnlyUseSite) {
    return 4 /* NotAllowed */;
  }
  if (isForNewImportDeclaration && compilerOptions.importsNotUsedAsValues === 2 /* Error */) {
    return 2 /* Required */;
  }
  if (importNameElisionDisabled(compilerOptions) && (!(targetFlags & 111551 /* Value */) || !!checker.getTypeOnlyAliasDeclaration(symbol))) {
    return 2 /* Required */;
  }
  return 1 /* Allowed */;
}
function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, compilerOptions) {
  let best;
  for (const existingImport of existingImports) {
    const fix = getAddToExistingImportFix(existingImport);
    if (!fix)
      continue;
    const isTypeOnly = isTypeOnlyImportDeclaration(fix.importClauseOrBindingPattern);
    if (fix.addAsTypeOnly !== 4 /* NotAllowed */ && isTypeOnly || fix.addAsTypeOnly === 4 /* NotAllowed */ && !isTypeOnly) {
      return fix;
    }
    best ?? (best = fix);
  }
  return best;
  function getAddToExistingImportFix({ declaration, importKind, symbol, targetFlags }) {
    if (importKind === 3 /* CommonJS */ || importKind === 2 /* Namespace */ || declaration.kind === 270 /* ImportEqualsDeclaration */) {
      return void 0;
    }
    if (declaration.kind === 259 /* VariableDeclaration */) {
      return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 205 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind, moduleSpecifier: declaration.initializer.arguments[0].text, addAsTypeOnly: 4 /* NotAllowed */ } : void 0;
    }
    const { importClause } = declaration;
    if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) {
      return void 0;
    }
    const { name, namedBindings } = importClause;
    if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) {
      return void 0;
    }
    const addAsTypeOnly = getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      false,
      symbol,
      targetFlags,
      checker,
      compilerOptions
    );
    if (importKind === 1 /* Default */ && (name || // Cannot add a default import to a declaration that already has one
    addAsTypeOnly === 2 /* Required */ && namedBindings)) {
      return void 0;
    }
    if (importKind === 0 /* Named */ && (namedBindings == null ? void 0 : namedBindings.kind) === 273 /* NamespaceImport */) {
      return void 0;
    }
    return {
      kind: 2 /* AddToExisting */,
      importClauseOrBindingPattern: importClause,
      importKind,
      moduleSpecifier: declaration.moduleSpecifier.text,
      addAsTypeOnly
    };
  }
}
function createExistingImportMap(checker, importingFile, compilerOptions) {
  let importMap;
  for (const moduleSpecifier of importingFile.imports) {
    const i = importFromModuleSpecifier(moduleSpecifier);
    if (isVariableDeclarationInitializedToRequire(i.parent)) {
      const moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier);
      if (moduleSymbol) {
        (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i.parent);
      }
    } else if (i.kind === 271 /* ImportDeclaration */ || i.kind === 270 /* ImportEqualsDeclaration */) {
      const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
      if (moduleSymbol) {
        (importMap || (importMap = createMultiMap())).add(getSymbolId(moduleSymbol), i);
      }
    }
  }
  return {
    getImportsForExportInfo: ({ moduleSymbol, exportKind, targetFlags, symbol }) => {
      if (!(targetFlags & 111551 /* Value */) && isSourceFileJS(importingFile))
        return emptyArray;
      const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol));
      if (!matchingDeclarations)
        return emptyArray;
      const importKind = getImportKind(importingFile, exportKind, compilerOptions);
      return matchingDeclarations.map((declaration) => ({ declaration, importKind, symbol, targetFlags }));
    }
  };
}
function shouldUseRequire(sourceFile, program) {
  if (!isSourceFileJS(sourceFile)) {
    return false;
  }
  if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator)
    return true;
  if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator)
    return false;
  const compilerOptions = program.getCompilerOptions();
  if (compilerOptions.configFile) {
    return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */;
  }
  for (const otherFile of program.getSourceFiles()) {
    if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile))
      continue;
    if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator)
      return true;
    if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator)
      return false;
  }
  return true;
}
function createGetChecker(program, host) {
  return memoizeOne((isFromPackageJson) => isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker());
}
function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) {
  const isJs = isSourceFileJS(sourceFile);
  const compilerOptions = program.getCompilerOptions();
  const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
  const getChecker = createGetChecker(program, host);
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution);
  const getModuleSpecifiers2 = fromCacheOnly ? (moduleSymbol) => ({ moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }) : (moduleSymbol, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences);
  let computedWithoutCacheCount = 0;
  const fixes = flatMap(exportInfo, (exportInfo2, i) => {
    const checker = getChecker(exportInfo2.isFromPackageJson);
    const { computedWithoutCache, moduleSpecifiers } = getModuleSpecifiers2(exportInfo2.moduleSymbol, checker);
    const importedSymbolHasValueMeaning = !!(exportInfo2.targetFlags & 111551 /* Value */);
    const addAsTypeOnly = getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      true,
      exportInfo2.symbol,
      exportInfo2.targetFlags,
      checker,
      compilerOptions
    );
    computedWithoutCacheCount += computedWithoutCache ? 1 : 0;
    return mapDefined(moduleSpecifiers, (moduleSpecifier) => {
      var _a;
      if (rejectNodeModulesRelativePaths && pathContainsNodeModules(moduleSpecifier)) {
        return void 0;
      }
      if (!importedSymbolHasValueMeaning && isJs && usagePosition !== void 0) {
        return { kind: 1 /* JsdocTypeImport */, moduleSpecifier, usagePosition, exportInfo: exportInfo2, isReExport: i > 0 };
      }
      const importKind = getImportKind(sourceFile, exportInfo2.exportKind, compilerOptions);
      let qualification;
      if (usagePosition !== void 0 && importKind === 3 /* CommonJS */ && exportInfo2.exportKind === 0 /* Named */) {
        const exportEquals = checker.resolveExternalModuleSymbol(exportInfo2.moduleSymbol);
        let namespacePrefix;
        if (exportEquals !== exportInfo2.moduleSymbol) {
          namespacePrefix = (_a = getDefaultExportInfoWorker(exportEquals, checker, compilerOptions)) == null ? void 0 : _a.name;
        }
        namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier(
          exportInfo2.moduleSymbol,
          getEmitScriptTarget(compilerOptions),
          /*forceCapitalize*/
          false
        ));
        qualification = { namespacePrefix, usagePosition };
      }
      return {
        kind: 3 /* AddNew */,
        moduleSpecifier,
        importKind,
        useRequire,
        addAsTypeOnly,
        exportInfo: exportInfo2,
        isReExport: i > 0,
        qualification
      };
    });
  });
  return { computedWithoutCacheCount, fixes };
}
function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly) {
  const existingDeclaration = firstDefined(existingImports, (info) => newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions()));
  return existingDeclaration ? { fixes: [existingDeclaration] } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly);
}
function newImportInfoFromExistingSpecifier({ declaration, importKind, symbol, targetFlags }, isValidTypeOnlyUseSite, useRequire, checker, compilerOptions) {
  var _a;
  const moduleSpecifier = (_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text;
  if (moduleSpecifier) {
    const addAsTypeOnly = useRequire ? 4 /* NotAllowed */ : getAddAsTypeOnly(
      isValidTypeOnlyUseSite,
      /*isForNewImportDeclaration*/
      true,
      symbol,
      targetFlags,
      checker,
      compilerOptions
    );
    return { kind: 3 /* AddNew */, moduleSpecifier, importKind, addAsTypeOnly, useRequire };
  }
}
function getFixInfos(context, errorCode, pos, useAutoImportProvider) {
  const symbolToken = getTokenAtPosition(context.sourceFile, pos);
  let info;
  if (errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) {
    info = getFixesInfoForUMDImport(context, symbolToken);
  } else if (!isIdentifier(symbolToken)) {
    return void 0;
  } else if (errorCode === Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) {
    const symbolName2 = single(getSymbolNamesToImport(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions()));
    const fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName2, context.program);
    return fix && [{ fix, symbolName: symbolName2, errorIdentifierText: symbolToken.text }];
  } else {
    info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider);
  }
  const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host);
  return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host);
}
function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host) {
  const _toPath = (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host));
  return sort(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath));
}
function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) {
  if (!some(fixes))
    return;
  if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) {
    return fixes[0];
  }
  return fixes.reduce(
    (best, fix) => (
      // Takes true branch of conditional if `fix` is better than `best`
      compareModuleSpecifiers(
        fix,
        best,
        sourceFile,
        program,
        packageJsonImportFilter.allowsImportingSpecifier,
        (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host))
      ) === -1 /* LessThan */ ? fix : best
    )
  );
}
function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath3) {
  if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) {
    return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans(
      isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath3),
      isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath3)
    ) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier);
  }
  return 0 /* EqualTo */;
}
function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath3) {
  var _a;
  if (fix.isReExport && ((_a = fix.exportInfo) == null ? void 0 : _a.moduleFileName) && getEmitModuleResolutionKind(compilerOptions) === 2 /* Node10 */ && isIndexFileName(fix.exportInfo.moduleFileName)) {
    const reExportDir = toPath3(getDirectoryPath(fix.exportInfo.moduleFileName));
    return startsWith(importingFile.path, reExportDir);
  }
  return false;
}
function isIndexFileName(fileName) {
  return getBaseFileName(
    fileName,
    [".js", ".jsx", ".d.ts", ".ts", ".tsx"],
    /*ignoreCase*/
    true
  ) === "index";
}
function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) {
  if (startsWith(a, "node:") && !startsWith(b, "node:"))
    return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */;
  if (startsWith(b, "node:") && !startsWith(a, "node:"))
    return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */;
  return 0 /* EqualTo */;
}
function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }, token) {
  const checker = program.getTypeChecker();
  const umdSymbol = getUmdSymbol(token, checker);
  if (!umdSymbol)
    return void 0;
  const symbol = checker.getAliasedSymbol(umdSymbol);
  const symbolName2 = umdSymbol.name;
  const exportInfo = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: void 0, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }];
  const useRequire = shouldUseRequire(sourceFile, program);
  const fixes = getImportFixes(
    exportInfo,
    /*usagePosition*/
    void 0,
    /*isValidTypeOnlyUseSite*/
    false,
    useRequire,
    program,
    sourceFile,
    host,
    preferences
  ).fixes;
  return fixes.map((fix) => {
    var _a;
    return { fix, symbolName: symbolName2, errorIdentifierText: (_a = tryCast(token, isIdentifier)) == null ? void 0 : _a.text };
  });
}
function getUmdSymbol(token, checker) {
  const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : void 0;
  if (isUMDExportSymbol(umdSymbol))
    return umdSymbol;
  const { parent: parent2 } = token;
  if (isJsxOpeningLikeElement(parent2) && parent2.tagName === token || isJsxOpeningFragment(parent2)) {
    const parentSymbol = checker.resolveName(
      checker.getJsxNamespace(parent2),
      isJsxOpeningLikeElement(parent2) ? token : parent2,
      111551 /* Value */,
      /*excludeGlobals*/
      false
    );
    if (isUMDExportSymbol(parentSymbol)) {
      return parentSymbol;
    }
  }
  return void 0;
}
function getImportKind(importingFile, exportKind, compilerOptions, forceImportKeyword) {
  if (compilerOptions.verbatimModuleSyntax && (getEmitModuleKind(compilerOptions) === 1 /* CommonJS */ || importingFile.impliedNodeFormat === 1 /* CommonJS */)) {
    return 3 /* CommonJS */;
  }
  switch (exportKind) {
    case 0 /* Named */:
      return 0 /* Named */;
    case 1 /* Default */:
      return 1 /* Default */;
    case 2 /* ExportEquals */:
      return getExportEqualsImportKind(importingFile, compilerOptions, !!forceImportKeyword);
    case 3 /* UMD */:
      return getUmdImportKind(importingFile, compilerOptions, !!forceImportKeyword);
    default:
      return Debug.assertNever(exportKind);
  }
}
function getUmdImportKind(importingFile, compilerOptions, forceImportKeyword) {
  if (getAllowSyntheticDefaultImports(compilerOptions)) {
    return 1 /* Default */;
  }
  const moduleKind = getEmitModuleKind(compilerOptions);
  switch (moduleKind) {
    case 2 /* AMD */:
    case 1 /* CommonJS */:
    case 3 /* UMD */:
      if (isInJSFile(importingFile)) {
        return isExternalModule(importingFile) || forceImportKeyword ? 2 /* Namespace */ : 3 /* CommonJS */;
      }
      return 3 /* CommonJS */;
    case 4 /* System */:
    case 5 /* ES2015 */:
    case 6 /* ES2020 */:
    case 7 /* ES2022 */:
    case 99 /* ESNext */:
    case 0 /* None */:
      return 2 /* Namespace */;
    case 100 /* Node16 */:
    case 199 /* NodeNext */:
      return importingFile.impliedNodeFormat === 99 /* ESNext */ ? 2 /* Namespace */ : 3 /* CommonJS */;
    default:
      return Debug.assertNever(moduleKind, `Unexpected moduleKind ${moduleKind}`);
  }
}
function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, host, preferences }, symbolToken, useAutoImportProvider) {
  const checker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), (symbolName2) => {
    if (symbolName2 === "default" /* Default */) {
      return void 0;
    }
    const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(symbolToken);
    const useRequire = shouldUseRequire(sourceFile, program);
    const exportInfo = getExportInfos(symbolName2, isJSXTagName(symbolToken), getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences);
    return arrayFrom(
      flatMapIterator(exportInfo.values(), (exportInfos) => getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes),
      (fix) => ({ fix, symbolName: symbolName2, errorIdentifierText: symbolToken.text, isJsxNamespaceFix: symbolName2 !== symbolToken.text })
    );
  });
}
function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program) {
  const checker = program.getTypeChecker();
  const symbol = checker.resolveName(
    symbolName2,
    symbolToken,
    111551 /* Value */,
    /*excludeGlobals*/
    true
  );
  if (!symbol)
    return void 0;
  const typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol);
  if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile)
    return void 0;
  return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration };
}
function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) {
  const parent2 = symbolToken.parent;
  if ((isJsxOpeningLikeElement(parent2) || isJsxClosingElement(parent2)) && parent2.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) {
    const jsxNamespace = checker.getJsxNamespace(sourceFile);
    if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) {
      const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(
        symbolToken.text,
        symbolToken,
        111551 /* Value */,
        /*excludeGlobals*/
        false
      );
      return needsComponentNameFix ? [symbolToken.text, jsxNamespace] : [jsxNamespace];
    }
  }
  return [symbolToken.text];
}
function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) {
  if (isIntrinsicJsxName(symbolToken.text))
    return true;
  const namespaceSymbol = checker.resolveName(
    jsxNamespace,
    symbolToken,
    111551 /* Value */,
    /*excludeGlobals*/
    true
  );
  return !namespaceSymbol || some(namespaceSymbol.declarations, isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */);
}
function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) {
  var _a;
  const originalSymbolToExportInfos = createMultiMap();
  const packageJsonFilter = createPackageJsonImportFilter(fromFile, preferences, host);
  const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host);
  const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => {
    return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host);
  });
  function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) {
    const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson);
    if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) {
      const checker = program2.getTypeChecker();
      originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFileName: toFile == null ? void 0 : toFile.fileName, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson });
    }
  }
  forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, (moduleSymbol, sourceFile, program2, isFromPackageJson) => {
    const checker = program2.getTypeChecker();
    cancellationToken.throwIfCancellationRequested();
    const compilerOptions = program2.getCompilerOptions();
    const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions);
    if (defaultInfo && (defaultInfo.name === symbolName2 || moduleSymbolToValidIdentifier(moduleSymbol, getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName2) && symbolHasMeaning(defaultInfo.resolvedSymbol, currentTokenMeaning)) {
      addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program2, isFromPackageJson);
    }
    const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol);
    if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
      addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program2, isFromPackageJson);
    }
  });
  return originalSymbolToExportInfos;
}
function getExportEqualsImportKind(importingFile, compilerOptions, forceImportKeyword) {
  const allowSyntheticDefaults = getAllowSyntheticDefaultImports(compilerOptions);
  const isJS = isInJSFile(importingFile);
  if (!isJS && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */) {
    return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */;
  }
  if (isJS) {
    return isExternalModule(importingFile) || forceImportKeyword ? allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ : 3 /* CommonJS */;
  }
  for (const statement of importingFile.statements) {
    if (isImportEqualsDeclaration(statement) && !nodeIsMissing(statement.moduleReference)) {
      return 3 /* CommonJS */;
    }
  }
  return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */;
}
function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) {
  let diag2;
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => {
    diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences);
  });
  return createCodeFixAction(importFixName, changes, diag2, importFixId, Diagnostics.Add_all_missing_imports);
}
function codeActionForFixWorker(changes, sourceFile, symbolName2, fix, includeSymbolNameInDescription, compilerOptions, preferences) {
  const quotePreference = getQuotePreference(sourceFile, preferences);
  switch (fix.kind) {
    case 0 /* UseNamespace */:
      addNamespaceQualifier(changes, sourceFile, fix);
      return [Diagnostics.Change_0_to_1, symbolName2, `${fix.namespacePrefix}.${symbolName2}`];
    case 1 /* JsdocTypeImport */:
      addImportType(changes, sourceFile, fix, quotePreference);
      return [Diagnostics.Change_0_to_1, symbolName2, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName2];
    case 2 /* AddToExisting */: {
      const { importClauseOrBindingPattern, importKind, addAsTypeOnly, moduleSpecifier } = fix;
      doAddExistingFix(
        changes,
        sourceFile,
        importClauseOrBindingPattern,
        importKind === 1 /* Default */ ? { name: symbolName2, addAsTypeOnly } : void 0,
        importKind === 0 /* Named */ ? [{ name: symbolName2, addAsTypeOnly }] : emptyArray,
        preferences
      );
      const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier);
      return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifierWithoutQuotes] : [Diagnostics.Update_import_from_0, moduleSpecifierWithoutQuotes];
    }
    case 3 /* AddNew */: {
      const { importKind, moduleSpecifier, addAsTypeOnly, useRequire, qualification } = fix;
      const getDeclarations = useRequire ? getNewRequires : getNewImports;
      const defaultImport = importKind === 1 /* Default */ ? { name: symbolName2, addAsTypeOnly } : void 0;
      const namedImports = importKind === 0 /* Named */ ? [{ name: symbolName2, addAsTypeOnly }] : void 0;
      const namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { importKind, name: (qualification == null ? void 0 : qualification.namespacePrefix) || symbolName2, addAsTypeOnly } : void 0;
      insertImports(
        changes,
        sourceFile,
        getDeclarations(
          moduleSpecifier,
          quotePreference,
          defaultImport,
          namedImports,
          namespaceLikeImport,
          compilerOptions
        ),
        /*blankLineBetween*/
        true,
        preferences
      );
      if (qualification) {
        addNamespaceQualifier(changes, sourceFile, qualification);
      }
      return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifier] : [Diagnostics.Add_import_from_0, moduleSpecifier];
    }
    case 4 /* PromoteTypeOnly */: {
      const { typeOnlyAliasDeclaration } = fix;
      const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile, preferences);
      return promotedDeclaration.kind === 275 /* ImportSpecifier */ ? [Diagnostics.Remove_type_from_import_of_0_from_1, symbolName2, getModuleSpecifierText(promotedDeclaration.parent.parent)] : [Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)];
    }
    default:
      return Debug.assertNever(fix, `Unexpected fix kind ${fix.kind}`);
  }
}
function getModuleSpecifierText(promotedDeclaration) {
  var _a, _b;
  return promotedDeclaration.kind === 270 /* ImportEqualsDeclaration */ ? ((_b = tryCast((_a = tryCast(promotedDeclaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression, isStringLiteralLike)) == null ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() : cast(promotedDeclaration.parent.moduleSpecifier, isStringLiteral).text;
}
function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceFile, preferences) {
  const convertExistingToTypeOnly = importNameElisionDisabled(compilerOptions);
  switch (aliasDeclaration.kind) {
    case 275 /* ImportSpecifier */:
      if (aliasDeclaration.isTypeOnly) {
        const sortKind = ts_OrganizeImports_exports.detectImportSpecifierSorting(aliasDeclaration.parent.elements, preferences);
        if (aliasDeclaration.parent.elements.length > 1 && sortKind) {
          changes.delete(sourceFile, aliasDeclaration);
          const newSpecifier = factory.updateImportSpecifier(
            aliasDeclaration,
            /*isTypeOnly*/
            false,
            aliasDeclaration.propertyName,
            aliasDeclaration.name
          );
          const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */);
          const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer);
          changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex);
        } else {
          changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken());
        }
        return aliasDeclaration;
      } else {
        Debug.assert(aliasDeclaration.parent.parent.isTypeOnly);
        promoteImportClause(aliasDeclaration.parent.parent);
        return aliasDeclaration.parent.parent;
      }
    case 272 /* ImportClause */:
      promoteImportClause(aliasDeclaration);
      return aliasDeclaration;
    case 273 /* NamespaceImport */:
      promoteImportClause(aliasDeclaration.parent);
      return aliasDeclaration.parent;
    case 270 /* ImportEqualsDeclaration */:
      changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1));
      return aliasDeclaration;
    default:
      Debug.failBadSyntaxKind(aliasDeclaration);
  }
  function promoteImportClause(importClause) {
    changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile));
    if (convertExistingToTypeOnly) {
      const namedImports = tryCast(importClause.namedBindings, isNamedImports);
      if (namedImports && namedImports.elements.length > 1) {
        if (ts_OrganizeImports_exports.detectImportSpecifierSorting(namedImports.elements, preferences) && aliasDeclaration.kind === 275 /* ImportSpecifier */ && namedImports.elements.indexOf(aliasDeclaration) !== 0) {
          changes.delete(sourceFile, aliasDeclaration);
          changes.insertImportSpecifierAtIndex(sourceFile, aliasDeclaration, namedImports, 0);
        }
        for (const element of namedImports.elements) {
          if (element !== aliasDeclaration && !element.isTypeOnly) {
            changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, element);
          }
        }
      }
    }
  }
}
function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, preferences) {
  var _a;
  if (clause.kind === 205 /* ObjectBindingPattern */) {
    if (defaultImport) {
      addElementToBindingPattern(clause, defaultImport.name, "default");
    }
    for (const specifier of namedImports) {
      addElementToBindingPattern(
        clause,
        specifier.name,
        /*propertyName*/
        void 0
      );
    }
    return;
  }
  const promoteFromTypeOnly2 = clause.isTypeOnly && some([defaultImport, ...namedImports], (i) => (i == null ? void 0 : i.addAsTypeOnly) === 4 /* NotAllowed */);
  const existingSpecifiers = clause.namedBindings && ((_a = tryCast(clause.namedBindings, isNamedImports)) == null ? void 0 : _a.elements);
  if (defaultImport) {
    Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one");
    changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), factory.createIdentifier(defaultImport.name), { suffix: ", " });
  }
  if (namedImports.length) {
    let ignoreCaseForSorting;
    if (typeof preferences.organizeImportsIgnoreCase === "boolean") {
      ignoreCaseForSorting = preferences.organizeImportsIgnoreCase;
    } else if (existingSpecifiers) {
      const targetImportSorting = ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences);
      if (targetImportSorting !== 3 /* Both */) {
        ignoreCaseForSorting = targetImportSorting === 2 /* CaseInsensitive */;
      }
    }
    if (ignoreCaseForSorting === void 0) {
      ignoreCaseForSorting = ts_OrganizeImports_exports.detectSorting(sourceFile, preferences) === 2 /* CaseInsensitive */;
    }
    const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, ignoreCaseForSorting);
    const newSpecifiers = stableSort(
      namedImports.map((namedImport) => factory.createImportSpecifier(
        (!clause.isTypeOnly || promoteFromTypeOnly2) && needsTypeOnly(namedImport),
        /*propertyName*/
        void 0,
        factory.createIdentifier(namedImport.name)
      )),
      (s1, s2) => ts_OrganizeImports_exports.compareImportOrExportSpecifiers(s1, s2, comparer)
    );
    const specifierSort = (existingSpecifiers == null ? void 0 : existingSpecifiers.length) && ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences);
    if (specifierSort && !(ignoreCaseForSorting && specifierSort === 1 /* CaseSensitive */)) {
      for (const spec of newSpecifiers) {
        const insertionIndex = promoteFromTypeOnly2 && !spec.isTypeOnly ? 0 : ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(existingSpecifiers, spec, comparer);
        changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings, insertionIndex);
      }
    } else if (existingSpecifiers == null ? void 0 : existingSpecifiers.length) {
      for (const spec of newSpecifiers) {
        changes.insertNodeInListAfter(sourceFile, last(existingSpecifiers), spec, existingSpecifiers);
      }
    } else {
      if (newSpecifiers.length) {
        const namedImports2 = factory.createNamedImports(newSpecifiers);
        if (clause.namedBindings) {
          changes.replaceNode(sourceFile, clause.namedBindings, namedImports2);
        } else {
          changes.insertNodeAfter(sourceFile, Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports2);
        }
      }
    }
  }
  if (promoteFromTypeOnly2) {
    changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(clause, sourceFile));
    if (existingSpecifiers) {
      for (const specifier of existingSpecifiers) {
        changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, specifier);
      }
    }
  }
  function addElementToBindingPattern(bindingPattern, name, propertyName) {
    const element = factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      propertyName,
      name
    );
    if (bindingPattern.elements.length) {
      changes.insertNodeInListAfter(sourceFile, last(bindingPattern.elements), element);
    } else {
      changes.replaceNode(sourceFile, bindingPattern, factory.createObjectBindingPattern([element]));
    }
  }
}
function addNamespaceQualifier(changes, sourceFile, { namespacePrefix, usagePosition }) {
  changes.insertText(sourceFile, usagePosition, namespacePrefix + ".");
}
function addImportType(changes, sourceFile, { moduleSpecifier, usagePosition: position }, quotePreference) {
  changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference));
}
function getImportTypePrefix(moduleSpecifier, quotePreference) {
  const quote2 = getQuoteFromPreference(quotePreference);
  return `import(${quote2}${moduleSpecifier}${quote2}).`;
}
function needsTypeOnly({ addAsTypeOnly }) {
  return addAsTypeOnly === 2 /* Required */;
}
function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions) {
  const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference);
  let statements;
  if (defaultImport !== void 0 || (namedImports == null ? void 0 : namedImports.length)) {
    const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || compilerOptions.verbatimModuleSyntax && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i) => i.addAsTypeOnly === 4 /* NotAllowed */);
    statements = combine(statements, makeImport(
      defaultImport && factory.createIdentifier(defaultImport.name),
      namedImports == null ? void 0 : namedImports.map(({ addAsTypeOnly, name }) => factory.createImportSpecifier(
        !topLevelTypeOnly && addAsTypeOnly === 2 /* Required */,
        /*propertyName*/
        void 0,
        factory.createIdentifier(name)
      )),
      moduleSpecifier,
      quotePreference,
      topLevelTypeOnly
    ));
  }
  if (namespaceLikeImport) {
    const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration(
      /*modifiers*/
      void 0,
      needsTypeOnly(namespaceLikeImport),
      factory.createIdentifier(namespaceLikeImport.name),
      factory.createExternalModuleReference(quotedModuleSpecifier)
    ) : factory.createImportDeclaration(
      /*modifiers*/
      void 0,
      factory.createImportClause(
        needsTypeOnly(namespaceLikeImport),
        /*name*/
        void 0,
        factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name))
      ),
      quotedModuleSpecifier,
      /*assertClause*/
      void 0
    );
    statements = combine(statements, declaration);
  }
  return Debug.checkDefined(statements);
}
function getNewRequires(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport) {
  const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference);
  let statements;
  if (defaultImport || (namedImports == null ? void 0 : namedImports.length)) {
    const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name }) => factory.createBindingElement(
      /*dotDotDotToken*/
      void 0,
      /*propertyName*/
      void 0,
      name
    ))) || [];
    if (defaultImport) {
      bindingElements.unshift(factory.createBindingElement(
        /*dotDotDotToken*/
        void 0,
        "default",
        defaultImport.name
      ));
    }
    const declaration = createConstEqualsRequireDeclaration(factory.createObjectBindingPattern(bindingElements), quotedModuleSpecifier);
    statements = combine(statements, declaration);
  }
  if (namespaceLikeImport) {
    const declaration = createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier);
    statements = combine(statements, declaration);
  }
  return Debug.checkDefined(statements);
}
function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) {
  return factory.createVariableStatement(
    /*modifiers*/
    void 0,
    factory.createVariableDeclarationList(
      [
        factory.createVariableDeclaration(
          typeof name === "string" ? factory.createIdentifier(name) : name,
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          factory.createCallExpression(
            factory.createIdentifier("require"),
            /*typeArguments*/
            void 0,
            [quotedModuleSpecifier]
          )
        )
      ],
      2 /* Const */
    )
  );
}
function symbolHasMeaning({ declarations }, meaning) {
  return some(declarations, (decl) => !!(getMeaningFromDeclaration(decl) & meaning));
}
function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) {
  return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize);
}
function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) {
  const baseName = getBaseFileName(removeSuffix(moduleSpecifier, "/index"));
  let res = "";
  let lastCharWasValid = true;
  const firstCharCode = baseName.charCodeAt(0);
  if (isIdentifierStart(firstCharCode, target)) {
    res += String.fromCharCode(firstCharCode);
    if (forceCapitalize) {
      res = res.toUpperCase();
    }
  } else {
    lastCharWasValid = false;
  }
  for (let i = 1; i < baseName.length; i++) {
    const ch = baseName.charCodeAt(i);
    const isValid = isIdentifierPart(ch, target);
    if (isValid) {
      let char = String.fromCharCode(ch);
      if (!lastCharWasValid) {
        char = char.toUpperCase();
      }
      res += char;
    }
    lastCharWasValid = isValid;
  }
  return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`;
}

// src/services/codefixes/fixAddMissingConstraint.ts
var fixId17 = "addMissingConstraint";
var errorCodes19 = [
  // We want errors this could be attached to:
  // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint
  Diagnostics.Type_0_is_not_comparable_to_type_1.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code,
  Diagnostics.Property_0_is_incompatible_with_index_signature.code,
  Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
  Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code
];
registerCodeFix({
  errorCodes: errorCodes19,
  getCodeActions(context) {
    const { sourceFile, span, program, preferences, host } = context;
    const info = getInfo6(program, sourceFile, span);
    if (info === void 0)
      return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info));
    return [createCodeFixAction(fixId17, changes, Diagnostics.Add_extends_constraint, fixId17, Diagnostics.Add_extends_constraint_to_all_type_parameters)];
  },
  fixIds: [fixId17],
  getAllCodeActions: (context) => {
    const { program, preferences, host } = context;
    const seen = /* @__PURE__ */ new Map();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes19, (diag2) => {
        const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length));
        if (info) {
          if (addToSeen(seen, getNodeId(info.declaration))) {
            return addMissingConstraint(changes, program, preferences, host, diag2.file, info);
          }
        }
        return void 0;
      });
    }));
  }
});
function getInfo6(program, sourceFile, span) {
  const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length);
  if (diag2 === void 0 || diag2.relatedInformation === void 0)
    return;
  const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code);
  if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0)
    return;
  let declaration = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length));
  if (declaration === void 0)
    return;
  if (isIdentifier(declaration) && isTypeParameterDeclaration(declaration.parent)) {
    declaration = declaration.parent;
  }
  if (isTypeParameterDeclaration(declaration)) {
    if (isMappedTypeNode(declaration.parent))
      return;
    const token = getTokenAtPosition(sourceFile, span.start);
    const checker = program.getTypeChecker();
    const constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText);
    return { constraint, declaration, token };
  }
  return void 0;
}
function addMissingConstraint(changes, program, preferences, host, sourceFile, info) {
  const { declaration, constraint } = info;
  const checker = program.getTypeChecker();
  if (isString(constraint)) {
    changes.insertText(sourceFile, declaration.name.end, ` extends ${constraint}`);
  } else {
    const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
    const tracker = getNoopSymbolTrackerWithResolver({ program, host });
    const importAdder = createImportAdder(sourceFile, program, preferences, host);
    const typeNode = typeToAutoImportableTypeNode(
      checker,
      importAdder,
      constraint,
      /*contextNode*/
      void 0,
      scriptTarget,
      /*flags*/
      void 0,
      tracker
    );
    if (typeNode) {
      changes.replaceNode(sourceFile, declaration, factory.updateTypeParameterDeclaration(
        declaration,
        /*modifiers*/
        void 0,
        declaration.name,
        typeNode,
        declaration.default
      ));
      importAdder.writeFixes(changes);
    }
  }
}
function tryGetConstraintFromDiagnosticMessage(messageText) {
  const [_, constraint] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [];
  return constraint;
}
function tryGetConstraintType(checker, node) {
  if (isTypeNode(node.parent)) {
    return checker.getTypeArgumentConstraint(node.parent);
  }
  const contextualType = isExpression(node) ? checker.getContextualType(node) : void 0;
  return contextualType || checker.getTypeAtLocation(node);
}

// src/services/codefixes/fixOverrideModifier.ts
var fixName = "fixOverrideModifier";
var fixAddOverrideId = "fixAddOverrideModifier";
var fixRemoveOverrideId = "fixRemoveOverrideModifier";
var errorCodes20 = [
  Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code,
  Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code,
  Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code,
  Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code,
  Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code,
  Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code,
  Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code,
  Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code,
  Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code
];
var errorCodeFixIdMap = {
  // case #1:
  [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  [Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  // case #2:
  [Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  },
  [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_override_modifier
  },
  // case #3:
  [Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  [Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers
  },
  // case #4:
  [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Add_override_modifier,
    fixId: fixAddOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  },
  // case #5:
  [Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  },
  [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code]: {
    descriptions: Diagnostics.Remove_override_modifier,
    fixId: fixRemoveOverrideId,
    fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers
  }
};
registerCodeFix({
  errorCodes: errorCodes20,
  getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) {
    const { errorCode, span } = context;
    const info = errorCodeFixIdMap[errorCode];
    if (!info)
      return emptyArray;
    const { descriptions, fixId: fixId52, fixAllDescriptions } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => dispatchChanges(changes2, context, errorCode, span.start));
    return [
      createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId52, fixAllDescriptions)
    ];
  },
  fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes20, (changes, diag2) => {
    const { code, start: start2 } = diag2;
    const info = errorCodeFixIdMap[code];
    if (!info || info.fixId !== context.fixId) {
      return;
    }
    dispatchChanges(changes, context, code, start2);
  })
});
function dispatchChanges(changeTracker, context, errorCode, pos) {
  switch (errorCode) {
    case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code:
    case Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code:
    case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code:
    case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code:
    case Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code:
      return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos);
    case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code:
    case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code:
    case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code:
    case Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code:
      return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos);
    default:
      Debug.fail("Unexpected error code: " + errorCode);
  }
}
function doAddOverrideModifierChange(changeTracker, sourceFile, pos) {
  const classElement = findContainerClassElementLike(sourceFile, pos);
  if (isSourceFileJS(sourceFile)) {
    changeTracker.addJSDocTags(sourceFile, classElement, [factory.createJSDocOverrideTag(factory.createIdentifier("override"))]);
    return;
  }
  const modifiers = classElement.modifiers || emptyArray;
  const staticModifier = find(modifiers, isStaticModifier);
  const abstractModifier = find(modifiers, isAbstractModifier);
  const accessibilityModifier = find(modifiers, (m) => isAccessibilityModifier(m.kind));
  const lastDecorator = findLast(modifiers, isDecorator);
  const modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile);
  const options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " };
  changeTracker.insertModifierAt(sourceFile, modifierPos, 163 /* OverrideKeyword */, options);
}
function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) {
  const classElement = findContainerClassElementLike(sourceFile, pos);
  if (isSourceFileJS(sourceFile)) {
    changeTracker.filterJSDocTags(sourceFile, classElement, not(isJSDocOverrideTag));
    return;
  }
  const overrideModifier = find(classElement.modifiers, isOverrideModifier);
  Debug.assertIsDefined(overrideModifier);
  changeTracker.deleteModifier(sourceFile, overrideModifier);
}
function isClassElementLikeHasJSDoc(node) {
  switch (node.kind) {
    case 175 /* Constructor */:
    case 171 /* PropertyDeclaration */:
    case 173 /* MethodDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
      return true;
    case 168 /* Parameter */:
      return isParameterPropertyDeclaration(node, node.parent);
    default:
      return false;
  }
}
function findContainerClassElementLike(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const classElement = findAncestor(token, (node) => {
    if (isClassLike(node))
      return "quit";
    return isClassElementLikeHasJSDoc(node);
  });
  Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement));
  return classElement;
}

// src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts
var fixId18 = "fixNoPropertyAccessFromIndexSignature";
var errorCodes21 = [
  Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code
];
registerCodeFix({
  errorCodes: errorCodes21,
  fixIds: [fixId18],
  getCodeActions(context) {
    const { sourceFile, span, preferences } = context;
    const property = getPropertyAccessExpression(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange14(t, context.sourceFile, property, preferences));
    return [createCodeFixAction(fixId18, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId18, Diagnostics.Use_element_access_for_all_undeclared_properties)];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences))
});
function doChange14(changes, sourceFile, node, preferences) {
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */);
  changes.replaceNode(
    sourceFile,
    node,
    isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : factory.createElementAccessExpression(node.expression, argumentsExpression)
  );
}
function getPropertyAccessExpression(sourceFile, pos) {
  return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression);
}

// src/services/codefixes/fixImplicitThis.ts
var fixId19 = "fixImplicitThis";
var errorCodes22 = [Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code];
registerCodeFix({
  errorCodes: errorCodes22,
  getCodeActions: function getCodeActionsToFixImplicitThis(context) {
    const { sourceFile, program, span } = context;
    let diagnostic;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker());
    });
    return diagnostic ? [createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray;
  },
  fixIds: [fixId19],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => {
    doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker());
  })
});
function doChange15(changes, sourceFile, pos, checker) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (!isThis(token))
    return void 0;
  const fn = getThisContainer(
    token,
    /*includeArrowFunctions*/
    false,
    /*includeClassComputedPropertyName*/
    false
  );
  if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn))
    return void 0;
  if (!isSourceFile(getThisContainer(
    fn,
    /*includeArrowFunctions*/
    false,
    /*includeClassComputedPropertyName*/
    false
  ))) {
    const fnKeyword = Debug.checkDefined(findChildOfKind(fn, 100 /* FunctionKeyword */, sourceFile));
    const { name } = fn;
    const body = Debug.checkDefined(fn.body);
    if (isFunctionExpression(fn)) {
      if (name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) {
        return void 0;
      }
      changes.delete(sourceFile, fnKeyword);
      if (name) {
        changes.delete(sourceFile, name);
      }
      changes.insertText(sourceFile, body.pos, " =>");
      return [Diagnostics.Convert_function_expression_0_to_arrow_function, name ? name.text : ANONYMOUS];
    } else {
      changes.replaceNode(sourceFile, fnKeyword, factory.createToken(87 /* ConstKeyword */));
      changes.insertText(sourceFile, name.end, " = ");
      changes.insertText(sourceFile, body.pos, " =>");
      return [Diagnostics.Convert_function_declaration_0_to_arrow_function, name.text];
    }
  }
}

// src/services/codefixes/fixImportNonExportedMember.ts
var fixId20 = "fixImportNonExportedMember";
var errorCodes23 = [
  Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code
];
registerCodeFix({
  errorCodes: errorCodes23,
  fixIds: [fixId20],
  getCodeActions(context) {
    const { sourceFile, span, program } = context;
    const info = getInfo7(sourceFile, span.start, program);
    if (info === void 0)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info));
    return [createCodeFixAction(fixId20, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId20, Diagnostics.Export_all_referenced_locals)];
  },
  getAllCodeActions(context) {
    const { program } = context;
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      const exports = /* @__PURE__ */ new Map();
      eachDiagnostic(context, errorCodes23, (diag2) => {
        const info = getInfo7(diag2.file, diag2.start, program);
        if (info === void 0)
          return void 0;
        const { exportName, node, moduleSourceFile } = info;
        if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === void 0 && canHaveExportModifier(node)) {
          changes.insertExportModifier(moduleSourceFile, node);
        } else {
          const moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] };
          if (exportName.isTypeOnly) {
            moduleExports.typeOnlyExports.push(exportName);
          } else {
            moduleExports.exports.push(exportName);
          }
          exports.set(moduleSourceFile, moduleExports);
        }
      });
      exports.forEach((moduleExports, moduleSourceFile) => {
        const exportDeclaration = tryGetExportDeclaration(
          moduleSourceFile,
          /*isTypeOnly*/
          true
        );
        if (exportDeclaration && exportDeclaration.isTypeOnly) {
          doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration);
          doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(
            moduleSourceFile,
            /*isTypeOnly*/
            false
          ));
        } else {
          doChanges(changes, program, moduleSourceFile, [...moduleExports.exports, ...moduleExports.typeOnlyExports], exportDeclaration);
        }
      });
    }));
  }
});
function getInfo7(sourceFile, pos, program) {
  var _a;
  const token = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(token)) {
    const importDeclaration = findAncestor(token, isImportDeclaration);
    if (importDeclaration === void 0)
      return void 0;
    const moduleSpecifier = isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : void 0;
    if (moduleSpecifier === void 0)
      return void 0;
    const resolvedModule = getResolvedModule(
      sourceFile,
      moduleSpecifier,
      /*mode*/
      void 0
    );
    if (resolvedModule === void 0)
      return void 0;
    const moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName);
    if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile))
      return void 0;
    const moduleSymbol = moduleSourceFile.symbol;
    const locals = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals;
    if (locals === void 0)
      return void 0;
    const localSymbol = locals.get(token.escapedText);
    if (localSymbol === void 0)
      return void 0;
    const node = getNodeOfSymbol(localSymbol);
    if (node === void 0)
      return void 0;
    const exportName = { node: token, isTypeOnly: isTypeDeclaration(node) };
    return { exportName, node, moduleSourceFile, moduleSpecifier };
  }
  return void 0;
}
function doChange16(changes, program, { exportName, node, moduleSourceFile }) {
  const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly);
  if (exportDeclaration) {
    updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]);
  } else if (canHaveExportModifier(node)) {
    changes.insertExportModifier(moduleSourceFile, node);
  } else {
    createExport(changes, program, moduleSourceFile, [exportName]);
  }
}
function doChanges(changes, program, sourceFile, moduleExports, node) {
  if (length(moduleExports)) {
    if (node) {
      updateExport(changes, program, sourceFile, node, moduleExports);
    } else {
      createExport(changes, program, sourceFile, moduleExports);
    }
  }
}
function tryGetExportDeclaration(sourceFile, isTypeOnly) {
  const predicate = (node) => isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly);
  return findLast(sourceFile.statements, predicate);
}
function updateExport(changes, program, sourceFile, node, names) {
  const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]);
  const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, (e) => e.isTypeOnly));
  changes.replaceNode(
    sourceFile,
    node,
    factory.updateExportDeclaration(
      node,
      node.modifiers,
      node.isTypeOnly,
      factory.createNamedExports(
        factory.createNodeArray(
          [...namedExports, ...createExportSpecifiers(names, allowTypeModifier)],
          /*hasTrailingComma*/
          namedExports.hasTrailingComma
        )
      ),
      node.moduleSpecifier,
      node.assertClause
    )
  );
}
function createExport(changes, program, sourceFile, names) {
  changes.insertNodeAtEndOfScope(
    sourceFile,
    sourceFile,
    factory.createExportDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      false,
      factory.createNamedExports(createExportSpecifiers(
        names,
        /*allowTypeModifier*/
        getIsolatedModules(program.getCompilerOptions())
      )),
      /*moduleSpecifier*/
      void 0,
      /*assertClause*/
      void 0
    )
  );
}
function createExportSpecifiers(names, allowTypeModifier) {
  return factory.createNodeArray(map(names, (n) => factory.createExportSpecifier(
    allowTypeModifier && n.isTypeOnly,
    /*propertyName*/
    void 0,
    n.node
  )));
}
function getNodeOfSymbol(symbol) {
  if (symbol.valueDeclaration === void 0) {
    return firstOrUndefined(symbol.declarations);
  }
  const declaration = symbol.valueDeclaration;
  const variableStatement = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : void 0;
  return variableStatement && length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration;
}

// src/services/codefixes/fixIncorrectNamedTupleSyntax.ts
var fixId21 = "fixIncorrectNamedTupleSyntax";
var errorCodes24 = [
  Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code,
  Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code
];
registerCodeFix({
  errorCodes: errorCodes24,
  getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) {
    const { sourceFile, span } = context;
    const namedTupleMember = getNamedTupleMember(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, namedTupleMember));
    return [createCodeFixAction(fixId21, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId21, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)];
  },
  fixIds: [fixId21]
});
function getNamedTupleMember(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  return findAncestor(token, (t) => t.kind === 201 /* NamedTupleMember */);
}
function doChange17(changes, sourceFile, namedTupleMember) {
  if (!namedTupleMember) {
    return;
  }
  let unwrappedType = namedTupleMember.type;
  let sawOptional = false;
  let sawRest = false;
  while (unwrappedType.kind === 189 /* OptionalType */ || unwrappedType.kind === 190 /* RestType */ || unwrappedType.kind === 195 /* ParenthesizedType */) {
    if (unwrappedType.kind === 189 /* OptionalType */) {
      sawOptional = true;
    } else if (unwrappedType.kind === 190 /* RestType */) {
      sawRest = true;
    }
    unwrappedType = unwrappedType.type;
  }
  const updated = factory.updateNamedTupleMember(
    namedTupleMember,
    namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(26 /* DotDotDotToken */) : void 0),
    namedTupleMember.name,
    namedTupleMember.questionToken || (sawOptional ? factory.createToken(58 /* QuestionToken */) : void 0),
    unwrappedType
  );
  if (updated === namedTupleMember) {
    return;
  }
  changes.replaceNode(sourceFile, namedTupleMember, updated);
}

// src/services/codefixes/fixSpelling.ts
var fixId22 = "fixSpelling";
var errorCodes25 = [
  Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
  Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
  Diagnostics.Could_not_find_name_0_Did_you_mean_1.code,
  Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
  Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code,
  Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code,
  Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code,
  // for JSX class components
  Diagnostics.No_overload_matches_this_call.code,
  // for JSX FC
  Diagnostics.Type_0_is_not_assignable_to_type_1.code
];
registerCodeFix({
  errorCodes: errorCodes25,
  getCodeActions(context) {
    const { sourceFile, errorCode } = context;
    const info = getInfo8(sourceFile, context.span.start, context, errorCode);
    if (!info)
      return void 0;
    const { node, suggestedSymbol } = info;
    const target = getEmitScriptTarget(context.host.getCompilationSettings());
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18(t, sourceFile, node, suggestedSymbol, target));
    return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId22, Diagnostics.Fix_all_detected_spelling_errors)];
  },
  fixIds: [fixId22],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => {
    const info = getInfo8(diag2.file, diag2.start, context, diag2.code);
    const target = getEmitScriptTarget(context.host.getCompilationSettings());
    if (info)
      doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target);
  })
});
function getInfo8(sourceFile, pos, context, errorCode) {
  const node = getTokenAtPosition(sourceFile, pos);
  const parent2 = node.parent;
  if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2))
    return void 0;
  const checker = context.program.getTypeChecker();
  let suggestedSymbol;
  if (isPropertyAccessExpression(parent2) && parent2.name === node) {
    Debug.assert(isMemberName(node), "Expected an identifier for spelling (property access)");
    let containingType = checker.getTypeAtLocation(parent2.expression);
    if (parent2.flags & 32 /* OptionalChain */) {
      containingType = checker.getNonNullableType(containingType);
    }
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType);
  } else if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 103 /* InKeyword */ && parent2.left === node && isPrivateIdentifier(node)) {
    const receiverType = checker.getTypeAtLocation(parent2.right);
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, receiverType);
  } else if (isQualifiedName(parent2) && parent2.right === node) {
    const symbol = checker.getSymbolAtLocation(parent2.left);
    if (symbol && symbol.flags & 1536 /* Module */) {
      suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(parent2.right, symbol);
    }
  } else if (isImportSpecifier(parent2) && parent2.name === node) {
    Debug.assertNode(node, isIdentifier, "Expected an identifier for spelling (import)");
    const importDeclaration = findAncestor(node, isImportDeclaration);
    const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration);
    if (resolvedSourceFile && resolvedSourceFile.symbol) {
      suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol);
    }
  } else if (isJsxAttribute(parent2) && parent2.name === node) {
    Debug.assertNode(node, isIdentifier, "Expected an identifier for JSX attribute");
    const tag = findAncestor(node, isJsxOpeningLikeElement);
    const props = checker.getContextualTypeForArgumentAtIndex(tag, 0);
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentJSXAttribute(node, props);
  } else if (hasSyntacticModifier(parent2, 16384 /* Override */) && isClassElement(parent2) && parent2.name === node) {
    const baseDeclaration = findAncestor(node, isClassLike);
    const baseTypeNode = baseDeclaration ? getEffectiveBaseTypeNode(baseDeclaration) : void 0;
    const baseType = baseTypeNode ? checker.getTypeAtLocation(baseTypeNode) : void 0;
    if (baseType) {
      suggestedSymbol = checker.getSuggestedSymbolForNonexistentClassMember(getTextOfNode(node), baseType);
    }
  } else {
    const meaning = getMeaningFromLocation(node);
    const name = getTextOfNode(node);
    Debug.assert(name !== void 0, "name should be defined");
    suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
  }
  return suggestedSymbol === void 0 ? void 0 : { node, suggestedSymbol };
}
function doChange18(changes, sourceFile, node, suggestedSymbol, target) {
  const suggestion = symbolName(suggestedSymbol);
  if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) {
    const valDecl = suggestedSymbol.valueDeclaration;
    if (valDecl && isNamedDeclaration(valDecl) && isPrivateIdentifier(valDecl.name)) {
      changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion));
    } else {
      changes.replaceNode(sourceFile, node.parent, factory.createElementAccessExpression(node.parent.expression, factory.createStringLiteral(suggestion)));
    }
  } else {
    changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion));
  }
}
function convertSemanticMeaningToSymbolFlags(meaning) {
  let flags = 0;
  if (meaning & 4 /* Namespace */) {
    flags |= 1920 /* Namespace */;
  }
  if (meaning & 2 /* Type */) {
    flags |= 788968 /* Type */;
  }
  if (meaning & 1 /* Value */) {
    flags |= 111551 /* Value */;
  }
  return flags;
}
function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) {
  if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier))
    return void 0;
  const resolvedModule = getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text, getModeForUsageLocation(sourceFile, importDeclaration.moduleSpecifier));
  if (!resolvedModule)
    return void 0;
  return context.program.getSourceFile(resolvedModule.resolvedFileName);
}

// src/services/codefixes/returnValueCorrect.ts
var fixId23 = "returnValueCorrect";
var fixIdAddReturnStatement = "fixAddReturnStatement";
var fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody";
var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen";
var errorCodes26 = [
  Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code,
  Diagnostics.Type_0_is_not_assignable_to_type_1.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code
];
registerCodeFix({
  errorCodes: errorCodes26,
  fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen],
  getCodeActions: function getCodeActionsToCorrectReturnValue(context) {
    const { program, sourceFile, span: { start: start2 }, errorCode } = context;
    const info = getInfo9(program.getTypeChecker(), sourceFile, start2, errorCode);
    if (!info)
      return void 0;
    if (info.kind === 0 /* MissingReturnStatement */) {
      return append(
        [getActionForfixAddReturnStatement(context, info.expression, info.statement)],
        isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : void 0
      );
    } else {
      return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)];
    }
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => {
    const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code);
    if (!info)
      return void 0;
    switch (context.fixId) {
      case fixIdAddReturnStatement:
        addReturnStatement(changes, diag2.file, info.expression, info.statement);
        break;
      case fixRemoveBracesFromArrowFunctionBody:
        if (!isArrowFunction(info.declaration))
          return void 0;
        removeBlockBodyBrace(
          changes,
          diag2.file,
          info.declaration,
          info.expression,
          info.commentSource,
          /*withParen*/
          false
        );
        break;
      case fixIdWrapTheBlockWithParen:
        if (!isArrowFunction(info.declaration))
          return void 0;
        wrapBlockWithParen(changes, diag2.file, info.declaration, info.expression);
        break;
      default:
        Debug.fail(JSON.stringify(context.fixId));
    }
  })
});
function createObjectTypeFromLabeledExpression(checker, label, expression) {
  const member = checker.createSymbol(4 /* Property */, label.escapedText);
  member.links.type = checker.getTypeAtLocation(expression);
  const members = createSymbolTable([member]);
  return checker.createAnonymousType(
    /*symbol*/
    void 0,
    members,
    [],
    [],
    []
  );
}
function getFixInfo(checker, declaration, expectType, isFunctionType) {
  if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1)
    return void 0;
  const firstStatement = first(declaration.body.statements);
  if (isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, checker.getTypeAtLocation(firstStatement.expression), expectType, isFunctionType)) {
    return {
      declaration,
      kind: 0 /* MissingReturnStatement */,
      expression: firstStatement.expression,
      statement: firstStatement,
      commentSource: firstStatement.expression
    };
  } else if (isLabeledStatement(firstStatement) && isExpressionStatement(firstStatement.statement)) {
    const node = factory.createObjectLiteralExpression([factory.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]);
    const nodeType = createObjectTypeFromLabeledExpression(checker, firstStatement.label, firstStatement.statement.expression);
    if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) {
      return isArrowFunction(declaration) ? {
        declaration,
        kind: 1 /* MissingParentheses */,
        expression: node,
        statement: firstStatement,
        commentSource: firstStatement.statement.expression
      } : {
        declaration,
        kind: 0 /* MissingReturnStatement */,
        expression: node,
        statement: firstStatement,
        commentSource: firstStatement.statement.expression
      };
    }
  } else if (isBlock(firstStatement) && length(firstStatement.statements) === 1) {
    const firstBlockStatement = first(firstStatement.statements);
    if (isLabeledStatement(firstBlockStatement) && isExpressionStatement(firstBlockStatement.statement)) {
      const node = factory.createObjectLiteralExpression([factory.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]);
      const nodeType = createObjectTypeFromLabeledExpression(checker, firstBlockStatement.label, firstBlockStatement.statement.expression);
      if (checkFixedAssignableTo(checker, declaration, nodeType, expectType, isFunctionType)) {
        return {
          declaration,
          kind: 0 /* MissingReturnStatement */,
          expression: node,
          statement: firstStatement,
          commentSource: firstBlockStatement
        };
      }
    }
  }
  return void 0;
}
function checkFixedAssignableTo(checker, declaration, exprType, type, isFunctionType) {
  if (isFunctionType) {
    const sig = checker.getSignatureFromDeclaration(declaration);
    if (sig) {
      if (hasSyntacticModifier(declaration, 512 /* Async */)) {
        exprType = checker.createPromiseType(exprType);
      }
      const newSig = checker.createSignature(
        declaration,
        sig.typeParameters,
        sig.thisParameter,
        sig.parameters,
        exprType,
        /*typePredicate*/
        void 0,
        sig.minArgumentCount,
        sig.flags
      );
      exprType = checker.createAnonymousType(
        /*symbol*/
        void 0,
        createSymbolTable(),
        [newSig],
        [],
        []
      );
    } else {
      exprType = checker.getAnyType();
    }
  }
  return checker.isTypeAssignableTo(exprType, type);
}
function getInfo9(checker, sourceFile, position, errorCode) {
  const node = getTokenAtPosition(sourceFile, position);
  if (!node.parent)
    return void 0;
  const declaration = findAncestor(node.parent, isFunctionLikeDeclaration);
  switch (errorCode) {
    case Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code:
      if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node))
        return void 0;
      return getFixInfo(
        checker,
        declaration,
        checker.getTypeFromTypeNode(declaration.type),
        /*isFunctionType*/
        false
      );
    case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code:
      if (!declaration || !isCallExpression(declaration.parent) || !declaration.body)
        return void 0;
      const pos = declaration.parent.arguments.indexOf(declaration);
      const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos);
      if (!type)
        return void 0;
      return getFixInfo(
        checker,
        declaration,
        type,
        /*isFunctionType*/
        true
      );
    case Diagnostics.Type_0_is_not_assignable_to_type_1.code:
      if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent))
        return void 0;
      const initializer = getVariableLikeInitializer(node.parent);
      if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body)
        return void 0;
      return getFixInfo(
        checker,
        initializer,
        checker.getTypeAtLocation(node.parent),
        /*isFunctionType*/
        true
      );
  }
  return void 0;
}
function getVariableLikeInitializer(declaration) {
  switch (declaration.kind) {
    case 259 /* VariableDeclaration */:
    case 168 /* Parameter */:
    case 207 /* BindingElement */:
    case 171 /* PropertyDeclaration */:
    case 302 /* PropertyAssignment */:
      return declaration.initializer;
    case 290 /* JsxAttribute */:
      return declaration.initializer && (isJsxExpression(declaration.initializer) ? declaration.initializer.expression : void 0);
    case 303 /* ShorthandPropertyAssignment */:
    case 170 /* PropertySignature */:
    case 305 /* EnumMember */:
    case 354 /* JSDocPropertyTag */:
    case 347 /* JSDocParameterTag */:
      return void 0;
  }
}
function addReturnStatement(changes, sourceFile, expression, statement) {
  suppressLeadingAndTrailingTrivia(expression);
  const probablyNeedSemi = probablyUsesSemicolons(sourceFile);
  changes.replaceNode(sourceFile, statement, factory.createReturnStatement(expression), {
    leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
    trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude,
    suffix: probablyNeedSemi ? ";" : void 0
  });
}
function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) {
  const newBody = withParen || needsParentheses(expression) ? factory.createParenthesizedExpression(expression) : expression;
  suppressLeadingAndTrailingTrivia(commentSource);
  copyComments(commentSource, newBody);
  changes.replaceNode(sourceFile, declaration.body, newBody);
}
function wrapBlockWithParen(changes, sourceFile, declaration, expression) {
  changes.replaceNode(sourceFile, declaration.body, factory.createParenthesizedExpression(expression));
}
function getActionForfixAddReturnStatement(context, expression, statement) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addReturnStatement(t, context.sourceFile, expression, statement));
  return createCodeFixAction(fixId23, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement);
}
function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, expression, commentSource) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => removeBlockBodyBrace(
    t,
    context.sourceFile,
    declaration,
    expression,
    commentSource,
    /*withParen*/
    false
  ));
  return createCodeFixAction(fixId23, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues);
}
function getActionForfixWrapTheBlockWithParen(context, declaration, expression) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => wrapBlockWithParen(t, context.sourceFile, declaration, expression));
  return createCodeFixAction(fixId23, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses);
}

// src/services/codefixes/fixAddMissingMember.ts
var fixMissingMember = "fixMissingMember";
var fixMissingProperties = "fixMissingProperties";
var fixMissingAttributes = "fixMissingAttributes";
var fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration";
var errorCodes27 = [
  Diagnostics.Property_0_does_not_exist_on_type_1.code,
  Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
  Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
  Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
  Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code,
  Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
  Diagnostics.Cannot_find_name_0.code
];
registerCodeFix({
  errorCodes: errorCodes27,
  getCodeActions(context) {
    const typeChecker = context.program.getTypeChecker();
    const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program);
    if (!info) {
      return void 0;
    }
    if (info.kind === 3 /* ObjectLiteral */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addObjectLiteralProperties(t, context, info));
      return [createCodeFixAction(fixMissingProperties, changes, Diagnostics.Add_missing_properties, fixMissingProperties, Diagnostics.Add_all_missing_properties)];
    }
    if (info.kind === 4 /* JsxAttributes */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addJsxAttributes(t, context, info));
      return [createCodeFixAction(fixMissingAttributes, changes, Diagnostics.Add_missing_attributes, fixMissingAttributes, Diagnostics.Add_all_missing_attributes)];
    }
    if (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addFunctionDeclaration(t, context, info));
      return [createCodeFixAction(fixMissingFunctionDeclaration, changes, [Diagnostics.Add_missing_function_declaration_0, info.token.text], fixMissingFunctionDeclaration, Diagnostics.Add_all_missing_function_declarations)];
    }
    if (info.kind === 1 /* Enum */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addEnumMemberDeclaration(t, context.program.getTypeChecker(), info));
      return [createCodeFixAction(fixMissingMember, changes, [Diagnostics.Add_missing_enum_member_0, info.token.text], fixMissingMember, Diagnostics.Add_all_missing_members)];
    }
    return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info));
  },
  fixIds: [fixMissingMember, fixMissingFunctionDeclaration, fixMissingProperties, fixMissingAttributes],
  getAllCodeActions: (context) => {
    const { program, fixId: fixId52 } = context;
    const checker = program.getTypeChecker();
    const seen = /* @__PURE__ */ new Map();
    const typeDeclToMembers = /* @__PURE__ */ new Map();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes27, (diag2) => {
        const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program);
        if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
          return;
        }
        if (fixId52 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */)) {
          addFunctionDeclaration(changes, context, info);
        } else if (fixId52 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */) {
          addObjectLiteralProperties(changes, context, info);
        } else if (fixId52 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */) {
          addJsxAttributes(changes, context, info);
        } else {
          if (info.kind === 1 /* Enum */) {
            addEnumMemberDeclaration(changes, checker, info);
          }
          if (info.kind === 0 /* TypeLikeDeclaration */) {
            const { parentDeclaration, token } = info;
            const infos = getOrUpdate(typeDeclToMembers, parentDeclaration, () => []);
            if (!infos.some((i) => i.token.text === token.text)) {
              infos.push(info);
            }
          }
        }
      });
      typeDeclToMembers.forEach((infos, declaration) => {
        const supers = isTypeLiteralNode(declaration) ? void 0 : getAllSupers(declaration, checker);
        for (const info of infos) {
          if (supers == null ? void 0 : supers.some((superClassOrInterface) => {
            const superInfos = typeDeclToMembers.get(superClassOrInterface);
            return !!superInfos && superInfos.some(({ token: token2 }) => token2.text === info.token.text);
          }))
            continue;
          const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info;
          if (call && !isPrivateIdentifier(token)) {
            addMethodDeclaration(context, changes, call, token, modifierFlags & 32 /* Static */, parentDeclaration, declSourceFile);
          } else {
            if (isJSFile && !isInterfaceDeclaration(parentDeclaration) && !isTypeLiteralNode(parentDeclaration)) {
              addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */));
            } else {
              const typeNode = getTypeNode2(checker, parentDeclaration, token);
              addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & 32 /* Static */);
            }
          }
        }
      });
    }));
  }
});
function getInfo10(sourceFile, tokenPos, errorCode, checker, program) {
  var _a;
  const token = getTokenAtPosition(sourceFile, tokenPos);
  const parent2 = token.parent;
  if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) {
    if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent)))
      return void 0;
    const argIndex = findIndex(parent2.parent.arguments, (arg) => arg === parent2);
    if (argIndex < 0)
      return void 0;
    const signature = checker.getResolvedSignature(parent2.parent);
    if (!(signature && signature.declaration && signature.parameters[argIndex]))
      return void 0;
    const param = signature.parameters[argIndex].valueDeclaration;
    if (!(param && isParameter(param) && isIdentifier(param.name)))
      return void 0;
    const properties = arrayFrom(checker.getUnmatchedProperties(
      checker.getTypeAtLocation(parent2),
      checker.getParameterType(signature, argIndex),
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    ));
    if (!length(properties))
      return void 0;
    return { kind: 3 /* ObjectLiteral */, token: param.name, properties, parentDeclaration: parent2 };
  }
  if (!isMemberName(token))
    return void 0;
  if (isIdentifier(token) && hasInitializer(parent2) && parent2.initializer && isObjectLiteralExpression(parent2.initializer)) {
    const targetType = checker.getContextualType(token) || checker.getTypeAtLocation(token);
    const properties = arrayFrom(checker.getUnmatchedProperties(
      checker.getTypeAtLocation(parent2.initializer),
      targetType,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    ));
    if (!length(properties))
      return void 0;
    return { kind: 3 /* ObjectLiteral */, token, properties, parentDeclaration: parent2.initializer };
  }
  if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) {
    const target = getEmitScriptTarget(program.getCompilerOptions());
    const attributes = getUnmatchedAttributes(checker, target, token.parent);
    if (!length(attributes))
      return void 0;
    return { kind: 4 /* JsxAttributes */, token, attributes, parentDeclaration: token.parent };
  }
  if (isIdentifier(token)) {
    const type = (_a = checker.getContextualType(token)) == null ? void 0 : _a.getNonNullableType();
    if (type && getObjectFlags(type) & 16 /* Anonymous */) {
      const signature = firstOrUndefined(checker.getSignaturesOfType(type, 0 /* Call */));
      if (signature === void 0)
        return void 0;
      return { kind: 5 /* Signature */, token, signature, sourceFile, parentDeclaration: findScope(token) };
    }
    if (isCallExpression(parent2) && parent2.expression === token) {
      return { kind: 2 /* Function */, token, call: parent2, sourceFile, modifierFlags: 0 /* None */, parentDeclaration: findScope(token) };
    }
  }
  if (!isPropertyAccessExpression(parent2))
    return void 0;
  const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent2.expression));
  const symbol = leftExpressionType.symbol;
  if (!symbol || !symbol.declarations)
    return void 0;
  if (isIdentifier(token) && isCallExpression(parent2.parent)) {
    const moduleDeclaration = find(symbol.declarations, isModuleDeclaration);
    const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile();
    if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) {
      return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile, modifierFlags: 1 /* Export */, parentDeclaration: moduleDeclaration };
    }
    const moduleSourceFile = find(symbol.declarations, isSourceFile);
    if (sourceFile.commonJsModuleIndicator)
      return void 0;
    if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) {
      return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* Export */, parentDeclaration: moduleSourceFile };
    }
  }
  const classDeclaration = find(symbol.declarations, isClassLike);
  if (!classDeclaration && isPrivateIdentifier(token))
    return void 0;
  const declaration = classDeclaration || find(symbol.declarations, (d) => isInterfaceDeclaration(d) || isTypeLiteralNode(d));
  if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) {
    const makeStatic = !isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
    if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration)))
      return void 0;
    const declSourceFile = declaration.getSourceFile();
    const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 32 /* Static */ : 0 /* None */) | (startsWithUnderscore(token.text) ? 8 /* Private */ : 0 /* None */);
    const isJSFile = isSourceFileJS(declSourceFile);
    const call = tryCast(parent2.parent, isCallExpression);
    return { kind: 0 /* TypeLikeDeclaration */, token, call, modifierFlags, parentDeclaration: declaration, declSourceFile, isJSFile };
  }
  const enumDeclaration = find(symbol.declarations, isEnumDeclaration);
  if (enumDeclaration && !(leftExpressionType.flags & 1056 /* EnumLike */) && !isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) {
    return { kind: 1 /* Enum */, token, parentDeclaration: enumDeclaration };
  }
  return void 0;
}
function getActionsForMissingMemberDeclaration(context, info) {
  return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info);
}
function createActionForAddMissingMemberInJavascriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) {
  if (isInterfaceDeclaration(parentDeclaration) || isTypeLiteralNode(parentDeclaration)) {
    return void 0;
  }
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 32 /* Static */)));
  if (changes.length === 0) {
    return void 0;
  }
  const diagnostic = modifierFlags & 32 /* Static */ ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor;
  return createCodeFixAction(fixMissingMember, changes, [diagnostic, token.text], fixMissingMember, Diagnostics.Add_all_missing_members);
}
function addMissingMemberInJs(changeTracker, sourceFile, classDeclaration, token, makeStatic) {
  const tokenName = token.text;
  if (makeStatic) {
    if (classDeclaration.kind === 230 /* ClassExpression */) {
      return;
    }
    const className = classDeclaration.name.getText();
    const staticInitialization = initializePropertyToUndefined(factory.createIdentifier(className), tokenName);
    changeTracker.insertNodeAfter(sourceFile, classDeclaration, staticInitialization);
  } else if (isPrivateIdentifier(token)) {
    const property = factory.createPropertyDeclaration(
      /*modifiers*/
      void 0,
      tokenName,
      /*questionOrExclamationToken*/
      void 0,
      /*type*/
      void 0,
      /*initializer*/
      void 0
    );
    const lastProp = getNodeToInsertPropertyAfter(classDeclaration);
    if (lastProp) {
      changeTracker.insertNodeAfter(sourceFile, lastProp, property);
    } else {
      changeTracker.insertMemberAtStart(sourceFile, classDeclaration, property);
    }
  } else {
    const classConstructor = getFirstConstructorWithBody(classDeclaration);
    if (!classConstructor) {
      return;
    }
    const propertyInitialization = initializePropertyToUndefined(factory.createThis(), tokenName);
    changeTracker.insertNodeAtConstructorEnd(sourceFile, classConstructor, propertyInitialization);
  }
}
function initializePropertyToUndefined(obj, propertyName) {
  return factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(obj, propertyName), createUndefined()));
}
function createActionsForAddMissingMemberInTypeScriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) {
  const memberName = token.text;
  const isStatic2 = modifierFlags & 32 /* Static */;
  const typeNode = getTypeNode2(context.program.getTypeChecker(), parentDeclaration, token);
  const addPropertyDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2));
  const actions2 = [createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 32 /* Static */), [isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixMissingMember, Diagnostics.Add_all_missing_members)];
  if (isStatic2 || isPrivateIdentifier(token)) {
    return actions2;
  }
  if (modifierFlags & 8 /* Private */) {
    actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addPropertyDeclarationChanges(8 /* Private */), [Diagnostics.Declare_private_property_0, memberName]));
  }
  actions2.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode));
  return actions2;
}
function getTypeNode2(checker, node, token) {
  let typeNode;
  if (token.parent.parent.kind === 225 /* BinaryExpression */) {
    const binaryExpression = token.parent.parent;
    const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
    const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
    typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */);
  } else {
    const contextualType = checker.getContextualType(token.parent);
    typeNode = contextualType ? checker.typeToTypeNode(
      contextualType,
      /*enclosingDeclaration*/
      void 0,
      1 /* NoTruncation */
    ) : void 0;
  }
  return typeNode || factory.createKeywordTypeNode(133 /* AnyKeyword */);
}
function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) {
  const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0;
  const property = isClassLike(node) ? factory.createPropertyDeclaration(
    modifiers,
    tokenName,
    /*questionOrExclamationToken*/
    void 0,
    typeNode,
    /*initializer*/
    void 0
  ) : factory.createPropertySignature(
    /*modifiers*/
    void 0,
    tokenName,
    /*questionToken*/
    void 0,
    typeNode
  );
  const lastProp = getNodeToInsertPropertyAfter(node);
  if (lastProp) {
    changeTracker.insertNodeAfter(sourceFile, lastProp, property);
  } else {
    changeTracker.insertMemberAtStart(sourceFile, node, property);
  }
}
function getNodeToInsertPropertyAfter(node) {
  let res;
  for (const member of node.members) {
    if (!isPropertyDeclaration(member))
      break;
    res = member;
  }
  return res;
}
function createAddIndexSignatureAction(context, sourceFile, node, tokenName, typeNode) {
  const stringTypeNode = factory.createKeywordTypeNode(154 /* StringKeyword */);
  const indexingParameter = factory.createParameterDeclaration(
    /*modifiers*/
    void 0,
    /*dotDotDotToken*/
    void 0,
    "x",
    /*questionToken*/
    void 0,
    stringTypeNode,
    /*initializer*/
    void 0
  );
  const indexSignature = factory.createIndexSignature(
    /*modifiers*/
    void 0,
    [indexingParameter],
    typeNode
  );
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.insertMemberAtStart(sourceFile, node, indexSignature));
  return createCodeFixActionWithoutFixAll(fixMissingMember, changes, [Diagnostics.Add_index_signature_for_property_0, tokenName]);
}
function getActionsForMissingMethodDeclaration(context, info) {
  const { parentDeclaration, declSourceFile, modifierFlags, token, call } = info;
  if (call === void 0) {
    return void 0;
  }
  if (isPrivateIdentifier(token)) {
    return void 0;
  }
  const methodName = token.text;
  const addMethodDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile));
  const actions2 = [createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 32 /* Static */), [modifierFlags & 32 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixMissingMember, Diagnostics.Add_all_missing_members)];
  if (modifierFlags & 8 /* Private */) {
    actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(8 /* Private */), [Diagnostics.Declare_private_method_0, methodName]));
  }
  return actions2;
}
function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) {
  const importAdder = createImportAdder(sourceFile, context.program, context.preferences, context.host);
  const kind = isClassLike(parentDeclaration) ? 173 /* MethodDeclaration */ : 172 /* MethodSignature */;
  const signatureDeclaration = createSignatureDeclarationFromCallExpression(kind, context, importAdder, callExpression, name, modifierFlags, parentDeclaration);
  const containingMethodDeclaration = tryGetContainingMethodDeclaration(parentDeclaration, callExpression);
  if (containingMethodDeclaration) {
    changes.insertNodeAfter(sourceFile, containingMethodDeclaration, signatureDeclaration);
  } else {
    changes.insertMemberAtStart(sourceFile, parentDeclaration, signatureDeclaration);
  }
  importAdder.writeFixes(changes);
}
function addEnumMemberDeclaration(changes, checker, { token, parentDeclaration }) {
  const hasStringInitializer = some(parentDeclaration.members, (member) => {
    const type = checker.getTypeAtLocation(member);
    return !!(type && type.flags & 402653316 /* StringLike */);
  });
  const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : void 0);
  changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration(
    parentDeclaration,
    parentDeclaration.modifiers,
    parentDeclaration.name,
    concatenate(parentDeclaration.members, singleElementArray(enumMember))
  ), {
    leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll,
    trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude
  });
}
function addFunctionDeclaration(changes, context, info) {
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const functionDeclaration = info.kind === 2 /* Function */ ? createSignatureDeclarationFromCallExpression(261 /* FunctionDeclaration */, context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) : createSignatureDeclarationFromSignature(
    261 /* FunctionDeclaration */,
    context,
    quotePreference,
    info.signature,
    createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference),
    info.token,
    /*modifiers*/
    void 0,
    /*optional*/
    void 0,
    /*enclosingDeclaration*/
    void 0,
    importAdder
  );
  if (functionDeclaration === void 0) {
    Debug.fail("fixMissingFunctionDeclaration codefix got unexpected error.");
  }
  isReturnStatement(info.parentDeclaration) ? changes.insertNodeBefore(
    info.sourceFile,
    info.parentDeclaration,
    functionDeclaration,
    /*blankLineBetween*/
    true
  ) : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration);
  importAdder.writeFixes(changes);
}
function addJsxAttributes(changes, context, info) {
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const checker = context.program.getTypeChecker();
  const jsxAttributesNode = info.parentDeclaration.attributes;
  const hasSpreadAttribute = some(jsxAttributesNode.properties, isJsxSpreadAttribute);
  const attrs = map(info.attributes, (attr) => {
    const value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration);
    const name = factory.createIdentifier(attr.name);
    const jsxAttribute = factory.createJsxAttribute(name, factory.createJsxExpression(
      /*dotDotDotToken*/
      void 0,
      value
    ));
    setParent(name, jsxAttribute);
    return jsxAttribute;
  });
  const jsxAttributes = factory.createJsxAttributes(hasSpreadAttribute ? [...attrs, ...jsxAttributesNode.properties] : [...jsxAttributesNode.properties, ...attrs]);
  const options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : void 0 };
  changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options);
  importAdder.writeFixes(changes);
}
function addObjectLiteralProperties(changes, context, info) {
  const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host);
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const target = getEmitScriptTarget(context.program.getCompilerOptions());
  const checker = context.program.getTypeChecker();
  const props = map(info.properties, (prop) => {
    const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration);
    return factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer);
  });
  const options = {
    leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
    trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude,
    indentation: info.indentation
  };
  changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression(
    [...info.parentDeclaration.properties, ...props],
    /*multiLine*/
    true
  ), options);
  importAdder.writeFixes(changes);
}
function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) {
  if (type.flags & 3 /* AnyOrUnknown */) {
    return createUndefined();
  }
  if (type.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
    return factory.createStringLiteral(
      "",
      /* isSingleQuote */
      quotePreference === 0 /* Single */
    );
  }
  if (type.flags & 8 /* Number */) {
    return factory.createNumericLiteral(0);
  }
  if (type.flags & 64 /* BigInt */) {
    return factory.createBigIntLiteral("0n");
  }
  if (type.flags & 16 /* Boolean */) {
    return factory.createFalse();
  }
  if (type.flags & 1056 /* EnumLike */) {
    const enumMember = type.symbol.exports ? firstOrUndefinedIterator(type.symbol.exports.values()) : type.symbol;
    const name = checker.symbolToExpression(
      type.symbol.parent ? type.symbol.parent : type.symbol,
      111551 /* Value */,
      /*enclosingDeclaration*/
      void 0,
      /*flags*/
      void 0
    );
    return enumMember === void 0 || name === void 0 ? factory.createNumericLiteral(0) : factory.createPropertyAccessExpression(name, checker.symbolToString(enumMember));
  }
  if (type.flags & 256 /* NumberLiteral */) {
    return factory.createNumericLiteral(type.value);
  }
  if (type.flags & 2048 /* BigIntLiteral */) {
    return factory.createBigIntLiteral(type.value);
  }
  if (type.flags & 128 /* StringLiteral */) {
    return factory.createStringLiteral(
      type.value,
      /* isSingleQuote */
      quotePreference === 0 /* Single */
    );
  }
  if (type.flags & 512 /* BooleanLiteral */) {
    return type === checker.getFalseType() || type === checker.getFalseType(
      /*fresh*/
      true
    ) ? factory.createFalse() : factory.createTrue();
  }
  if (type.flags & 65536 /* Null */) {
    return factory.createNull();
  }
  if (type.flags & 1048576 /* Union */) {
    const expression = firstDefined(type.types, (t) => tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration));
    return expression ?? createUndefined();
  }
  if (checker.isArrayLikeType(type)) {
    return factory.createArrayLiteralExpression();
  }
  if (isObjectLiteralType(type)) {
    const props = map(checker.getPropertiesOfType(type), (prop) => {
      const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), enclosingDeclaration);
      return factory.createPropertyAssignment(prop.name, initializer);
    });
    return factory.createObjectLiteralExpression(
      props,
      /*multiLine*/
      true
    );
  }
  if (getObjectFlags(type) & 16 /* Anonymous */) {
    const decl = find(type.symbol.declarations || emptyArray, or(isFunctionTypeNode, isMethodSignature, isMethodDeclaration));
    if (decl === void 0)
      return createUndefined();
    const signature = checker.getSignaturesOfType(type, 0 /* Call */);
    if (signature === void 0)
      return createUndefined();
    const func = createSignatureDeclarationFromSignature(
      217 /* FunctionExpression */,
      context,
      quotePreference,
      signature[0],
      createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference),
      /*name*/
      void 0,
      /*modifiers*/
      void 0,
      /*optional*/
      void 0,
      /*enclosingDeclaration*/
      enclosingDeclaration,
      importAdder
    );
    return func ?? createUndefined();
  }
  if (getObjectFlags(type) & 1 /* Class */) {
    const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
    if (classDeclaration === void 0 || hasAbstractModifier(classDeclaration))
      return createUndefined();
    const constructorDeclaration = getFirstConstructorWithBody(classDeclaration);
    if (constructorDeclaration && length(constructorDeclaration.parameters))
      return createUndefined();
    return factory.createNewExpression(
      factory.createIdentifier(type.symbol.name),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      void 0
    );
  }
  return createUndefined();
}
function createUndefined() {
  return factory.createIdentifier("undefined");
}
function isObjectLiteralType(type) {
  return type.flags & 524288 /* Object */ && (getObjectFlags(type) & 128 /* ObjectLiteral */ || type.symbol && tryCast(singleOrUndefined(type.symbol.declarations), isTypeLiteralNode));
}
function getUnmatchedAttributes(checker, target, source) {
  const attrsType = checker.getContextualType(source.attributes);
  if (attrsType === void 0)
    return emptyArray;
  const targetProps = attrsType.getProperties();
  if (!length(targetProps))
    return emptyArray;
  const seenNames = /* @__PURE__ */ new Set();
  for (const sourceProp of source.attributes.properties) {
    if (isJsxAttribute(sourceProp)) {
      seenNames.add(getEscapedTextOfJsxAttributeName(sourceProp.name));
    }
    if (isJsxSpreadAttribute(sourceProp)) {
      const type = checker.getTypeAtLocation(sourceProp.expression);
      for (const prop of type.getProperties()) {
        seenNames.add(prop.escapedName);
      }
    }
  }
  return filter(targetProps, (targetProp) => isIdentifierText(targetProp.name, target, 1 /* JSX */) && !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */ || seenNames.has(targetProp.escapedName)));
}
function tryGetContainingMethodDeclaration(node, callExpression) {
  if (isTypeLiteralNode(node)) {
    return void 0;
  }
  const declaration = findAncestor(callExpression, (n) => isMethodDeclaration(n) || isConstructorDeclaration(n));
  return declaration && declaration.parent === node ? declaration : void 0;
}
function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) {
  if (isTransientSymbol(symbol)) {
    const prop = checker.symbolToNode(
      symbol,
      111551 /* Value */,
      /*enclosingDeclaration*/
      void 0,
      1073741824 /* WriteComputedProps */
    );
    if (prop && isComputedPropertyName(prop))
      return prop;
  }
  return createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* Single */);
}
function findScope(node) {
  if (findAncestor(node, isJsxExpression)) {
    const returnStatement = findAncestor(node.parent, isReturnStatement);
    if (returnStatement)
      return returnStatement;
  }
  return getSourceFileOfNode(node);
}

// src/services/codefixes/fixAddMissingNewOperator.ts
var fixId24 = "addMissingNewOperator";
var errorCodes28 = [Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
registerCodeFix({
  errorCodes: errorCodes28,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingNewOperator(t, sourceFile, span));
    return [createCodeFixAction(fixId24, changes, Diagnostics.Add_missing_new_operator_to_call, fixId24, Diagnostics.Add_missing_new_operator_to_all_calls)];
  },
  fixIds: [fixId24],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes28, (changes, diag2) => addMissingNewOperator(changes, context.sourceFile, diag2))
});
function addMissingNewOperator(changes, sourceFile, span) {
  const call = cast(findAncestorMatchingSpan2(sourceFile, span), isCallExpression);
  const newExpression = factory.createNewExpression(call.expression, call.typeArguments, call.arguments);
  changes.replaceNode(sourceFile, call, newExpression);
}
function findAncestorMatchingSpan2(sourceFile, span) {
  let token = getTokenAtPosition(sourceFile, span.start);
  const end = textSpanEnd(span);
  while (token.end < end) {
    token = token.parent;
  }
  return token;
}

// src/services/codefixes/fixCannotFindModule.ts
var fixName2 = "fixCannotFindModule";
var fixIdInstallTypesPackage = "installTypesPackage";
var errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code;
var errorCodes29 = [
  errorCodeCannotFindModule,
  Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code
];
registerCodeFix({
  errorCodes: errorCodes29,
  getCodeActions: function getCodeActionsToFixNotFoundModule(context) {
    const { host, sourceFile, span: { start: start2 } } = context;
    const packageName = tryGetImportedPackageName(sourceFile, start2);
    if (packageName === void 0)
      return void 0;
    const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode);
    return typesPackageName === void 0 ? [] : [createCodeFixAction(
      fixName2,
      /*changes*/
      [],
      [Diagnostics.Install_0, typesPackageName],
      fixIdInstallTypesPackage,
      Diagnostics.Install_all_missing_types_packages,
      getInstallCommand(sourceFile.fileName, typesPackageName)
    )];
  },
  fixIds: [fixIdInstallTypesPackage],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes29, (_changes, diag2, commands) => {
      const packageName = tryGetImportedPackageName(diag2.file, diag2.start);
      if (packageName === void 0)
        return void 0;
      switch (context.fixId) {
        case fixIdInstallTypesPackage: {
          const pkg = getTypesPackageNameToInstall(packageName, context.host, diag2.code);
          if (pkg) {
            commands.push(getInstallCommand(diag2.file.fileName, pkg));
          }
          break;
        }
        default:
          Debug.fail(`Bad fixId: ${context.fixId}`);
      }
    });
  }
});
function getInstallCommand(fileName, packageName) {
  return { type: "install package", file: fileName, packageName };
}
function tryGetImportedPackageName(sourceFile, pos) {
  const moduleSpecifierText = tryCast(getTokenAtPosition(sourceFile, pos), isStringLiteral);
  if (!moduleSpecifierText)
    return void 0;
  const moduleName = moduleSpecifierText.text;
  const { packageName } = parsePackageName(moduleName);
  return isExternalModuleNameRelative(packageName) ? void 0 : packageName;
}
function getTypesPackageNameToInstall(packageName, host, diagCode) {
  var _a;
  return diagCode === errorCodeCannotFindModule ? ts_JsTyping_exports.nodeCoreModules.has(packageName) ? "@types/node" : void 0 : ((_a = host.isKnownTypesPackageName) == null ? void 0 : _a.call(host, packageName)) ? getTypesPackageName(packageName) : void 0;
}

// src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts
var errorCodes30 = [
  Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1.code
];
var fixId25 = "fixClassDoesntImplementInheritedAbstractMember";
registerCodeFix({
  errorCodes: errorCodes30,
  getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) {
    const { sourceFile, span } = context;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences));
    return changes.length === 0 ? void 0 : [createCodeFixAction(fixId25, changes, Diagnostics.Implement_inherited_abstract_class, fixId25, Diagnostics.Implement_all_inherited_abstract_classes)];
  },
  fixIds: [fixId25],
  getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) {
    const seenClassDeclarations = /* @__PURE__ */ new Map();
    return codeFixAll(context, errorCodes30, (changes, diag2) => {
      const classDeclaration = getClass2(diag2.file, diag2.start);
      if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) {
        addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences);
      }
    });
  }
});
function getClass2(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  return cast(token.parent, isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) {
  const extendsNode = getEffectiveBaseTypeNode(classDeclaration);
  const checker = context.program.getTypeChecker();
  const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
  const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
  const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host);
  createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, (member) => changeTracker.insertMemberAtStart(sourceFile, classDeclaration, member));
  importAdder.writeFixes(changeTracker);
}
function symbolPointsToNonPrivateAndAbstractMember(symbol) {
  const flags = getSyntacticModifierFlags(first(symbol.getDeclarations()));
  return !(flags & 8 /* Private */) && !!(flags & 256 /* Abstract */);
}

// src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts
var fixId26 = "classSuperMustPrecedeThisAccess";
var errorCodes31 = [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code];
registerCodeFix({
  errorCodes: errorCodes31,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const nodes = getNodes(sourceFile, span.start);
    if (!nodes)
      return void 0;
    const { constructor, superCall } = nodes;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, sourceFile, constructor, superCall));
    return [createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)];
  },
  fixIds: [fixId26],
  getAllCodeActions(context) {
    const { sourceFile } = context;
    const seenClasses = /* @__PURE__ */ new Map();
    return codeFixAll(context, errorCodes31, (changes, diag2) => {
      const nodes = getNodes(diag2.file, diag2.start);
      if (!nodes)
        return;
      const { constructor, superCall } = nodes;
      if (addToSeen(seenClasses, getNodeId(constructor.parent))) {
        doChange19(changes, sourceFile, constructor, superCall);
      }
    });
  }
});
function doChange19(changes, sourceFile, constructor, superCall) {
  changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
  changes.delete(sourceFile, superCall);
}
function getNodes(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (token.kind !== 110 /* ThisKeyword */)
    return void 0;
  const constructor = getContainingFunction(token);
  const superCall = findSuperCall(constructor.body);
  return superCall && !superCall.expression.arguments.some((arg) => isPropertyAccessExpression(arg) && arg.expression === token) ? { constructor, superCall } : void 0;
}
function findSuperCall(n) {
  return isExpressionStatement(n) && isSuperCall(n.expression) ? n : isFunctionLike(n) ? void 0 : forEachChild(n, findSuperCall);
}

// src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts
var fixId27 = "constructorForDerivedNeedSuperCall";
var errorCodes32 = [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code];
registerCodeFix({
  errorCodes: errorCodes32,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const ctr = getNode(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, ctr));
    return [createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls)];
  },
  fixIds: [fixId27],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start)))
});
function getNode(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration");
  return token.parent;
}
function doChange20(changes, sourceFile, ctr) {
  const superCall = factory.createExpressionStatement(factory.createCallExpression(
    factory.createSuper(),
    /*typeArguments*/
    void 0,
    /*argumentsArray*/
    emptyArray
  ));
  changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall);
}

// src/services/codefixes/fixEnableJsxFlag.ts
var fixID = "fixEnableJsxFlag";
var errorCodes33 = [Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code];
registerCodeFix({
  errorCodes: errorCodes33,
  getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) {
    const { configFile } = context.program.getCompilerOptions();
    if (configFile === void 0) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(
      context,
      (changeTracker) => doChange21(changeTracker, configFile)
    );
    return [
      createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file)
    ];
  },
  fixIds: [fixID],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes33, (changes) => {
    const { configFile } = context.program.getCompilerOptions();
    if (configFile === void 0) {
      return void 0;
    }
    doChange21(changes, configFile);
  })
});
function doChange21(changeTracker, configFile) {
  setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react"));
}

// src/services/codefixes/fixNaNEquality.ts
var fixId28 = "fixNaNEquality";
var errorCodes34 = [
  Diagnostics.This_condition_will_always_return_0.code
];
registerCodeFix({
  errorCodes: errorCodes34,
  getCodeActions(context) {
    const { sourceFile, span, program } = context;
    const info = getInfo11(program, sourceFile, span);
    if (info === void 0)
      return;
    const { suggestion, expression, arg } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, sourceFile, arg, expression));
    return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)];
  },
  fixIds: [fixId28],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes34, (changes, diag2) => {
      const info = getInfo11(context.program, diag2.file, createTextSpan(diag2.start, diag2.length));
      if (info) {
        doChange22(changes, diag2.file, info.arg, info.expression);
      }
    });
  }
});
function getInfo11(program, sourceFile, span) {
  const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length);
  if (diag2 === void 0 || diag2.relatedInformation === void 0)
    return;
  const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.Did_you_mean_0.code);
  if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0)
    return;
  const token = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length));
  if (token === void 0)
    return;
  if (isExpression(token) && isBinaryExpression(token.parent)) {
    return { suggestion: getSuggestion(related.messageText), expression: token.parent, arg: token };
  }
  return void 0;
}
function doChange22(changes, sourceFile, arg, expression) {
  const callExpression = factory.createCallExpression(
    factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")),
    /*typeArguments*/
    void 0,
    [arg]
  );
  const operator = expression.operatorToken.kind;
  changes.replaceNode(
    sourceFile,
    expression,
    operator === 38 /* ExclamationEqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? factory.createPrefixUnaryExpression(54 /* ExclamationToken */, callExpression) : callExpression
  );
}
function getSuggestion(messageText) {
  const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || [];
  return suggestion;
}

// src/services/codefixes/fixModuleAndTargetOptions.ts
registerCodeFix({
  errorCodes: [
    Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code,
    Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code
  ],
  getCodeActions: function getCodeActionsToFixModuleAndTarget(context) {
    const compilerOptions = context.program.getCompilerOptions();
    const { configFile } = compilerOptions;
    if (configFile === void 0) {
      return void 0;
    }
    const codeFixes = [];
    const moduleKind = getEmitModuleKind(compilerOptions);
    const moduleOutOfRange = moduleKind >= 5 /* ES2015 */ && moduleKind < 99 /* ESNext */;
    if (moduleOutOfRange) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
        setJsonCompilerOptionValue(changes2, configFile, "module", factory.createStringLiteral("esnext"));
      });
      codeFixes.push(createCodeFixActionWithoutFixAll("fixModuleOption", changes, [Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"]));
    }
    const target = getEmitScriptTarget(compilerOptions);
    const targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */;
    if (targetOutOfRange) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => {
        const configObject = getTsConfigObjectLiteralExpression(configFile);
        if (!configObject)
          return;
        const options = [["target", factory.createStringLiteral("es2017")]];
        if (moduleKind === 1 /* CommonJS */) {
          options.push(["module", factory.createStringLiteral("commonjs")]);
        }
        setJsonCompilerOptionValues(tracker, configFile, options);
      });
      codeFixes.push(createCodeFixActionWithoutFixAll("fixTargetOption", changes, [Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"]));
    }
    return codeFixes.length ? codeFixes : void 0;
  }
});

// src/services/codefixes/fixPropertyAssignment.ts
var fixId29 = "fixPropertyAssignment";
var errorCodes35 = [
  Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code
];
registerCodeFix({
  errorCodes: errorCodes35,
  fixIds: [fixId29],
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const property = getProperty2(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, context.sourceFile, property));
    return [createCodeFixAction(fixId29, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId29, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start)))
});
function doChange23(changes, sourceFile, node) {
  changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer));
}
function getProperty2(sourceFile, pos) {
  return cast(getTokenAtPosition(sourceFile, pos).parent, isShorthandPropertyAssignment);
}

// src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts
var fixId30 = "extendsInterfaceBecomesImplements";
var errorCodes36 = [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
registerCodeFix({
  errorCodes: errorCodes36,
  getCodeActions(context) {
    const { sourceFile } = context;
    const nodes = getNodes2(sourceFile, context.span.start);
    if (!nodes)
      return void 0;
    const { extendsToken, heritageClauses } = nodes;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChanges2(t, sourceFile, extendsToken, heritageClauses));
    return [createCodeFixAction(fixId30, changes, Diagnostics.Change_extends_to_implements, fixId30, Diagnostics.Change_all_extended_interfaces_to_implements)];
  },
  fixIds: [fixId30],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes36, (changes, diag2) => {
    const nodes = getNodes2(diag2.file, diag2.start);
    if (nodes)
      doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses);
  })
});
function getNodes2(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const heritageClauses = getContainingClass(token).heritageClauses;
  const extendsToken = heritageClauses[0].getFirstToken();
  return extendsToken.kind === 96 /* ExtendsKeyword */ ? { extendsToken, heritageClauses } : void 0;
}
function doChanges2(changes, sourceFile, extendsToken, heritageClauses) {
  changes.replaceNode(sourceFile, extendsToken, factory.createToken(119 /* ImplementsKeyword */));
  if (heritageClauses.length === 2 && heritageClauses[0].token === 96 /* ExtendsKeyword */ && heritageClauses[1].token === 119 /* ImplementsKeyword */) {
    const implementsToken = heritageClauses[1].getFirstToken();
    const implementsFullStart = implementsToken.getFullStart();
    changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, factory.createToken(28 /* CommaToken */));
    const text = sourceFile.text;
    let end = implementsToken.end;
    while (end < text.length && isWhiteSpaceSingleLine(text.charCodeAt(end))) {
      end++;
    }
    changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end });
  }
}

// src/services/codefixes/fixForgottenThisPropertyAccess.ts
var fixId31 = "forgottenThisPropertyAccess";
var didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
var errorCodes37 = [
  Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
  Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code,
  didYouMeanStaticMemberCode
];
registerCodeFix({
  errorCodes: errorCodes37,
  getCodeActions(context) {
    const { sourceFile } = context;
    const info = getInfo12(sourceFile, context.span.start, context.errorCode);
    if (!info) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, sourceFile, info));
    return [createCodeFixAction(fixId31, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId31, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)];
  },
  fixIds: [fixId31],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => {
    const info = getInfo12(diag2.file, diag2.start, diag2.code);
    if (info)
      doChange24(changes, context.sourceFile, info);
  })
});
function getInfo12(sourceFile, pos, diagCode) {
  const node = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(node) || isPrivateIdentifier(node)) {
    return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 };
  }
}
function doChange24(changes, sourceFile, { node, className }) {
  suppressLeadingAndTrailingTrivia(node);
  changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node));
}

// src/services/codefixes/fixInvalidJsxCharacters.ts
var fixIdExpression = "fixInvalidJsxCharacters_expression";
var fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity";
var errorCodes38 = [
  Diagnostics.Unexpected_token_Did_you_mean_or_gt.code,
  Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code
];
registerCodeFix({
  errorCodes: errorCodes38,
  fixIds: [fixIdExpression, fixIdHtmlEntity],
  getCodeActions(context) {
    const { sourceFile, preferences, span } = context;
    const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25(
      t,
      preferences,
      sourceFile,
      span.start,
      /*useHtmlEntity*/
      false
    ));
    const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25(
      t,
      preferences,
      sourceFile,
      span.start,
      /*useHtmlEntity*/
      true
    ));
    return [
      createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container),
      createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code)
    ];
  },
  getAllCodeActions(context) {
    return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange25(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity));
  }
});
var htmlEntity = {
  ">": "&gt;",
  "}": "&rbrace;"
};
function isValidCharacter(character) {
  return hasProperty(htmlEntity, character);
}
function doChange25(changes, preferences, sourceFile, start2, useHtmlEntity) {
  const character = sourceFile.getText()[start2];
  if (!isValidCharacter(character)) {
    return;
  }
  const replacement = useHtmlEntity ? htmlEntity[character] : `{${quote(sourceFile, preferences, character)}}`;
  changes.replaceRangeWithText(sourceFile, { pos: start2, end: start2 + 1 }, replacement);
}

// src/services/codefixes/fixUnmatchedParameter.ts
var deleteUnmatchedParameter = "deleteUnmatchedParameter";
var renameUnmatchedParameter = "renameUnmatchedParameter";
var errorCodes39 = [
  Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code
];
registerCodeFix({
  fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter],
  errorCodes: errorCodes39,
  getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) {
    const { sourceFile, span } = context;
    const actions2 = [];
    const info = getInfo13(sourceFile, span.start);
    if (info) {
      append(actions2, getDeleteAction(context, info));
      append(actions2, getRenameAction(context, info));
      return actions2;
    }
    return void 0;
  },
  getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) {
    const tagsToSignature = /* @__PURE__ */ new Map();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes39, ({ file, start: start2 }) => {
        const info = getInfo13(file, start2);
        if (info) {
          tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag));
        }
      });
      tagsToSignature.forEach((tags, signature) => {
        if (context.fixId === deleteUnmatchedParameter) {
          const tagsSet = new Set(tags);
          changes.filterJSDocTags(signature.getSourceFile(), signature, (t) => !tagsSet.has(t));
        }
      });
    }));
  }
});
function getDeleteAction(context, { name, jsDocHost, jsDocParameterTag }) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, (t) => t !== jsDocParameterTag));
  return createCodeFixAction(
    deleteUnmatchedParameter,
    changes,
    [Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)],
    deleteUnmatchedParameter,
    Diagnostics.Delete_all_unused_param_tags
  );
}
function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) {
  if (!length(signature.parameters))
    return void 0;
  const sourceFile = context.sourceFile;
  const tags = getJSDocTags(signature);
  const names = /* @__PURE__ */ new Set();
  for (const tag of tags) {
    if (isJSDocParameterTag(tag) && isIdentifier(tag.name)) {
      names.add(tag.name.escapedText);
    }
  }
  const parameterName = firstDefined(signature.parameters, (p) => isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0);
  if (parameterName === void 0)
    return void 0;
  const newJSDocParameterTag = factory.updateJSDocParameterTag(
    jsDocParameterTag,
    jsDocParameterTag.tagName,
    factory.createIdentifier(parameterName),
    jsDocParameterTag.isBracketed,
    jsDocParameterTag.typeExpression,
    jsDocParameterTag.isNameFirst,
    jsDocParameterTag.comment
  );
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t)));
  return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]);
}
function getInfo13(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) {
    const jsDocParameterTag = token.parent;
    const jsDocHost = getJSDocHost(jsDocParameterTag);
    const signature = getHostSignatureFromJSDoc(jsDocParameterTag);
    if (jsDocHost && signature) {
      return { jsDocHost, signature, name: token.parent.name, jsDocParameterTag };
    }
  }
  return void 0;
}

// src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts
var fixId32 = "fixUnreferenceableDecoratorMetadata";
var errorCodes40 = [Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code];
registerCodeFix({
  errorCodes: errorCodes40,
  getCodeActions: (context) => {
    const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start);
    if (!importDeclaration)
      return;
    const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => importDeclaration.kind === 275 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program));
    const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program));
    let actions2;
    if (namespaceChanges.length) {
      actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import));
    }
    if (typeOnlyChanges.length) {
      actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, typeOnlyChanges, Diagnostics.Convert_to_type_only_import));
    }
    return actions2;
  },
  fixIds: [fixId32]
});
function getImportDeclaration(sourceFile, program, start2) {
  const identifier = tryCast(getTokenAtPosition(sourceFile, start2), isIdentifier);
  if (!identifier || identifier.parent.kind !== 182 /* TypeReference */)
    return;
  const checker = program.getTypeChecker();
  const symbol = checker.getSymbolAtLocation(identifier);
  return find((symbol == null ? void 0 : symbol.declarations) || emptyArray, or(isImportClause, isImportSpecifier, isImportEqualsDeclaration));
}
function doTypeOnlyImportChange(changes, sourceFile, importDeclaration, program) {
  if (importDeclaration.kind === 270 /* ImportEqualsDeclaration */) {
    changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, importDeclaration.name);
    return;
  }
  const importClause = importDeclaration.kind === 272 /* ImportClause */ ? importDeclaration : importDeclaration.parent.parent;
  if (importClause.name && importClause.namedBindings) {
    return;
  }
  const checker = program.getTypeChecker();
  const importsValue = !!forEachImportClauseDeclaration(importClause, (decl) => {
    if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */)
      return true;
  });
  if (importsValue) {
    return;
  }
  changes.insertModifierBefore(sourceFile, 156 /* TypeKeyword */, importClause);
}
function doNamespaceImportChange(changes, sourceFile, importDeclaration, program) {
  ts_refactor_exports.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent);
}

// src/services/codefixes/fixUnusedIdentifier.ts
var fixName3 = "unusedIdentifier";
var fixIdPrefix = "unusedIdentifier_prefix";
var fixIdDelete = "unusedIdentifier_delete";
var fixIdDeleteImports = "unusedIdentifier_deleteImports";
var fixIdInfer = "unusedIdentifier_infer";
var errorCodes41 = [
  Diagnostics._0_is_declared_but_its_value_is_never_read.code,
  Diagnostics._0_is_declared_but_never_used.code,
  Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
  Diagnostics.All_imports_in_import_declaration_are_unused.code,
  Diagnostics.All_destructured_elements_are_unused.code,
  Diagnostics.All_variables_are_unused.code,
  Diagnostics.All_type_parameters_are_unused.code
];
registerCodeFix({
  errorCodes: errorCodes41,
  getCodeActions(context) {
    const { errorCode, sourceFile, program, cancellationToken } = context;
    const checker = program.getTypeChecker();
    const sourceFiles = program.getSourceFiles();
    const token = getTokenAtPosition(sourceFile, context.span.start);
    if (isJSDocTemplateTag(token)) {
      return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => t.delete(sourceFile, token)), Diagnostics.Remove_template_tag)];
    }
    if (token.kind === 30 /* LessThanToken */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteTypeParameters(t, sourceFile, token));
      return [createDeleteFix(changes, Diagnostics.Remove_type_parameters)];
    }
    const importDecl = tryGetFullImport(token);
    if (importDecl) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.delete(sourceFile, importDecl));
      return [createCodeFixAction(fixName3, changes, [Diagnostics.Remove_import_from_0, showModuleSpecifier(importDecl)], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports)];
    } else if (isImport(token)) {
      const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryDeleteDeclaration(
        sourceFile,
        token,
        t,
        checker,
        sourceFiles,
        program,
        cancellationToken,
        /*isFixAll*/
        false
      ));
      if (deletion.length) {
        return [createCodeFixAction(fixName3, deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports)];
      }
    }
    if (isObjectBindingPattern(token.parent) || isArrayBindingPattern(token.parent)) {
      if (isParameter(token.parent.parent)) {
        const elements = token.parent.elements;
        const diagnostic = [
          elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0,
          map(elements, (e) => e.getText(sourceFile)).join(", ")
        ];
        return [
          createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteDestructuringElements(t, sourceFile, token.parent)), diagnostic)
        ];
      }
      return [
        createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteDestructuring(context, t, sourceFile, token.parent)), Diagnostics.Remove_unused_destructuring_declaration)
      ];
    }
    if (canDeleteEntireVariableStatement(sourceFile, token)) {
      return [
        createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteEntireVariableStatement(t, sourceFile, token.parent)), Diagnostics.Remove_variable_statement)
      ];
    }
    const result = [];
    if (token.kind === 140 /* InferKeyword */) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => changeInferToUnknown(t, sourceFile, token));
      const name = cast(token.parent, isInferTypeNode).typeParameter.name.text;
      result.push(createCodeFixAction(fixName3, changes, [Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, Diagnostics.Replace_all_unused_infer_with_unknown));
    } else {
      const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryDeleteDeclaration(
        sourceFile,
        token,
        t,
        checker,
        sourceFiles,
        program,
        cancellationToken,
        /*isFixAll*/
        false
      ));
      if (deletion.length) {
        const name = isComputedPropertyName(token.parent) ? token.parent : token;
        result.push(createDeleteFix(deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)]));
      }
    }
    const prefix = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryPrefixDeclaration(t, errorCode, sourceFile, token));
    if (prefix.length) {
      result.push(createCodeFixAction(fixName3, prefix, [Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, Diagnostics.Prefix_all_unused_declarations_with_where_possible));
    }
    return result;
  },
  fixIds: [fixIdPrefix, fixIdDelete, fixIdDeleteImports, fixIdInfer],
  getAllCodeActions: (context) => {
    const { sourceFile, program, cancellationToken } = context;
    const checker = program.getTypeChecker();
    const sourceFiles = program.getSourceFiles();
    return codeFixAll(context, errorCodes41, (changes, diag2) => {
      const token = getTokenAtPosition(sourceFile, diag2.start);
      switch (context.fixId) {
        case fixIdPrefix:
          tryPrefixDeclaration(changes, diag2.code, sourceFile, token);
          break;
        case fixIdDeleteImports: {
          const importDecl = tryGetFullImport(token);
          if (importDecl) {
            changes.delete(sourceFile, importDecl);
          } else if (isImport(token)) {
            tryDeleteDeclaration(
              sourceFile,
              token,
              changes,
              checker,
              sourceFiles,
              program,
              cancellationToken,
              /*isFixAll*/
              true
            );
          }
          break;
        }
        case fixIdDelete: {
          if (token.kind === 140 /* InferKeyword */ || isImport(token)) {
            break;
          } else if (isJSDocTemplateTag(token)) {
            changes.delete(sourceFile, token);
          } else if (token.kind === 30 /* LessThanToken */) {
            deleteTypeParameters(changes, sourceFile, token);
          } else if (isObjectBindingPattern(token.parent)) {
            if (token.parent.parent.initializer) {
              break;
            } else if (!isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) {
              changes.delete(sourceFile, token.parent.parent);
            }
          } else if (isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) {
            break;
          } else if (canDeleteEntireVariableStatement(sourceFile, token)) {
            deleteEntireVariableStatement(changes, sourceFile, token.parent);
          } else {
            tryDeleteDeclaration(
              sourceFile,
              token,
              changes,
              checker,
              sourceFiles,
              program,
              cancellationToken,
              /*isFixAll*/
              true
            );
          }
          break;
        }
        case fixIdInfer:
          if (token.kind === 140 /* InferKeyword */) {
            changeInferToUnknown(changes, sourceFile, token);
          }
          break;
        default:
          Debug.fail(JSON.stringify(context.fixId));
      }
    });
  }
});
function changeInferToUnknown(changes, sourceFile, token) {
  changes.replaceNode(sourceFile, token.parent, factory.createKeywordTypeNode(159 /* UnknownKeyword */));
}
function createDeleteFix(changes, diag2) {
  return createCodeFixAction(fixName3, changes, diag2, fixIdDelete, Diagnostics.Delete_all_unused_declarations);
}
function deleteTypeParameters(changes, sourceFile, token) {
  changes.delete(sourceFile, Debug.checkDefined(cast(token.parent, isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
}
function isImport(token) {
  return token.kind === 102 /* ImportKeyword */ || token.kind === 80 /* Identifier */ && (token.parent.kind === 275 /* ImportSpecifier */ || token.parent.kind === 272 /* ImportClause */);
}
function tryGetFullImport(token) {
  return token.kind === 102 /* ImportKeyword */ ? tryCast(token.parent, isImportDeclaration) : void 0;
}
function canDeleteEntireVariableStatement(sourceFile, token) {
  return isVariableDeclarationList(token.parent) && first(token.parent.getChildren(sourceFile)) === token;
}
function deleteEntireVariableStatement(changes, sourceFile, node) {
  changes.delete(sourceFile, node.parent.kind === 242 /* VariableStatement */ ? node.parent : node);
}
function deleteDestructuringElements(changes, sourceFile, node) {
  forEach(node.elements, (n) => changes.delete(sourceFile, n));
}
function deleteDestructuring(context, changes, sourceFile, { parent: parent2 }) {
  if (isVariableDeclaration(parent2) && parent2.initializer && isCallLikeExpression(parent2.initializer)) {
    if (isVariableDeclarationList(parent2.parent) && length(parent2.parent.declarations) > 1) {
      const varStatement = parent2.parent.parent;
      const pos = varStatement.getStart(sourceFile);
      const end = varStatement.end;
      changes.delete(sourceFile, parent2);
      changes.insertNodeAt(sourceFile, end, parent2.initializer, {
        prefix: getNewLineOrDefaultFromHost(context.host, context.formatContext.options) + sourceFile.text.slice(getPrecedingNonSpaceCharacterPosition(sourceFile.text, pos - 1), pos),
        suffix: probablyUsesSemicolons(sourceFile) ? ";" : ""
      });
    } else {
      changes.replaceNode(sourceFile, parent2.parent, parent2.initializer);
    }
  } else {
    changes.delete(sourceFile, parent2);
  }
}
function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
  if (errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code)
    return;
  if (token.kind === 140 /* InferKeyword */) {
    token = cast(token.parent, isInferTypeNode).typeParameter.name;
  }
  if (isIdentifier(token) && canPrefix(token)) {
    changes.replaceNode(sourceFile, token, factory.createIdentifier(`_${token.text}`));
    if (isParameter(token.parent)) {
      getJSDocParameterTags(token.parent).forEach((tag) => {
        if (isIdentifier(tag.name)) {
          changes.replaceNode(sourceFile, tag.name, factory.createIdentifier(`_${tag.name.text}`));
        }
      });
    }
  }
}
function canPrefix(token) {
  switch (token.parent.kind) {
    case 168 /* Parameter */:
    case 167 /* TypeParameter */:
      return true;
    case 259 /* VariableDeclaration */: {
      const varDecl = token.parent;
      switch (varDecl.parent.parent.kind) {
        case 249 /* ForOfStatement */:
        case 248 /* ForInStatement */:
          return true;
      }
    }
  }
  return false;
}
function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, isFixAll) {
  tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll);
  if (isIdentifier(token)) {
    ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref) => {
      if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref)
        ref = ref.parent;
      if (!isFixAll && mayDeleteExpression(ref)) {
        changes.delete(sourceFile, ref.parent.parent);
      }
    });
  }
}
function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll) {
  const { parent: parent2 } = token;
  if (isParameter(parent2)) {
    tryDeleteParameter(changes, sourceFile, parent2, checker, sourceFiles, program, cancellationToken, isFixAll);
  } else if (!(isFixAll && isIdentifier(token) && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(token, checker, sourceFile))) {
    const node = isImportClause(parent2) ? token : isComputedPropertyName(parent2) ? parent2.parent : parent2;
    Debug.assert(node !== sourceFile, "should not delete whole source file");
    changes.delete(sourceFile, node);
  }
}
function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll = false) {
  if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) {
    if (parameter.modifiers && parameter.modifiers.length > 0 && (!isIdentifier(parameter.name) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) {
      for (const modifier of parameter.modifiers) {
        if (isModifier(modifier)) {
          changes.deleteModifier(sourceFile, modifier);
        }
      }
    } else if (!parameter.initializer && isNotProvidedArguments(parameter, checker, sourceFiles)) {
      changes.delete(sourceFile, parameter);
    }
  }
}
function isNotProvidedArguments(parameter, checker, sourceFiles) {
  const index = parameter.parent.parameters.indexOf(parameter);
  return !ts_FindAllReferences_exports.Core.someSignatureUsage(parameter.parent, sourceFiles, checker, (_, call) => !call || call.arguments.length > index);
}
function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) {
  const { parent: parent2 } = parameter;
  switch (parent2.kind) {
    case 173 /* MethodDeclaration */:
    case 175 /* Constructor */:
      const index = parent2.parameters.indexOf(parameter);
      const referent = isMethodDeclaration(parent2) ? parent2.name : parent2;
      const entries = ts_FindAllReferences_exports.Core.getReferencedSymbolsForNode(parent2.pos, referent, program, sourceFiles, cancellationToken);
      if (entries) {
        for (const entry of entries) {
          for (const reference of entry.references) {
            if (reference.kind === ts_FindAllReferences_exports.EntryKind.Node) {
              const isSuperCall2 = isSuperKeyword(reference.node) && isCallExpression(reference.node.parent) && reference.node.parent.arguments.length > index;
              const isSuperMethodCall = isPropertyAccessExpression(reference.node.parent) && isSuperKeyword(reference.node.parent.expression) && isCallExpression(reference.node.parent.parent) && reference.node.parent.parent.arguments.length > index;
              const isOverriddenMethod = (isMethodDeclaration(reference.node.parent) || isMethodSignature(reference.node.parent)) && reference.node.parent !== parameter.parent && reference.node.parent.parameters.length > index;
              if (isSuperCall2 || isSuperMethodCall || isOverriddenMethod)
                return false;
            }
          }
        }
      }
      return true;
    case 261 /* FunctionDeclaration */: {
      if (parent2.name && isCallbackLike(checker, sourceFile, parent2.name)) {
        return isLastParameter(parent2, parameter, isFixAll);
      }
      return true;
    }
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
      return isLastParameter(parent2, parameter, isFixAll);
    case 177 /* SetAccessor */:
      return false;
    case 176 /* GetAccessor */:
      return true;
    default:
      return Debug.failBadSyntaxKind(parent2);
  }
}
function isCallbackLike(checker, sourceFile, name) {
  return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference) => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0);
}
function isLastParameter(func, parameter, isFixAll) {
  const parameters = func.parameters;
  const index = parameters.indexOf(parameter);
  Debug.assert(index !== -1, "The parameter should already be in the list");
  return isFixAll ? parameters.slice(index + 1).every((p) => isIdentifier(p.name) && !p.symbol.isReferenced) : index === parameters.length - 1;
}
function mayDeleteExpression(node) {
  return (isBinaryExpression(node.parent) && node.parent.left === node || (isPostfixUnaryExpression(node.parent) || isPrefixUnaryExpression(node.parent)) && node.parent.operand === node) && isExpressionStatement(node.parent.parent);
}

// src/services/codefixes/fixUnreachableCode.ts
var fixId33 = "fixUnreachableCode";
var errorCodes42 = [Diagnostics.Unreachable_code_detected.code];
registerCodeFix({
  errorCodes: errorCodes42,
  getCodeActions(context) {
    const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken);
    if (syntacticDiagnostics.length)
      return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode));
    return [createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code)];
  },
  fixIds: [fixId33],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code))
});
function doChange26(changes, sourceFile, start2, length2, errorCode) {
  const token = getTokenAtPosition(sourceFile, start2);
  const statement = findAncestor(token, isStatement);
  if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) {
    const logData = JSON.stringify({
      statementKind: Debug.formatSyntaxKind(statement.kind),
      tokenKind: Debug.formatSyntaxKind(token.kind),
      errorCode,
      start: start2,
      length: length2
    });
    Debug.fail("Token and statement should start at the same point. " + logData);
  }
  const container = (isBlock(statement.parent) ? statement.parent : statement).parent;
  if (!isBlock(statement.parent) || statement === first(statement.parent.statements)) {
    switch (container.kind) {
      case 244 /* IfStatement */:
        if (container.elseStatement) {
          if (isBlock(statement.parent)) {
            break;
          } else {
            changes.replaceNode(sourceFile, statement, factory.createBlock(emptyArray));
          }
          return;
        }
      case 246 /* WhileStatement */:
      case 247 /* ForStatement */:
        changes.delete(sourceFile, container);
        return;
    }
  }
  if (isBlock(statement.parent)) {
    const end = start2 + length2;
    const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), (s) => s.pos < end), "Some statement should be last");
    changes.deleteNodeRange(sourceFile, statement, lastStatement);
  } else {
    changes.delete(sourceFile, statement);
  }
}
function lastWhere(a, pred) {
  let last2;
  for (const value of a) {
    if (!pred(value))
      break;
    last2 = value;
  }
  return last2;
}

// src/services/codefixes/fixUnusedLabel.ts
var fixId34 = "fixUnusedLabel";
var errorCodes43 = [Diagnostics.Unused_label.code];
registerCodeFix({
  errorCodes: errorCodes43,
  getCodeActions(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start));
    return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels)];
  },
  fixIds: [fixId34],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start))
});
function doChange27(changes, sourceFile, start2) {
  const token = getTokenAtPosition(sourceFile, start2);
  const labeledStatement = cast(token.parent, isLabeledStatement);
  const pos = token.getStart(sourceFile);
  const statementPos = labeledStatement.statement.getStart(sourceFile);
  const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos : skipTrivia(
    sourceFile.text,
    findChildOfKind(labeledStatement, 59 /* ColonToken */, sourceFile).end,
    /*stopAfterLineBreak*/
    true
  );
  changes.deleteRange(sourceFile, { pos, end });
}

// src/services/codefixes/fixJSDocTypes.ts
var fixIdPlain = "fixJSDocTypes_plain";
var fixIdNullable = "fixJSDocTypes_nullable";
var errorCodes44 = [
  Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code,
  Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code,
  Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code
];
registerCodeFix({
  errorCodes: errorCodes44,
  getCodeActions(context) {
    const { sourceFile } = context;
    const checker = context.program.getTypeChecker();
    const info = getInfo14(sourceFile, context.span.start, checker);
    if (!info)
      return void 0;
    const { typeNode, type } = info;
    const original = typeNode.getText(sourceFile);
    const actions2 = [fix(type, fixIdPlain, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
    if (typeNode.kind === 320 /* JSDocNullableType */) {
      actions2.push(fix(type, fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
    }
    return actions2;
    function fix(type2, fixId52, fixAllDescription) {
      const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, typeNode, type2, checker));
      return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId52, fixAllDescription);
    }
  },
  fixIds: [fixIdPlain, fixIdNullable],
  getAllCodeActions(context) {
    const { fixId: fixId52, program, sourceFile } = context;
    const checker = program.getTypeChecker();
    return codeFixAll(context, errorCodes44, (changes, err) => {
      const info = getInfo14(err.file, err.start, checker);
      if (!info)
        return;
      const { typeNode, type } = info;
      const fixedType = typeNode.kind === 320 /* JSDocNullableType */ && fixId52 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
      doChange28(changes, sourceFile, typeNode, fixedType, checker);
    });
  }
});
function doChange28(changes, sourceFile, oldTypeNode, newType, checker) {
  changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(
    newType,
    /*enclosingDeclaration*/
    oldTypeNode,
    /*flags*/
    void 0
  ));
}
function getInfo14(sourceFile, pos, checker) {
  const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer);
  const typeNode = decl && decl.type;
  return typeNode && { typeNode, type: getType(checker, typeNode) };
}
function isTypeContainer(node) {
  switch (node.kind) {
    case 233 /* AsExpression */:
    case 178 /* CallSignature */:
    case 179 /* ConstructSignature */:
    case 261 /* FunctionDeclaration */:
    case 176 /* GetAccessor */:
    case 180 /* IndexSignature */:
    case 199 /* MappedType */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 168 /* Parameter */:
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
    case 177 /* SetAccessor */:
    case 264 /* TypeAliasDeclaration */:
    case 215 /* TypeAssertionExpression */:
    case 259 /* VariableDeclaration */:
      return true;
    default:
      return false;
  }
}
function getType(checker, node) {
  if (isJSDocNullableType(node)) {
    const type = checker.getTypeFromTypeNode(node.type);
    if (type === checker.getNeverType() || type === checker.getVoidType()) {
      return type;
    }
    return checker.getUnionType(
      append([type, checker.getUndefinedType()], node.postfix ? void 0 : checker.getNullType())
    );
  }
  return checker.getTypeFromTypeNode(node);
}

// src/services/codefixes/fixMissingCallParentheses.ts
var fixId35 = "fixMissingCallParentheses";
var errorCodes45 = [
  Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code
];
registerCodeFix({
  errorCodes: errorCodes45,
  fixIds: [fixId35],
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const callName = getCallName(sourceFile, span.start);
    if (!callName)
      return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, context.sourceFile, callName));
    return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => {
    const callName = getCallName(diag2.file, diag2.start);
    if (callName)
      doChange29(changes, diag2.file, callName);
  })
});
function doChange29(changes, sourceFile, name) {
  changes.replaceNodeWithText(sourceFile, name, `${name.text}()`);
}
function getCallName(sourceFile, start2) {
  const token = getTokenAtPosition(sourceFile, start2);
  if (isPropertyAccessExpression(token.parent)) {
    let current = token.parent;
    while (isPropertyAccessExpression(current.parent)) {
      current = current.parent;
    }
    return current.name;
  }
  if (isIdentifier(token)) {
    return token;
  }
  return void 0;
}

// src/services/codefixes/fixAwaitInSyncFunction.ts
var fixId36 = "fixAwaitInSyncFunction";
var errorCodes46 = [
  Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
  Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
  Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code
];
registerCodeFix({
  errorCodes: errorCodes46,
  getCodeActions(context) {
    const { sourceFile, span } = context;
    const nodes = getNodes3(sourceFile, span.start);
    if (!nodes)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, nodes));
    return [createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers)];
  },
  fixIds: [fixId36],
  getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) {
    const seen = /* @__PURE__ */ new Map();
    return codeFixAll(context, errorCodes46, (changes, diag2) => {
      const nodes = getNodes3(diag2.file, diag2.start);
      if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore)))
        return;
      doChange30(changes, context.sourceFile, nodes);
    });
  }
});
function getReturnType(expr) {
  if (expr.type) {
    return expr.type;
  }
  if (isVariableDeclaration(expr.parent) && expr.parent.type && isFunctionTypeNode(expr.parent.type)) {
    return expr.parent.type.type;
  }
}
function getNodes3(sourceFile, start2) {
  const token = getTokenAtPosition(sourceFile, start2);
  const containingFunction = getContainingFunction(token);
  if (!containingFunction) {
    return;
  }
  let insertBefore;
  switch (containingFunction.kind) {
    case 173 /* MethodDeclaration */:
      insertBefore = containingFunction.name;
      break;
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
      insertBefore = findChildOfKind(containingFunction, 100 /* FunctionKeyword */, sourceFile);
      break;
    case 218 /* ArrowFunction */:
      const kind = containingFunction.typeParameters ? 30 /* LessThanToken */ : 21 /* OpenParenToken */;
      insertBefore = findChildOfKind(containingFunction, kind, sourceFile) || first(containingFunction.parameters);
      break;
    default:
      return;
  }
  return insertBefore && {
    insertBefore,
    returnType: getReturnType(containingFunction)
  };
}
function doChange30(changes, sourceFile, { insertBefore, returnType }) {
  if (returnType) {
    const entityName = getEntityNameFromTypeNode(returnType);
    if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") {
      changes.replaceNode(sourceFile, returnType, factory.createTypeReferenceNode("Promise", factory.createNodeArray([returnType])));
    }
  }
  changes.insertModifierBefore(sourceFile, 134 /* AsyncKeyword */, insertBefore);
}

// src/services/codefixes/fixPropertyOverrideAccessor.ts
var errorCodes47 = [
  Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code,
  Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code
];
var fixId37 = "fixPropertyOverrideAccessor";
registerCodeFix({
  errorCodes: errorCodes47,
  getCodeActions(context) {
    const edits = doChange31(context.sourceFile, context.span.start, context.span.length, context.errorCode, context);
    if (edits) {
      return [createCodeFixAction(fixId37, edits, Diagnostics.Generate_get_and_set_accessors, fixId37, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)];
    }
  },
  fixIds: [fixId37],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => {
    const edits = doChange31(diag2.file, diag2.start, diag2.length, diag2.code, context);
    if (edits) {
      for (const edit of edits) {
        changes.pushRaw(context.sourceFile, edit);
      }
    }
  })
});
function doChange31(file, start2, length2, code, context) {
  let startPosition;
  let endPosition;
  if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) {
    startPosition = start2;
    endPosition = start2 + length2;
  } else if (code === Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code) {
    const checker = context.program.getTypeChecker();
    const node = getTokenAtPosition(file, start2).parent;
    Debug.assert(isAccessor(node), "error span of fixPropertyOverrideAccessor should only be on an accessor");
    const containingClass = node.parent;
    Debug.assert(isClassLike(containingClass), "erroneous accessors should only be inside classes");
    const base = singleOrUndefined(getAllSupers(containingClass, checker));
    if (!base)
      return [];
    const name = unescapeLeadingUnderscores(getTextOfPropertyName(node.name));
    const baseProp = checker.getPropertyOfType(checker.getTypeAtLocation(base), name);
    if (!baseProp || !baseProp.valueDeclaration)
      return [];
    startPosition = baseProp.valueDeclaration.pos;
    endPosition = baseProp.valueDeclaration.end;
    file = getSourceFileOfNode(baseProp.valueDeclaration);
  } else {
    Debug.fail("fixPropertyOverrideAccessor codefix got unexpected error code " + code);
  }
  return generateAccessorFromProperty(file, context.program, startPosition, endPosition, context, Diagnostics.Generate_get_and_set_accessors.message);
}

// src/services/codefixes/inferFromUsage.ts
var fixId38 = "inferFromUsage";
var errorCodes48 = [
  // Variable declarations
  Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
  // Variable uses
  Diagnostics.Variable_0_implicitly_has_an_1_type.code,
  // Parameter declarations
  Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
  Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
  // Get Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
  Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
  // Set Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
  // Property declarations
  Diagnostics.Member_0_implicitly_has_an_1_type.code,
  //// Suggestions
  // Variable declarations
  Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code,
  // Variable uses
  Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Parameter declarations
  Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Get Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code,
  Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Set Accessor declarations
  Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code,
  // Property declarations
  Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
  // Function expressions and declarations
  Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code
];
registerCodeFix({
  errorCodes: errorCodes48,
  getCodeActions(context) {
    const { sourceFile, program, span: { start: start2 }, errorCode, cancellationToken, host, preferences } = context;
    const token = getTokenAtPosition(sourceFile, start2);
    let declaration;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => {
      declaration = doChange32(
        changes2,
        sourceFile,
        token,
        errorCode,
        program,
        cancellationToken,
        /*markSeen*/
        returnTrue,
        host,
        preferences
      );
    });
    const name = declaration && getNameOfDeclaration(declaration);
    return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId38, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId38, Diagnostics.Infer_all_types_from_usage)];
  },
  fixIds: [fixId38],
  getAllCodeActions(context) {
    const { sourceFile, program, cancellationToken, host, preferences } = context;
    const markSeen = nodeSeenTracker();
    return codeFixAll(context, errorCodes48, (changes, err) => {
      doChange32(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences);
    });
  }
});
function getDiagnostic(errorCode, token) {
  switch (errorCode) {
    case Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
    case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return isSetAccessorDeclaration(getContainingFunction(token)) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage;
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Infer_parameter_types_from_usage;
    case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
      return Diagnostics.Infer_this_type_of_0_from_usage;
    default:
      return Diagnostics.Infer_type_of_0_from_usage;
  }
}
function mapSuggestionDiagnostic(errorCode) {
  switch (errorCode) {
    case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code;
    case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Variable_0_implicitly_has_an_1_type.code;
    case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Parameter_0_implicitly_has_an_1_type.code;
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code;
    case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code:
      return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code;
    case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code;
    case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code:
      return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code;
    case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
      return Diagnostics.Member_0_implicitly_has_an_1_type.code;
  }
  return errorCode;
}
function doChange32(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) {
  if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */) {
    return void 0;
  }
  const { parent: parent2 } = token;
  const importAdder = createImportAdder(sourceFile, program, preferences, host);
  errorCode = mapSuggestionDiagnostic(errorCode);
  switch (errorCode) {
    case Diagnostics.Member_0_implicitly_has_an_1_type.code:
    case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
      if (isVariableDeclaration(parent2) && markSeen(parent2) || isPropertyDeclaration(parent2) || isPropertySignature(parent2)) {
        annotateVariableDeclaration(changes, importAdder, sourceFile, parent2, program, host, cancellationToken);
        importAdder.writeFixes(changes);
        return parent2;
      }
      if (isPropertyAccessExpression(parent2)) {
        const type = inferTypeForVariableFromUsage(parent2.name, program, cancellationToken);
        const typeNode = getTypeNodeIfAccessible(type, parent2, program, host);
        if (typeNode) {
          const typeTag = factory.createJSDocTypeTag(
            /*tagName*/
            void 0,
            factory.createJSDocTypeExpression(typeNode),
            /*comment*/
            void 0
          );
          changes.addJSDocTags(sourceFile, cast(parent2.parent.parent, isExpressionStatement), [typeTag]);
        }
        importAdder.writeFixes(changes);
        return parent2;
      }
      return void 0;
    case Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
      const symbol = program.getTypeChecker().getSymbolAtLocation(token);
      if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
        annotateVariableDeclaration(changes, importAdder, getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken);
        importAdder.writeFixes(changes);
        return symbol.valueDeclaration;
      }
      return void 0;
    }
  }
  const containingFunction = getContainingFunction(token);
  if (containingFunction === void 0) {
    return void 0;
  }
  let declaration;
  switch (errorCode) {
    case Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
      if (isSetAccessorDeclaration(containingFunction)) {
        annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
        declaration = containingFunction;
        break;
      }
    case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
      if (markSeen(containingFunction)) {
        const param = cast(parent2, isParameter);
        annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken);
        declaration = param;
      }
      break;
    case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
    case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
      if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) {
        annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host);
        declaration = containingFunction;
      }
      break;
    case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
      if (isSetAccessorDeclaration(containingFunction)) {
        annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
        declaration = containingFunction;
      }
      break;
    case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
      if (ts_textChanges_exports.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) {
        annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken);
        declaration = containingFunction;
      }
      break;
    default:
      return Debug.fail(String(errorCode));
  }
  importAdder.writeFixes(changes);
  return declaration;
}
function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) {
  if (isIdentifier(declaration.name)) {
    annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host);
  }
}
function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) {
  if (!isIdentifier(parameterDeclaration.name)) {
    return;
  }
  const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken);
  Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match");
  if (isInJSFile(containingFunction)) {
    annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host);
  } else {
    const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 21 /* OpenParenToken */, sourceFile);
    if (needParens)
      changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */));
    for (const { declaration, type } of parameterInferences) {
      if (declaration && !declaration.type && !declaration.initializer) {
        annotate(changes, importAdder, sourceFile, declaration, type, program, host);
      }
    }
    if (needParens)
      changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(22 /* CloseParenToken */));
  }
}
function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) {
  const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken);
  if (!references || !references.length) {
    return;
  }
  const thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter();
  const typeNode = getTypeNodeIfAccessible(thisInference, containingFunction, program, host);
  if (!typeNode) {
    return;
  }
  if (isInJSFile(containingFunction)) {
    annotateJSDocThis(changes, sourceFile, containingFunction, typeNode);
  } else {
    changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode);
  }
}
function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) {
  changes.addJSDocTags(sourceFile, containingFunction, [
    factory.createJSDocThisTag(
      /*tagName*/
      void 0,
      factory.createJSDocTypeExpression(typeNode)
    )
  ]);
}
function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) {
  const param = firstOrUndefined(setAccessorDeclaration.parameters);
  if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) {
    let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken);
    if (type === program.getTypeChecker().getAnyType()) {
      type = inferTypeForVariableFromUsage(param.name, program, cancellationToken);
    }
    if (isInJSFile(setAccessorDeclaration)) {
      annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host);
    } else {
      annotate(changes, importAdder, sourceFile, param, type, program, host);
    }
  }
}
function annotate(changes, importAdder, sourceFile, declaration, type, program, host) {
  const typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
  if (typeNode) {
    if (isInJSFile(sourceFile) && declaration.kind !== 170 /* PropertySignature */) {
      const parent2 = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration;
      if (!parent2) {
        return;
      }
      const typeExpression = factory.createJSDocTypeExpression(typeNode);
      const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(
        /*tagName*/
        void 0,
        typeExpression,
        /*comment*/
        void 0
      ) : factory.createJSDocTypeTag(
        /*tagName*/
        void 0,
        typeExpression,
        /*comment*/
        void 0
      );
      changes.addJSDocTags(sourceFile, parent2, [typeTag]);
    } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) {
      changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
    }
  }
}
function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, scriptTarget) {
  const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
  if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) {
    forEach(importableReference.symbols, (s) => importAdder.addImportFromExportedSymbol(
      s,
      /*isValidTypeOnlyUseSite*/
      true
    ));
    return true;
  }
  return false;
}
function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) {
  const signature = parameterInferences.length && parameterInferences[0].declaration.parent;
  if (!signature) {
    return;
  }
  const inferences = mapDefined(parameterInferences, (inference) => {
    const param = inference.declaration;
    if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) {
      return;
    }
    const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
    if (typeNode) {
      const name = factory.cloneNode(param.name);
      setEmitFlags(name, 3072 /* NoComments */ | 4096 /* NoNestedComments */);
      return { name: factory.cloneNode(param.name), param, isOptional: !!inference.isOptional, typeNode };
    }
  });
  if (!inferences.length) {
    return;
  }
  if (isArrowFunction(signature) || isFunctionExpression(signature)) {
    const needParens = isArrowFunction(signature) && !findChildOfKind(signature, 21 /* OpenParenToken */, sourceFile);
    if (needParens) {
      changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(21 /* OpenParenToken */));
    }
    forEach(inferences, ({ typeNode, param }) => {
      const typeTag = factory.createJSDocTypeTag(
        /*tagName*/
        void 0,
        factory.createJSDocTypeExpression(typeNode)
      );
      const jsDoc = factory.createJSDocComment(
        /*comment*/
        void 0,
        [typeTag]
      );
      changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { suffix: " " });
    });
    if (needParens) {
      changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(22 /* CloseParenToken */));
    }
  } else {
    const paramTags = map(inferences, ({ name, typeNode, isOptional }) => factory.createJSDocParameterTag(
      /*tagName*/
      void 0,
      name,
      /*isBracketed*/
      !!isOptional,
      factory.createJSDocTypeExpression(typeNode),
      /*isNameFirst*/
      false,
      /*comment*/
      void 0
    ));
    changes.addJSDocTags(sourceFile, signature, paramTags);
  }
}
function getReferences(token, program, cancellationToken) {
  return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), (entry) => entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0);
}
function inferTypeForVariableFromUsage(token, program, cancellationToken) {
  const references = getReferences(token, program, cancellationToken);
  return inferTypeFromReferences(program, references, cancellationToken).single();
}
function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) {
  const references = getFunctionReferences(func, sourceFile, program, cancellationToken);
  return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map((p) => ({
    declaration: p,
    type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType()
  }));
}
function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) {
  let searchToken;
  switch (containingFunction.kind) {
    case 175 /* Constructor */:
      searchToken = findChildOfKind(containingFunction, 137 /* ConstructorKeyword */, sourceFile);
      break;
    case 218 /* ArrowFunction */:
    case 217 /* FunctionExpression */:
      const parent2 = containingFunction.parent;
      searchToken = (isVariableDeclaration(parent2) || isPropertyDeclaration(parent2)) && isIdentifier(parent2.name) ? parent2.name : containingFunction.name;
      break;
    case 261 /* FunctionDeclaration */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
      searchToken = containingFunction.name;
      break;
  }
  if (!searchToken) {
    return void 0;
  }
  return getReferences(searchToken, program, cancellationToken);
}
function inferTypeFromReferences(program, references, cancellationToken) {
  const checker = program.getTypeChecker();
  const builtinConstructors = {
    string: () => checker.getStringType(),
    number: () => checker.getNumberType(),
    Array: (t) => checker.createArrayType(t),
    Promise: (t) => checker.createPromiseType(t)
  };
  const builtins = [
    checker.getStringType(),
    checker.getNumberType(),
    checker.createArrayType(checker.getAnyType()),
    checker.createPromiseType(checker.getAnyType())
  ];
  return {
    single: single2,
    parameters,
    thisParameter
  };
  function createEmptyUsage() {
    return {
      isNumber: void 0,
      isString: void 0,
      isNumberOrString: void 0,
      candidateTypes: void 0,
      properties: void 0,
      calls: void 0,
      constructs: void 0,
      numberIndex: void 0,
      stringIndex: void 0,
      candidateThisTypes: void 0,
      inferredTypes: void 0
    };
  }
  function combineUsages(usages) {
    const combinedProperties = /* @__PURE__ */ new Map();
    for (const u of usages) {
      if (u.properties) {
        u.properties.forEach((p, name) => {
          if (!combinedProperties.has(name)) {
            combinedProperties.set(name, []);
          }
          combinedProperties.get(name).push(p);
        });
      }
    }
    const properties = /* @__PURE__ */ new Map();
    combinedProperties.forEach((ps, name) => {
      properties.set(name, combineUsages(ps));
    });
    return {
      isNumber: usages.some((u) => u.isNumber),
      isString: usages.some((u) => u.isString),
      isNumberOrString: usages.some((u) => u.isNumberOrString),
      candidateTypes: flatMap(usages, (u) => u.candidateTypes),
      properties,
      calls: flatMap(usages, (u) => u.calls),
      constructs: flatMap(usages, (u) => u.constructs),
      numberIndex: forEach(usages, (u) => u.numberIndex),
      stringIndex: forEach(usages, (u) => u.stringIndex),
      candidateThisTypes: flatMap(usages, (u) => u.candidateThisTypes),
      inferredTypes: void 0
      // clear type cache
    };
  }
  function single2() {
    return combineTypes(inferTypesFromReferencesSingle(references));
  }
  function parameters(declaration) {
    if (references.length === 0 || !declaration.parameters) {
      return void 0;
    }
    const usage = createEmptyUsage();
    for (const reference of references) {
      cancellationToken.throwIfCancellationRequested();
      calculateUsageOfNode(reference, usage);
    }
    const calls = [...usage.constructs || [], ...usage.calls || []];
    return declaration.parameters.map((parameter, parameterIndex) => {
      const types = [];
      const isRest = isRestParameter(parameter);
      let isOptional = false;
      for (const call of calls) {
        if (call.argumentTypes.length <= parameterIndex) {
          isOptional = isInJSFile(declaration);
          types.push(checker.getUndefinedType());
        } else if (isRest) {
          for (let i = parameterIndex; i < call.argumentTypes.length; i++) {
            types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i]));
          }
        } else {
          types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex]));
        }
      }
      if (isIdentifier(parameter.name)) {
        const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken));
        types.push(...isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred);
      }
      const type = combineTypes(types);
      return {
        type: isRest ? checker.createArrayType(type) : type,
        isOptional: isOptional && !isRest,
        declaration: parameter
      };
    });
  }
  function thisParameter() {
    const usage = createEmptyUsage();
    for (const reference of references) {
      cancellationToken.throwIfCancellationRequested();
      calculateUsageOfNode(reference, usage);
    }
    return combineTypes(usage.candidateThisTypes || emptyArray);
  }
  function inferTypesFromReferencesSingle(references2) {
    const usage = createEmptyUsage();
    for (const reference of references2) {
      cancellationToken.throwIfCancellationRequested();
      calculateUsageOfNode(reference, usage);
    }
    return inferTypes(usage);
  }
  function calculateUsageOfNode(node, usage) {
    while (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
      node = node.parent;
    }
    switch (node.parent.kind) {
      case 243 /* ExpressionStatement */:
        inferTypeFromExpressionStatement(node, usage);
        break;
      case 224 /* PostfixUnaryExpression */:
        usage.isNumber = true;
        break;
      case 223 /* PrefixUnaryExpression */:
        inferTypeFromPrefixUnaryExpression(node.parent, usage);
        break;
      case 225 /* BinaryExpression */:
        inferTypeFromBinaryExpression(node, node.parent, usage);
        break;
      case 295 /* CaseClause */:
      case 296 /* DefaultClause */:
        inferTypeFromSwitchStatementLabel(node.parent, usage);
        break;
      case 212 /* CallExpression */:
      case 213 /* NewExpression */:
        if (node.parent.expression === node) {
          inferTypeFromCallExpression(node.parent, usage);
        } else {
          inferTypeFromContextualType(node, usage);
        }
        break;
      case 210 /* PropertyAccessExpression */:
        inferTypeFromPropertyAccessExpression(node.parent, usage);
        break;
      case 211 /* ElementAccessExpression */:
        inferTypeFromPropertyElementExpression(node.parent, node, usage);
        break;
      case 302 /* PropertyAssignment */:
      case 303 /* ShorthandPropertyAssignment */:
        inferTypeFromPropertyAssignment(node.parent, usage);
        break;
      case 171 /* PropertyDeclaration */:
        inferTypeFromPropertyDeclaration(node.parent, usage);
        break;
      case 259 /* VariableDeclaration */: {
        const { name, initializer } = node.parent;
        if (node === name) {
          if (initializer) {
            addCandidateType(usage, checker.getTypeAtLocation(initializer));
          }
          break;
        }
      }
      default:
        return inferTypeFromContextualType(node, usage);
    }
  }
  function inferTypeFromContextualType(node, usage) {
    if (isExpressionNode(node)) {
      addCandidateType(usage, checker.getContextualType(node));
    }
  }
  function inferTypeFromExpressionStatement(node, usage) {
    addCandidateType(usage, isCallExpression(node) ? checker.getVoidType() : checker.getAnyType());
  }
  function inferTypeFromPrefixUnaryExpression(node, usage) {
    switch (node.operator) {
      case 46 /* PlusPlusToken */:
      case 47 /* MinusMinusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
        usage.isNumber = true;
        break;
      case 40 /* PlusToken */:
        usage.isNumberOrString = true;
        break;
    }
  }
  function inferTypeFromBinaryExpression(node, parent2, usage) {
    switch (parent2.operatorToken.kind) {
      case 43 /* AsteriskAsteriskToken */:
      case 42 /* AsteriskToken */:
      case 44 /* SlashToken */:
      case 45 /* PercentToken */:
      case 48 /* LessThanLessThanToken */:
      case 49 /* GreaterThanGreaterThanToken */:
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
      case 51 /* AmpersandToken */:
      case 52 /* BarToken */:
      case 53 /* CaretToken */:
      case 66 /* MinusEqualsToken */:
      case 68 /* AsteriskAsteriskEqualsToken */:
      case 67 /* AsteriskEqualsToken */:
      case 69 /* SlashEqualsToken */:
      case 70 /* PercentEqualsToken */:
      case 74 /* AmpersandEqualsToken */:
      case 75 /* BarEqualsToken */:
      case 79 /* CaretEqualsToken */:
      case 71 /* LessThanLessThanEqualsToken */:
      case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      case 72 /* GreaterThanGreaterThanEqualsToken */:
      case 41 /* MinusToken */:
      case 30 /* LessThanToken */:
      case 33 /* LessThanEqualsToken */:
      case 32 /* GreaterThanToken */:
      case 34 /* GreaterThanEqualsToken */:
        const operandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left);
        if (operandType.flags & 1056 /* EnumLike */) {
          addCandidateType(usage, operandType);
        } else {
          usage.isNumber = true;
        }
        break;
      case 65 /* PlusEqualsToken */:
      case 40 /* PlusToken */:
        const otherOperandType = checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left);
        if (otherOperandType.flags & 1056 /* EnumLike */) {
          addCandidateType(usage, otherOperandType);
        } else if (otherOperandType.flags & 296 /* NumberLike */) {
          usage.isNumber = true;
        } else if (otherOperandType.flags & 402653316 /* StringLike */) {
          usage.isString = true;
        } else if (otherOperandType.flags & 1 /* Any */) {
        } else {
          usage.isNumberOrString = true;
        }
        break;
      case 64 /* EqualsToken */:
      case 35 /* EqualsEqualsToken */:
      case 37 /* EqualsEqualsEqualsToken */:
      case 38 /* ExclamationEqualsEqualsToken */:
      case 36 /* ExclamationEqualsToken */:
      case 77 /* AmpersandAmpersandEqualsToken */:
      case 78 /* QuestionQuestionEqualsToken */:
      case 76 /* BarBarEqualsToken */:
        addCandidateType(usage, checker.getTypeAtLocation(parent2.left === node ? parent2.right : parent2.left));
        break;
      case 103 /* InKeyword */:
        if (node === parent2.left) {
          usage.isString = true;
        }
        break;
      case 57 /* BarBarToken */:
      case 61 /* QuestionQuestionToken */:
        if (node === parent2.left && (node.parent.parent.kind === 259 /* VariableDeclaration */ || isAssignmentExpression(
          node.parent.parent,
          /*excludeCompoundAssignment*/
          true
        ))) {
          addCandidateType(usage, checker.getTypeAtLocation(parent2.right));
        }
        break;
      case 56 /* AmpersandAmpersandToken */:
      case 28 /* CommaToken */:
      case 104 /* InstanceOfKeyword */:
        break;
    }
  }
  function inferTypeFromSwitchStatementLabel(parent2, usage) {
    addCandidateType(usage, checker.getTypeAtLocation(parent2.parent.parent.expression));
  }
  function inferTypeFromCallExpression(parent2, usage) {
    const call = {
      argumentTypes: [],
      return_: createEmptyUsage()
    };
    if (parent2.arguments) {
      for (const argument of parent2.arguments) {
        call.argumentTypes.push(checker.getTypeAtLocation(argument));
      }
    }
    calculateUsageOfNode(parent2, call.return_);
    if (parent2.kind === 212 /* CallExpression */) {
      (usage.calls || (usage.calls = [])).push(call);
    } else {
      (usage.constructs || (usage.constructs = [])).push(call);
    }
  }
  function inferTypeFromPropertyAccessExpression(parent2, usage) {
    const name = escapeLeadingUnderscores(parent2.name.text);
    if (!usage.properties) {
      usage.properties = /* @__PURE__ */ new Map();
    }
    const propertyUsage = usage.properties.get(name) || createEmptyUsage();
    calculateUsageOfNode(parent2, propertyUsage);
    usage.properties.set(name, propertyUsage);
  }
  function inferTypeFromPropertyElementExpression(parent2, node, usage) {
    if (node === parent2.argumentExpression) {
      usage.isNumberOrString = true;
      return;
    } else {
      const indexType = checker.getTypeAtLocation(parent2.argumentExpression);
      const indexUsage = createEmptyUsage();
      calculateUsageOfNode(parent2, indexUsage);
      if (indexType.flags & 296 /* NumberLike */) {
        usage.numberIndex = indexUsage;
      } else {
        usage.stringIndex = indexUsage;
      }
    }
  }
  function inferTypeFromPropertyAssignment(assignment, usage) {
    const nodeWithRealType = isVariableDeclaration(assignment.parent.parent) ? assignment.parent.parent : assignment.parent;
    addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType));
  }
  function inferTypeFromPropertyDeclaration(declaration, usage) {
    addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent));
  }
  function removeLowPriorityInferences(inferences, priorities) {
    const toRemove = [];
    for (const i of inferences) {
      for (const { high, low } of priorities) {
        if (high(i)) {
          Debug.assert(!low(i), "Priority can't have both low and high");
          toRemove.push(low);
        }
      }
    }
    return inferences.filter((i) => toRemove.every((f) => !f(i)));
  }
  function combineFromUsage(usage) {
    return combineTypes(inferTypes(usage));
  }
  function combineTypes(inferences) {
    if (!inferences.length)
      return checker.getAnyType();
    const stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
    const priorities = [
      {
        high: (t) => t === checker.getStringType() || t === checker.getNumberType(),
        low: (t) => t === stringNumber
      },
      {
        high: (t) => !(t.flags & (1 /* Any */ | 16384 /* Void */)),
        low: (t) => !!(t.flags & (1 /* Any */ | 16384 /* Void */))
      },
      {
        high: (t) => !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(getObjectFlags(t) & 16 /* Anonymous */),
        low: (t) => !!(getObjectFlags(t) & 16 /* Anonymous */)
      }
    ];
    let good = removeLowPriorityInferences(inferences, priorities);
    const anons = good.filter((i) => getObjectFlags(i) & 16 /* Anonymous */);
    if (anons.length) {
      good = good.filter((i) => !(getObjectFlags(i) & 16 /* Anonymous */));
      good.push(combineAnonymousTypes(anons));
    }
    return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */));
  }
  function combineAnonymousTypes(anons) {
    if (anons.length === 1) {
      return anons[0];
    }
    const calls = [];
    const constructs = [];
    const stringIndices = [];
    const numberIndices = [];
    let stringIndexReadonly = false;
    let numberIndexReadonly = false;
    const props = createMultiMap();
    for (const anon2 of anons) {
      for (const p of checker.getPropertiesOfType(anon2)) {
        props.add(p.escapedName, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType());
      }
      calls.push(...checker.getSignaturesOfType(anon2, 0 /* Call */));
      constructs.push(...checker.getSignaturesOfType(anon2, 1 /* Construct */));
      const stringIndexInfo = checker.getIndexInfoOfType(anon2, 0 /* String */);
      if (stringIndexInfo) {
        stringIndices.push(stringIndexInfo.type);
        stringIndexReadonly = stringIndexReadonly || stringIndexInfo.isReadonly;
      }
      const numberIndexInfo = checker.getIndexInfoOfType(anon2, 1 /* Number */);
      if (numberIndexInfo) {
        numberIndices.push(numberIndexInfo.type);
        numberIndexReadonly = numberIndexReadonly || numberIndexInfo.isReadonly;
      }
    }
    const members = mapEntries(props, (name, types) => {
      const isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0;
      const s = checker.createSymbol(4 /* Property */ | isOptional, name);
      s.links.type = checker.getUnionType(types);
      return [name, s];
    });
    const indexInfos = [];
    if (stringIndices.length)
      indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly));
    if (numberIndices.length)
      indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly));
    return checker.createAnonymousType(
      anons[0].symbol,
      members,
      calls,
      constructs,
      indexInfos
    );
  }
  function inferTypes(usage) {
    var _a, _b, _c;
    const types = [];
    if (usage.isNumber) {
      types.push(checker.getNumberType());
    }
    if (usage.isString) {
      types.push(checker.getStringType());
    }
    if (usage.isNumberOrString) {
      types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
    }
    if (usage.numberIndex) {
      types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
    }
    if (((_a = usage.properties) == null ? void 0 : _a.size) || ((_b = usage.constructs) == null ? void 0 : _b.length) || usage.stringIndex) {
      types.push(inferStructuralType(usage));
    }
    const candidateTypes = (usage.candidateTypes || []).map((t) => checker.getBaseTypeOfLiteralType(t));
    const callsType = ((_c = usage.calls) == null ? void 0 : _c.length) ? inferStructuralType(usage) : void 0;
    if (callsType && candidateTypes) {
      types.push(checker.getUnionType([callsType, ...candidateTypes], 2 /* Subtype */));
    } else {
      if (callsType) {
        types.push(callsType);
      }
      if (length(candidateTypes)) {
        types.push(...candidateTypes);
      }
    }
    types.push(...inferNamedTypesFromProperties(usage));
    return types;
  }
  function inferStructuralType(usage) {
    const members = /* @__PURE__ */ new Map();
    if (usage.properties) {
      usage.properties.forEach((u, name) => {
        const symbol = checker.createSymbol(4 /* Property */, name);
        symbol.links.type = combineFromUsage(u);
        members.set(name, symbol);
      });
    }
    const callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : [];
    const constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : [];
    const indexInfos = usage.stringIndex ? [checker.createIndexInfo(
      checker.getStringType(),
      combineFromUsage(usage.stringIndex),
      /*isReadonly*/
      false
    )] : [];
    return checker.createAnonymousType(
      /*symbol*/
      void 0,
      members,
      callSignatures,
      constructSignatures,
      indexInfos
    );
  }
  function inferNamedTypesFromProperties(usage) {
    if (!usage.properties || !usage.properties.size)
      return [];
    const types = builtins.filter((t) => allPropertiesAreAssignableToUsage(t, usage));
    if (0 < types.length && types.length < 3) {
      return types.map((t) => inferInstantiationFromUsage(t, usage));
    }
    return [];
  }
  function allPropertiesAreAssignableToUsage(type, usage) {
    if (!usage.properties)
      return false;
    return !forEachEntry(usage.properties, (propUsage, name) => {
      const source = checker.getTypeOfPropertyOfType(type, name);
      if (!source) {
        return true;
      }
      if (propUsage.calls) {
        const sigs = checker.getSignaturesOfType(source, 0 /* Call */);
        return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls));
      } else {
        return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage));
      }
    });
  }
  function inferInstantiationFromUsage(type, usage) {
    if (!(getObjectFlags(type) & 4 /* Reference */) || !usage.properties) {
      return type;
    }
    const generic = type.target;
    const singleTypeParameter = singleOrUndefined(generic.typeParameters);
    if (!singleTypeParameter)
      return type;
    const types = [];
    usage.properties.forEach((propUsage, name) => {
      const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name);
      Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
      types.push(...inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter));
    });
    return builtinConstructors[type.symbol.escapedName](combineTypes(types));
  }
  function inferTypeParameters(genericType, usageType, typeParameter) {
    if (genericType === typeParameter) {
      return [usageType];
    } else if (genericType.flags & 3145728 /* UnionOrIntersection */) {
      return flatMap(genericType.types, (t) => inferTypeParameters(t, usageType, typeParameter));
    } else if (getObjectFlags(genericType) & 4 /* Reference */ && getObjectFlags(usageType) & 4 /* Reference */) {
      const genericArgs = checker.getTypeArguments(genericType);
      const usageArgs = checker.getTypeArguments(usageType);
      const types = [];
      if (genericArgs && usageArgs) {
        for (let i = 0; i < genericArgs.length; i++) {
          if (usageArgs[i]) {
            types.push(...inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter));
          }
        }
      }
      return types;
    }
    const genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */);
    const usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */);
    if (genericSigs.length === 1 && usageSigs.length === 1) {
      return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter);
    }
    return [];
  }
  function inferFromSignatures(genericSig, usageSig, typeParameter) {
    var _a;
    const types = [];
    for (let i = 0; i < genericSig.parameters.length; i++) {
      const genericParam = genericSig.parameters[i];
      const usageParam = usageSig.parameters[i];
      const isRest = genericSig.declaration && isRestParameter(genericSig.declaration.parameters[i]);
      if (!usageParam) {
        break;
      }
      let genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType();
      const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType);
      if (elementType) {
        genericParamType = elementType;
      }
      const targetType = ((_a = tryCast(usageParam, isTransientSymbol)) == null ? void 0 : _a.links.type) || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType());
      types.push(...inferTypeParameters(genericParamType, targetType, typeParameter));
    }
    const genericReturn = checker.getReturnTypeOfSignature(genericSig);
    const usageReturn = checker.getReturnTypeOfSignature(usageSig);
    types.push(...inferTypeParameters(genericReturn, usageReturn, typeParameter));
    return types;
  }
  function getFunctionFromCalls(calls) {
    return checker.createAnonymousType(
      /*symbol*/
      void 0,
      createSymbolTable(),
      [getSignatureFromCalls(calls)],
      emptyArray,
      emptyArray
    );
  }
  function getSignatureFromCalls(calls) {
    const parameters2 = [];
    const length2 = Math.max(...calls.map((c) => c.argumentTypes.length));
    for (let i = 0; i < length2; i++) {
      const symbol = checker.createSymbol(1 /* FunctionScopedVariable */, escapeLeadingUnderscores(`arg${i}`));
      symbol.links.type = combineTypes(calls.map((call) => call.argumentTypes[i] || checker.getUndefinedType()));
      if (calls.some((call) => call.argumentTypes[i] === void 0)) {
        symbol.flags |= 16777216 /* Optional */;
      }
      parameters2.push(symbol);
    }
    const returnType = combineFromUsage(combineUsages(calls.map((call) => call.return_)));
    return checker.createSignature(
      /*declaration*/
      void 0,
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      parameters2,
      returnType,
      /*typePredicate*/
      void 0,
      length2,
      0 /* None */
    );
  }
  function addCandidateType(usage, type) {
    if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
      (usage.candidateTypes || (usage.candidateTypes = [])).push(type);
    }
  }
  function addCandidateThisType(usage, type) {
    if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
      (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type);
    }
  }
}

// src/services/codefixes/fixReturnTypeInAsyncFunction.ts
var fixId39 = "fixReturnTypeInAsyncFunction";
var errorCodes49 = [
  Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code
];
registerCodeFix({
  errorCodes: errorCodes49,
  fixIds: [fixId39],
  getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) {
    const { sourceFile, program, span } = context;
    const checker = program.getTypeChecker();
    const info = getInfo15(sourceFile, program.getTypeChecker(), span.start);
    if (!info) {
      return void 0;
    }
    const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, returnTypeNode, promisedTypeNode));
    return [createCodeFixAction(
      fixId39,
      changes,
      [
        Diagnostics.Replace_0_with_Promise_1,
        checker.typeToString(returnType),
        checker.typeToString(promisedType)
      ],
      fixId39,
      Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions
    )];
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => {
    const info = getInfo15(diag2.file, context.program.getTypeChecker(), diag2.start);
    if (info) {
      doChange33(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode);
    }
  })
});
function getInfo15(sourceFile, checker, pos) {
  if (isInJSFile(sourceFile)) {
    return void 0;
  }
  const token = getTokenAtPosition(sourceFile, pos);
  const func = findAncestor(token, isFunctionLikeDeclaration);
  const returnTypeNode = func == null ? void 0 : func.type;
  if (!returnTypeNode) {
    return void 0;
  }
  const returnType = checker.getTypeFromTypeNode(returnTypeNode);
  const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType();
  const promisedTypeNode = checker.typeToTypeNode(
    promisedType,
    /*enclosingDeclaration*/
    returnTypeNode,
    /*flags*/
    void 0
  );
  if (promisedTypeNode) {
    return { returnTypeNode, returnType, promisedTypeNode, promisedType };
  }
}
function doChange33(changes, sourceFile, returnTypeNode, promisedTypeNode) {
  changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [promisedTypeNode]));
}

// src/services/codefixes/disableJsDiagnostics.ts
var fixName4 = "disableJsDiagnostics";
var fixId40 = "disableJsDiagnostics";
var errorCodes50 = mapDefined(Object.keys(Diagnostics), (key) => {
  const diag2 = Diagnostics[key];
  return diag2.category === 1 /* Error */ ? diag2.code : void 0;
});
registerCodeFix({
  errorCodes: errorCodes50,
  getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) {
    const { sourceFile, program, span, host, formatContext } = context;
    if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
      return void 0;
    }
    const newLineCharacter = sourceFile.checkJsDirective ? "" : getNewLineOrDefaultFromHost(host, formatContext.options);
    const fixes = [
      // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
      createCodeFixActionWithoutFixAll(
        fixName4,
        [createFileTextChanges(sourceFile.fileName, [
          createTextChange(sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`)
        ])],
        Diagnostics.Disable_checking_for_this_file
      )
    ];
    if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) {
      fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId40, Diagnostics.Add_ts_ignore_to_all_error_messages));
    }
    return fixes;
  },
  fixIds: [fixId40],
  getAllCodeActions: (context) => {
    const seenLines = /* @__PURE__ */ new Set();
    return codeFixAll(context, errorCodes50, (changes, diag2) => {
      if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) {
        makeChange8(changes, diag2.file, diag2.start, seenLines);
      }
    });
  }
});
function makeChange8(changes, sourceFile, position, seenLines) {
  const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position);
  if (!seenLines || tryAddToSet(seenLines, lineNumber)) {
    changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
  }
}

// src/services/codefixes/helpers.ts
function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, sourceFile, context, preferences, importAdder, addClassElement) {
  const classMembers = classDeclaration.symbol.members;
  for (const symbol of possiblyMissingSymbols) {
    if (!classMembers.has(symbol.escapedName)) {
      addNewNodeForMemberSymbol(
        symbol,
        classDeclaration,
        sourceFile,
        context,
        preferences,
        importAdder,
        addClassElement,
        /*body*/
        void 0
      );
    }
  }
}
function getNoopSymbolTrackerWithResolver(context) {
  return {
    trackSymbol: () => false,
    moduleResolverHost: getModuleSpecifierResolverHost(context.program, context.host)
  };
}
var PreserveOptionalFlags = /* @__PURE__ */ ((PreserveOptionalFlags2) => {
  PreserveOptionalFlags2[PreserveOptionalFlags2["Method"] = 1] = "Method";
  PreserveOptionalFlags2[PreserveOptionalFlags2["Property"] = 2] = "Property";
  PreserveOptionalFlags2[PreserveOptionalFlags2["All"] = 3] = "All";
  return PreserveOptionalFlags2;
})(PreserveOptionalFlags || {});
function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */, isAmbient = false) {
  const declarations = symbol.getDeclarations();
  const declaration = declarations == null ? void 0 : declarations[0];
  const checker = context.program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
  const kind = (declaration == null ? void 0 : declaration.kind) ?? 170 /* PropertySignature */;
  const declarationName = getSynthesizedDeepClone(
    getNameOfDeclaration(declaration),
    /*includeTrivia*/
    false
  );
  const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */;
  let modifierFlags = effectiveModifierFlags & 4 /* Public */ ? 4 /* Public */ : effectiveModifierFlags & 16 /* Protected */ ? 16 /* Protected */ : 0 /* None */;
  if (declaration && isAutoAccessorPropertyDeclaration(declaration)) {
    modifierFlags |= 128 /* Accessor */;
  }
  const modifiers = createModifiers();
  const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
  const optional = !!(symbol.flags & 16777216 /* Optional */);
  const ambient = !!(enclosingDeclaration.flags & 16777216 /* Ambient */) || isAmbient;
  const quotePreference = getQuotePreference(sourceFile, preferences);
  switch (kind) {
    case 170 /* PropertySignature */:
    case 171 /* PropertyDeclaration */:
      const flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : void 0;
      let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context));
      if (importAdder) {
        const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
        if (importableReference) {
          typeNode = importableReference.typeNode;
          importSymbols(importAdder, importableReference.symbols);
        }
      }
      addClassElement(factory.createPropertyDeclaration(
        modifiers,
        declaration ? createName(declarationName) : symbol.getName(),
        optional && preserveOptional & 2 /* Property */ ? factory.createToken(58 /* QuestionToken */) : void 0,
        typeNode,
        /*initializer*/
        void 0
      ));
      break;
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */: {
      Debug.assertIsDefined(declarations);
      let typeNode2 = checker.typeToTypeNode(
        type,
        enclosingDeclaration,
        /*flags*/
        void 0,
        getNoopSymbolTrackerWithResolver(context)
      );
      const allAccessors = getAllAccessorDeclarations(declarations, declaration);
      const orderedAccessors = allAccessors.secondAccessor ? [allAccessors.firstAccessor, allAccessors.secondAccessor] : [allAccessors.firstAccessor];
      if (importAdder) {
        const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode2, scriptTarget);
        if (importableReference) {
          typeNode2 = importableReference.typeNode;
          importSymbols(importAdder, importableReference.symbols);
        }
      }
      for (const accessor of orderedAccessors) {
        if (isGetAccessorDeclaration(accessor)) {
          addClassElement(factory.createGetAccessorDeclaration(
            modifiers,
            createName(declarationName),
            emptyArray,
            createTypeNode(typeNode2),
            createBody(body, quotePreference, ambient)
          ));
        } else {
          Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter");
          const parameter = getSetAccessorValueParameter(accessor);
          const parameterName = parameter && isIdentifier(parameter.name) ? idText(parameter.name) : void 0;
          addClassElement(factory.createSetAccessorDeclaration(
            modifiers,
            createName(declarationName),
            createDummyParameters(
              1,
              [parameterName],
              [createTypeNode(typeNode2)],
              1,
              /*inJs*/
              false
            ),
            createBody(body, quotePreference, ambient)
          ));
        }
      }
      break;
    }
    case 172 /* MethodSignature */:
    case 173 /* MethodDeclaration */:
      Debug.assertIsDefined(declarations);
      const signatures = type.isUnion() ? flatMap(type.types, (t) => t.getCallSignatures()) : type.getCallSignatures();
      if (!some(signatures)) {
        break;
      }
      if (declarations.length === 1) {
        Debug.assert(signatures.length === 1, "One declaration implies one signature");
        const signature = signatures[0];
        outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference, ambient));
        break;
      }
      for (const signature of signatures) {
        outputMethod(quotePreference, signature, modifiers, createName(declarationName));
      }
      if (!ambient) {
        if (declarations.length > signatures.length) {
          const signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
          outputMethod(quotePreference, signature, modifiers, createName(declarationName), createBody(body, quotePreference));
        } else {
          Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count");
          addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, createName(declarationName), optional && !!(preserveOptional & 1 /* Method */), modifiers, quotePreference, body));
        }
      }
      break;
  }
  function outputMethod(quotePreference2, signature, modifiers2, name, body2) {
    const method = createSignatureDeclarationFromSignature(173 /* MethodDeclaration */, context, quotePreference2, signature, body2, name, modifiers2, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder);
    if (method)
      addClassElement(method);
  }
  function createModifiers() {
    let modifiers2;
    if (modifierFlags) {
      modifiers2 = combine(modifiers2, factory.createModifiersFromModifierFlags(modifierFlags));
    }
    if (shouldAddOverrideKeyword()) {
      modifiers2 = append(modifiers2, factory.createToken(163 /* OverrideKeyword */));
    }
    return modifiers2 && factory.createNodeArray(modifiers2);
  }
  function shouldAddOverrideKeyword() {
    return !!(context.program.getCompilerOptions().noImplicitOverride && declaration && hasAbstractModifier(declaration));
  }
  function createName(node) {
    if (isIdentifier(node) && node.escapedText === "constructor") {
      return factory.createComputedPropertyName(factory.createStringLiteral(idText(node), quotePreference === 0 /* Single */));
    }
    return getSynthesizedDeepClone(
      node,
      /*includeTrivia*/
      false
    );
  }
  function createBody(block, quotePreference2, ambient2) {
    return ambient2 ? void 0 : getSynthesizedDeepClone(
      block,
      /*includeTrivia*/
      false
    ) || createStubbedMethodBody(quotePreference2);
  }
  function createTypeNode(typeNode) {
    return getSynthesizedDeepClone(
      typeNode,
      /*includeTrivia*/
      false
    );
  }
}
function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) {
  const program = context.program;
  const checker = program.getTypeChecker();
  const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
  const isJs = isInJSFile(enclosingDeclaration);
  const flags = 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */ | 524288 /* AllowEmptyTuple */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */);
  const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context));
  if (!signatureDeclaration) {
    return void 0;
  }
  let typeParameters = isJs ? void 0 : signatureDeclaration.typeParameters;
  let parameters = signatureDeclaration.parameters;
  let type = isJs ? void 0 : signatureDeclaration.type;
  if (importAdder) {
    if (typeParameters) {
      const newTypeParameters = sameMap(typeParameters, (typeParameterDecl) => {
        let constraint = typeParameterDecl.constraint;
        let defaultType = typeParameterDecl.default;
        if (constraint) {
          const importableReference = tryGetAutoImportableReferenceFromTypeNode(constraint, scriptTarget);
          if (importableReference) {
            constraint = importableReference.typeNode;
            importSymbols(importAdder, importableReference.symbols);
          }
        }
        if (defaultType) {
          const importableReference = tryGetAutoImportableReferenceFromTypeNode(defaultType, scriptTarget);
          if (importableReference) {
            defaultType = importableReference.typeNode;
            importSymbols(importAdder, importableReference.symbols);
          }
        }
        return factory.updateTypeParameterDeclaration(
          typeParameterDecl,
          typeParameterDecl.modifiers,
          typeParameterDecl.name,
          constraint,
          defaultType
        );
      });
      if (typeParameters !== newTypeParameters) {
        typeParameters = setTextRange(factory.createNodeArray(newTypeParameters, typeParameters.hasTrailingComma), typeParameters);
      }
    }
    const newParameters = sameMap(parameters, (parameterDecl) => {
      let type2 = isJs ? void 0 : parameterDecl.type;
      if (type2) {
        const importableReference = tryGetAutoImportableReferenceFromTypeNode(type2, scriptTarget);
        if (importableReference) {
          type2 = importableReference.typeNode;
          importSymbols(importAdder, importableReference.symbols);
        }
      }
      return factory.updateParameterDeclaration(
        parameterDecl,
        parameterDecl.modifiers,
        parameterDecl.dotDotDotToken,
        parameterDecl.name,
        isJs ? void 0 : parameterDecl.questionToken,
        type2,
        parameterDecl.initializer
      );
    });
    if (parameters !== newParameters) {
      parameters = setTextRange(factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters);
    }
    if (type) {
      const importableReference = tryGetAutoImportableReferenceFromTypeNode(type, scriptTarget);
      if (importableReference) {
        type = importableReference.typeNode;
        importSymbols(importAdder, importableReference.symbols);
      }
    }
  }
  const questionToken = optional ? factory.createToken(58 /* QuestionToken */) : void 0;
  const asteriskToken = signatureDeclaration.asteriskToken;
  if (isFunctionExpression(signatureDeclaration)) {
    return factory.updateFunctionExpression(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body);
  }
  if (isArrowFunction(signatureDeclaration)) {
    return factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body ?? signatureDeclaration.body);
  }
  if (isMethodDeclaration(signatureDeclaration)) {
    return factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name ?? factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body);
  }
  if (isFunctionDeclaration(signatureDeclaration)) {
    return factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body);
  }
  return void 0;
}
function createSignatureDeclarationFromCallExpression(kind, context, importAdder, call, name, modifierFlags, contextNode) {
  const quotePreference = getQuotePreference(context.sourceFile, context.preferences);
  const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
  const tracker = getNoopSymbolTrackerWithResolver(context);
  const checker = context.program.getTypeChecker();
  const isJs = isInJSFile(contextNode);
  const { typeArguments, arguments: args, parent: parent2 } = call;
  const contextualType = isJs ? void 0 : checker.getContextualType(call);
  const names = map(args, (arg) => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : void 0);
  const instanceTypes = isJs ? [] : map(args, (arg) => checker.getTypeAtLocation(arg));
  const { argumentTypeNodes, argumentTypeParameters } = getArgumentTypesAndTypeParameters(
    checker,
    importAdder,
    instanceTypes,
    contextNode,
    scriptTarget,
    /*flags*/
    void 0,
    tracker
  );
  const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0;
  const asteriskToken = isYieldExpression(parent2) ? factory.createToken(42 /* AsteriskToken */) : void 0;
  const typeParameters = isJs ? void 0 : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments);
  const parameters = createDummyParameters(
    args.length,
    names,
    argumentTypeNodes,
    /*minArgumentCount*/
    void 0,
    isJs
  );
  const type = isJs || contextualType === void 0 ? void 0 : checker.typeToTypeNode(
    contextualType,
    contextNode,
    /*flags*/
    void 0,
    tracker
  );
  switch (kind) {
    case 173 /* MethodDeclaration */:
      return factory.createMethodDeclaration(
        modifiers,
        asteriskToken,
        name,
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        type,
        createStubbedMethodBody(quotePreference)
      );
    case 172 /* MethodSignature */:
      return factory.createMethodSignature(
        modifiers,
        name,
        /*questionToken*/
        void 0,
        typeParameters,
        parameters,
        type === void 0 ? factory.createKeywordTypeNode(159 /* UnknownKeyword */) : type
      );
    case 261 /* FunctionDeclaration */:
      return factory.createFunctionDeclaration(
        modifiers,
        asteriskToken,
        name,
        typeParameters,
        parameters,
        type,
        createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference)
      );
    default:
      Debug.fail("Unexpected kind");
  }
}
function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) {
  const usedNames = new Set(argumentTypeParameters.map((pair) => pair[0]));
  const constraintsByName = new Map(argumentTypeParameters);
  if (typeArguments) {
    const typeArgumentsWithNewTypes = typeArguments.filter((typeArgument) => !argumentTypeParameters.some((pair) => {
      var _a;
      return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) == null ? void 0 : _a.argumentType);
    }));
    const targetSize = usedNames.size + typeArgumentsWithNewTypes.length;
    for (let i = 0; usedNames.size < targetSize; i += 1) {
      usedNames.add(createTypeParameterName(i));
    }
  }
  return arrayFrom(
    usedNames.values(),
    (usedName) => {
      var _a;
      return factory.createTypeParameterDeclaration(
        /*modifiers*/
        void 0,
        usedName,
        (_a = constraintsByName.get(usedName)) == null ? void 0 : _a.constraint
      );
    }
  );
}
function createTypeParameterName(index) {
  return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`;
}
function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) {
  let typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker);
  if (typeNode && isImportTypeNode(typeNode)) {
    const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
    if (importableReference) {
      importSymbols(importAdder, importableReference.symbols);
      typeNode = importableReference.typeNode;
    }
  }
  return getSynthesizedDeepClone(typeNode);
}
function typeContainsTypeParameter(type) {
  if (type.isUnionOrIntersection()) {
    return type.types.some(typeContainsTypeParameter);
  }
  return type.flags & 262144 /* TypeParameter */;
}
function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) {
  const argumentTypeNodes = [];
  const argumentTypeParameters = /* @__PURE__ */ new Map();
  for (let i = 0; i < instanceTypes.length; i += 1) {
    const instanceType = instanceTypes[i];
    if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) {
      const synthesizedTypeParameterName = createTypeParameterName(i);
      argumentTypeNodes.push(factory.createTypeReferenceNode(synthesizedTypeParameterName));
      argumentTypeParameters.set(synthesizedTypeParameterName, void 0);
      continue;
    }
    const widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType);
    const argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker);
    if (!argumentTypeNode) {
      continue;
    }
    argumentTypeNodes.push(argumentTypeNode);
    const argumentTypeParameter = getFirstTypeParameterName(instanceType);
    const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) : void 0;
    if (argumentTypeParameter) {
      argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint });
    }
  }
  return { argumentTypeNodes, argumentTypeParameters: arrayFrom(argumentTypeParameters.entries()) };
}
function isAnonymousObjectConstraintType(type) {
  return type.flags & 524288 /* Object */ && type.objectFlags === 16 /* Anonymous */;
}
function getFirstTypeParameterName(type) {
  var _a;
  if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
    for (const subType of type.types) {
      const subTypeName = getFirstTypeParameterName(subType);
      if (subTypeName) {
        return subTypeName;
      }
    }
  }
  return type.flags & 262144 /* TypeParameter */ ? (_a = type.getSymbol()) == null ? void 0 : _a.getName() : void 0;
}
function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
  const parameters = [];
  const parameterNameCounts = /* @__PURE__ */ new Map();
  for (let i = 0; i < argCount; i++) {
    const parameterName = (names == null ? void 0 : names[i]) || `arg${i}`;
    const parameterNameCount = parameterNameCounts.get(parameterName);
    parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1);
    const newParameter = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      /*name*/
      parameterName + (parameterNameCount || ""),
      /*questionToken*/
      minArgumentCount !== void 0 && i >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0,
      /*type*/
      inJs ? void 0 : (types == null ? void 0 : types[i]) || factory.createKeywordTypeNode(159 /* UnknownKeyword */),
      /*initializer*/
      void 0
    );
    parameters.push(newParameter);
  }
  return parameters;
}
function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) {
  let maxArgsSignature = signatures[0];
  let minArgumentCount = signatures[0].minArgumentCount;
  let someSigHasRestParameter = false;
  for (const sig of signatures) {
    minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
    if (signatureHasRestParameter(sig)) {
      someSigHasRestParameter = true;
    }
    if (sig.parameters.length >= maxArgsSignature.parameters.length && (!signatureHasRestParameter(sig) || signatureHasRestParameter(maxArgsSignature))) {
      maxArgsSignature = sig;
    }
  }
  const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0);
  const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map((symbol) => symbol.name);
  const parameters = createDummyParameters(
    maxNonRestArgs,
    maxArgsParameterSymbolNames,
    /*types*/
    void 0,
    minArgumentCount,
    /*inJs*/
    false
  );
  if (someSigHasRestParameter) {
    const restParameter = factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      factory.createToken(26 /* DotDotDotToken */),
      maxArgsParameterSymbolNames[maxNonRestArgs] || "rest",
      /*questionToken*/
      maxNonRestArgs >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0,
      factory.createArrayTypeNode(factory.createKeywordTypeNode(159 /* UnknownKeyword */)),
      /*initializer*/
      void 0
    );
    parameters.push(restParameter);
  }
  return createStubbedMethod(
    modifiers,
    name,
    optional,
    /*typeParameters*/
    void 0,
    parameters,
    getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration),
    quotePreference,
    body
  );
}
function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) {
  if (length(signatures)) {
    const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature));
    return checker.typeToTypeNode(type, enclosingDeclaration, 1 /* NoTruncation */, getNoopSymbolTrackerWithResolver(context));
  }
}
function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) {
  return factory.createMethodDeclaration(
    modifiers,
    /*asteriskToken*/
    void 0,
    name,
    optional ? factory.createToken(58 /* QuestionToken */) : void 0,
    typeParameters,
    parameters,
    returnType,
    body || createStubbedMethodBody(quotePreference)
  );
}
function createStubbedMethodBody(quotePreference) {
  return createStubbedBody(Diagnostics.Method_not_implemented.message, quotePreference);
}
function createStubbedBody(text, quotePreference) {
  return factory.createBlock(
    [factory.createThrowStatement(
      factory.createNewExpression(
        factory.createIdentifier("Error"),
        /*typeArguments*/
        void 0,
        // TODO Handle auto quote preference.
        [factory.createStringLiteral(
          text,
          /*isSingleQuote*/
          quotePreference === 0 /* Single */
        )]
      )
    )],
    /*multiLine*/
    true
  );
}
function setJsonCompilerOptionValues(changeTracker, configFile, options) {
  const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile);
  if (!tsconfigObjectLiteral)
    return void 0;
  const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
  if (compilerOptionsProperty === void 0) {
    changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment(
      "compilerOptions",
      factory.createObjectLiteralExpression(
        options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)),
        /*multiLine*/
        true
      )
    ));
    return;
  }
  const compilerOptions = compilerOptionsProperty.initializer;
  if (!isObjectLiteralExpression(compilerOptions)) {
    return;
  }
  for (const [optionName, optionValue] of options) {
    const optionProperty = findJsonProperty(compilerOptions, optionName);
    if (optionProperty === void 0) {
      changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue));
    } else {
      changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue);
    }
  }
}
function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) {
  setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]);
}
function createJsonPropertyAssignment(name, initializer) {
  return factory.createPropertyAssignment(factory.createStringLiteral(name), initializer);
}
function findJsonProperty(obj, name) {
  return find(obj.properties, (p) => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name);
}
function tryGetAutoImportableReferenceFromTypeNode(importTypeNode, scriptTarget) {
  let symbols;
  const typeNode = visitNode(importTypeNode, visit, isTypeNode);
  if (symbols && typeNode) {
    return { typeNode, symbols };
  }
  function visit(node) {
    if (isLiteralImportTypeNode(node) && node.qualifier) {
      const firstIdentifier = getFirstIdentifier(node.qualifier);
      const name = getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget);
      const qualifier = name !== firstIdentifier.text ? replaceFirstIdentifierOfEntityName(node.qualifier, factory.createIdentifier(name)) : node.qualifier;
      symbols = append(symbols, firstIdentifier.symbol);
      const typeArguments = visitNodes2(node.typeArguments, visit, isTypeNode);
      return factory.createTypeReferenceNode(qualifier, typeArguments);
    }
    return visitEachChild(node, visit, nullTransformationContext);
  }
}
function replaceFirstIdentifierOfEntityName(name, newIdentifier) {
  if (name.kind === 80 /* Identifier */) {
    return newIdentifier;
  }
  return factory.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right);
}
function importSymbols(importAdder, symbols) {
  symbols.forEach((s) => importAdder.addImportFromExportedSymbol(
    s,
    /*isValidTypeOnlyUseSite*/
    true
  ));
}
function findAncestorMatchingSpan(sourceFile, span) {
  const end = textSpanEnd(span);
  let token = getTokenAtPosition(sourceFile, span.start);
  while (token.end < end) {
    token = token.parent;
  }
  return token;
}

// src/services/codefixes/generateAccessors.ts
function generateAccessorFromProperty(file, program, start2, end, context, _actionName) {
  const fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start2, end);
  if (!fieldInfo || ts_refactor_exports.isRefactorErrorInfo(fieldInfo))
    return void 0;
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context);
  const { isStatic: isStatic2, isReadonly, fieldName, accessorName, originalName, type, container, declaration } = fieldInfo;
  suppressLeadingAndTrailingTrivia(fieldName);
  suppressLeadingAndTrailingTrivia(accessorName);
  suppressLeadingAndTrailingTrivia(declaration);
  suppressLeadingAndTrailingTrivia(container);
  let accessorModifiers;
  let fieldModifiers;
  if (isClassLike(container)) {
    const modifierFlags = getEffectiveModifierFlags(declaration);
    if (isSourceFileJS(file)) {
      const modifiers = factory.createModifiersFromModifierFlags(modifierFlags);
      accessorModifiers = modifiers;
      fieldModifiers = modifiers;
    } else {
      accessorModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForAccessor(modifierFlags));
      fieldModifiers = factory.createModifiersFromModifierFlags(prepareModifierFlagsForField(modifierFlags));
    }
    if (canHaveDecorators(declaration)) {
      fieldModifiers = concatenate(getDecorators(declaration), fieldModifiers);
    }
  }
  updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers);
  const getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container);
  suppressLeadingAndTrailingTrivia(getAccessor);
  insertAccessor(changeTracker, file, getAccessor, declaration, container);
  if (isReadonly) {
    const constructor = getFirstConstructorWithBody(container);
    if (constructor) {
      updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
    }
  } else {
    const setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic2, container);
    suppressLeadingAndTrailingTrivia(setAccessor);
    insertAccessor(changeTracker, file, setAccessor, declaration, container);
  }
  return changeTracker.getChanges();
}
function isConvertibleName(name) {
  return isIdentifier(name) || isStringLiteral(name);
}
function isAcceptedDeclaration(node) {
  return isParameterPropertyDeclaration(node, node.parent) || isPropertyDeclaration(node) || isPropertyAssignment(node);
}
function createPropertyName(name, originalName) {
  return isIdentifier(originalName) ? factory.createIdentifier(name) : factory.createStringLiteral(name);
}
function createAccessorAccessExpression(fieldName, isStatic2, container) {
  const leftHead = isStatic2 ? container.name : factory.createThis();
  return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName));
}
function prepareModifierFlagsForAccessor(modifierFlags) {
  modifierFlags &= ~64 /* Readonly */;
  modifierFlags &= ~8 /* Private */;
  if (!(modifierFlags & 16 /* Protected */)) {
    modifierFlags |= 4 /* Public */;
  }
  return modifierFlags;
}
function prepareModifierFlagsForField(modifierFlags) {
  modifierFlags &= ~4 /* Public */;
  modifierFlags &= ~16 /* Protected */;
  modifierFlags |= 8 /* Private */;
  return modifierFlags;
}
function getAccessorConvertiblePropertyAtPosition(file, program, start2, end, considerEmptySpans = true) {
  const node = getTokenAtPosition(file, start2);
  const cursorRequest = start2 === end && considerEmptySpans;
  const declaration = findAncestor(node.parent, isAcceptedDeclaration);
  const meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
  if (!declaration || !(nodeOverlapsWithStartEnd(declaration.name, file, start2, end) || cursorRequest)) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor)
    };
  }
  if (!isConvertibleName(declaration.name)) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid)
    };
  }
  if ((getEffectiveModifierFlags(declaration) & 126975 /* Modifier */ | meaning) !== meaning) {
    return {
      error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier)
    };
  }
  const name = declaration.name.text;
  const startWithUnderscore = startsWithUnderscore(name);
  const fieldName = createPropertyName(startWithUnderscore ? name : getUniqueName(`_${name}`, file), declaration.name);
  const accessorName = createPropertyName(startWithUnderscore ? getUniqueName(name.substring(1), file) : name, declaration.name);
  return {
    isStatic: hasStaticModifier(declaration),
    isReadonly: hasEffectiveReadonlyModifier(declaration),
    type: getDeclarationType(declaration, program),
    container: declaration.kind === 168 /* Parameter */ ? declaration.parent.parent : declaration.parent,
    originalName: declaration.name.text,
    declaration,
    fieldName,
    accessorName,
    renameAccessor: startWithUnderscore
  };
}
function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) {
  return factory.createGetAccessorDeclaration(
    modifiers,
    accessorName,
    [],
    type,
    factory.createBlock(
      [
        factory.createReturnStatement(
          createAccessorAccessExpression(fieldName, isStatic2, container)
        )
      ],
      /*multiLine*/
      true
    )
  );
}
function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) {
  return factory.createSetAccessorDeclaration(
    modifiers,
    accessorName,
    [factory.createParameterDeclaration(
      /*modifiers*/
      void 0,
      /*dotDotDotToken*/
      void 0,
      factory.createIdentifier("value"),
      /*questionToken*/
      void 0,
      type
    )],
    factory.createBlock(
      [
        factory.createExpressionStatement(
          factory.createAssignment(
            createAccessorAccessExpression(fieldName, isStatic2, container),
            factory.createIdentifier("value")
          )
        )
      ],
      /*multiLine*/
      true
    )
  );
}
function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) {
  const property = factory.updatePropertyDeclaration(
    declaration,
    modifiers,
    fieldName,
    declaration.questionToken || declaration.exclamationToken,
    type,
    declaration.initializer
  );
  changeTracker.replaceNode(file, declaration, property);
}
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
  let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
  if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) {
    if (assignment === declaration)
      assignment = factory.cloneNode(assignment);
    assignment.modifiers = void 0;
    assignment.questionToken = void 0;
    assignment.exclamationToken = void 0;
  }
  changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
function updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) {
  if (isPropertyDeclaration(declaration)) {
    updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers);
  } else if (isPropertyAssignment(declaration)) {
    updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
  } else {
    changeTracker.replaceNode(
      file,
      declaration,
      factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)
    );
  }
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
  isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertMemberAtStart(file, container, accessor) : isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor);
}
function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
  if (!constructor.body)
    return;
  constructor.body.forEachChild(function recur(node) {
    if (isElementAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && isStringLiteral(node.argumentExpression) && node.argumentExpression.text === originalName && isWriteAccess(node)) {
      changeTracker.replaceNode(file, node.argumentExpression, factory.createStringLiteral(fieldName));
    }
    if (isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && node.name.text === originalName && isWriteAccess(node)) {
      changeTracker.replaceNode(file, node.name, factory.createIdentifier(fieldName));
    }
    if (!isFunctionLike(node) && !isClassLike(node)) {
      node.forEachChild(recur);
    }
  });
}
function getDeclarationType(declaration, program) {
  const typeNode = getTypeAnnotationNode(declaration);
  if (isPropertyDeclaration(declaration) && typeNode && declaration.questionToken) {
    const typeChecker = program.getTypeChecker();
    const type = typeChecker.getTypeFromTypeNode(typeNode);
    if (!typeChecker.isTypeAssignableTo(typeChecker.getUndefinedType(), type)) {
      const types = isUnionTypeNode(typeNode) ? typeNode.types : [typeNode];
      return factory.createUnionTypeNode([...types, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]);
    }
  }
  return typeNode;
}
function getAllSupers(decl, checker) {
  const res = [];
  while (decl) {
    const superElement = getClassExtendsHeritageElement(decl);
    const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
    if (!superSymbol)
      break;
    const symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol;
    const superDecl = symbol.declarations && find(symbol.declarations, isClassLike);
    if (!superDecl)
      break;
    res.push(superDecl);
    decl = superDecl;
  }
  return res;
}

// src/services/codefixes/fixInvalidImportSyntax.ts
var fixName5 = "invalidImportSyntax";
function getCodeFixesForImportDeclaration(context, node) {
  const sourceFile = getSourceFileOfNode(node);
  const namespace = getNamespaceDeclarationNode(node);
  const opts = context.program.getCompilerOptions();
  const variations = [];
  variations.push(createAction(context, sourceFile, node, makeImport(
    namespace.name,
    /*namedImports*/
    void 0,
    node.moduleSpecifier,
    getQuotePreference(sourceFile, context.preferences)
  )));
  if (getEmitModuleKind(opts) === 1 /* CommonJS */) {
    variations.push(createAction(context, sourceFile, node, factory.createImportEqualsDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      false,
      namespace.name,
      factory.createExternalModuleReference(node.moduleSpecifier)
    )));
  }
  return variations;
}
function createAction(context, sourceFile, node, replacement) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(sourceFile, node, replacement));
  return createCodeFixActionWithoutFixAll(fixName5, changes, [Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]);
}
registerCodeFix({
  errorCodes: [
    Diagnostics.This_expression_is_not_callable.code,
    Diagnostics.This_expression_is_not_constructable.code
  ],
  getCodeActions: getActionsForUsageOfInvalidImport
});
function getActionsForUsageOfInvalidImport(context) {
  const sourceFile = context.sourceFile;
  const targetKind = Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 212 /* CallExpression */ : 213 /* NewExpression */;
  const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a) => a.kind === targetKind);
  if (!node) {
    return [];
  }
  const expr = node.expression;
  return getImportCodeFixesForExpression(context, expr);
}
registerCodeFix({
  errorCodes: [
    // The following error codes cover pretty much all assignability errors that could involve an expression
    Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
    Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code,
    Diagnostics.Type_0_is_not_assignable_to_type_1.code,
    Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
    Diagnostics.Type_predicate_0_is_not_assignable_to_1.code,
    Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3.code,
    Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3.code,
    Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code,
    Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
    Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code,
    Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code
  ],
  getCodeActions: getActionsForInvalidImportLocation
});
function getActionsForInvalidImportLocation(context) {
  const sourceFile = context.sourceFile;
  const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a) => a.getStart() === context.span.start && a.getEnd() === context.span.start + context.span.length);
  if (!node) {
    return [];
  }
  return getImportCodeFixesForExpression(context, node);
}
function getImportCodeFixesForExpression(context, expr) {
  const type = context.program.getTypeChecker().getTypeAtLocation(expr);
  if (!(type.symbol && isTransientSymbol(type.symbol) && type.symbol.links.originatingImport)) {
    return [];
  }
  const fixes = [];
  const relatedImport = type.symbol.links.originatingImport;
  if (!isImportCall(relatedImport)) {
    addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
  }
  if (isExpression(expr) && !(isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
    const sourceFile = context.sourceFile;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(sourceFile, expr, factory.createPropertyAccessExpression(expr, "default"), {}));
    fixes.push(createCodeFixActionWithoutFixAll(fixName5, changes, Diagnostics.Use_synthetic_default_member));
  }
  return fixes;
}

// src/services/codefixes/fixStrictClassInitialization.ts
var fixName6 = "strictClassInitialization";
var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
var fixIdAddInitializer = "addMissingPropertyInitializer";
var errorCodes51 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
registerCodeFix({
  errorCodes: errorCodes51,
  getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) {
    const info = getInfo16(context.sourceFile, context.span.start);
    if (!info)
      return;
    const result = [];
    append(result, getActionForAddMissingUndefinedType(context, info));
    append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info));
    append(result, getActionForAddMissingInitializer(context, info));
    return result;
  },
  fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes51, (changes, diag2) => {
      const info = getInfo16(diag2.file, diag2.start);
      if (!info)
        return;
      switch (context.fixId) {
        case fixIdAddDefiniteAssignmentAssertions:
          addDefiniteAssignmentAssertion(changes, diag2.file, info.prop);
          break;
        case fixIdAddUndefinedType:
          addUndefinedType(changes, diag2.file, info);
          break;
        case fixIdAddInitializer:
          const checker = context.program.getTypeChecker();
          const initializer = getInitializer(checker, info.prop);
          if (!initializer)
            return;
          addInitializer(changes, diag2.file, info.prop, initializer);
          break;
        default:
          Debug.fail(JSON.stringify(context.fixId));
      }
    });
  }
});
function getInfo16(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  if (isIdentifier(token) && isPropertyDeclaration(token.parent)) {
    const type = getEffectiveTypeAnnotationNode(token.parent);
    if (type) {
      return { type, prop: token.parent, isJs: isInJSFile(token.parent) };
    }
  }
  return void 0;
}
function getActionForAddMissingDefiniteAssignmentAssertion(context, info) {
  if (info.isJs)
    return void 0;
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop));
  return createCodeFixAction(fixName6, changes, [Diagnostics.Add_definite_assignment_assertion_to_property_0, info.prop.getText()], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties);
}
function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
  suppressLeadingAndTrailingTrivia(propertyDeclaration);
  const property = factory.updatePropertyDeclaration(
    propertyDeclaration,
    propertyDeclaration.modifiers,
    propertyDeclaration.name,
    factory.createToken(54 /* ExclamationToken */),
    propertyDeclaration.type,
    propertyDeclaration.initializer
  );
  changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
}
function getActionForAddMissingUndefinedType(context, info) {
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addUndefinedType(t, context.sourceFile, info));
  return createCodeFixAction(fixName6, changes, [Diagnostics.Add_undefined_type_to_property_0, info.prop.name.getText()], fixIdAddUndefinedType, Diagnostics.Add_undefined_type_to_all_uninitialized_properties);
}
function addUndefinedType(changeTracker, sourceFile, info) {
  const undefinedTypeNode = factory.createKeywordTypeNode(157 /* UndefinedKeyword */);
  const types = isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [info.type, undefinedTypeNode];
  const unionTypeNode = factory.createUnionTypeNode(types);
  if (info.isJs) {
    changeTracker.addJSDocTags(sourceFile, info.prop, [factory.createJSDocTypeTag(
      /*tagName*/
      void 0,
      factory.createJSDocTypeExpression(unionTypeNode)
    )]);
  } else {
    changeTracker.replaceNode(sourceFile, info.type, unionTypeNode);
  }
}
function getActionForAddMissingInitializer(context, info) {
  if (info.isJs)
    return void 0;
  const checker = context.program.getTypeChecker();
  const initializer = getInitializer(checker, info.prop);
  if (!initializer)
    return void 0;
  const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addInitializer(t, context.sourceFile, info.prop, initializer));
  return createCodeFixAction(fixName6, changes, [Diagnostics.Add_initializer_to_property_0, info.prop.name.getText()], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties);
}
function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) {
  suppressLeadingAndTrailingTrivia(propertyDeclaration);
  const property = factory.updatePropertyDeclaration(
    propertyDeclaration,
    propertyDeclaration.modifiers,
    propertyDeclaration.name,
    propertyDeclaration.questionToken,
    propertyDeclaration.type,
    initializer
  );
  changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
}
function getInitializer(checker, propertyDeclaration) {
  return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type));
}
function getDefaultValueFromType(checker, type) {
  if (type.flags & 512 /* BooleanLiteral */) {
    return type === checker.getFalseType() || type === checker.getFalseType(
      /*fresh*/
      true
    ) ? factory.createFalse() : factory.createTrue();
  } else if (type.isStringLiteral()) {
    return factory.createStringLiteral(type.value);
  } else if (type.isNumberLiteral()) {
    return factory.createNumericLiteral(type.value);
  } else if (type.flags & 2048 /* BigIntLiteral */) {
    return factory.createBigIntLiteral(type.value);
  } else if (type.isUnion()) {
    return firstDefined(type.types, (t) => getDefaultValueFromType(checker, t));
  } else if (type.isClass()) {
    const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
    if (!classDeclaration || hasSyntacticModifier(classDeclaration, 256 /* Abstract */))
      return void 0;
    const constructorDeclaration = getFirstConstructorWithBody(classDeclaration);
    if (constructorDeclaration && constructorDeclaration.parameters.length)
      return void 0;
    return factory.createNewExpression(
      factory.createIdentifier(type.symbol.name),
      /*typeArguments*/
      void 0,
      /*argumentsArray*/
      void 0
    );
  } else if (checker.isArrayLikeType(type)) {
    return factory.createArrayLiteralExpression();
  }
  return void 0;
}

// src/services/codefixes/requireInTs.ts
var fixId41 = "requireInTs";
var errorCodes52 = [Diagnostics.require_call_may_be_converted_to_an_import.code];
registerCodeFix({
  errorCodes: errorCodes52,
  getCodeActions(context) {
    const info = getInfo17(context.sourceFile, context.program, context.span.start);
    if (!info) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, context.sourceFile, info));
    return [createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import)];
  },
  fixIds: [fixId41],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => {
    const info = getInfo17(diag2.file, context.program, diag2.start);
    if (info) {
      doChange34(changes, context.sourceFile, info);
    }
  })
});
function doChange34(changes, sourceFile, info) {
  const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info;
  changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration(
    /*modifiers*/
    void 0,
    /*isTypeOnly*/
    false,
    defaultImportName,
    factory.createExternalModuleReference(required)
  ) : factory.createImportDeclaration(
    /*modifiers*/
    void 0,
    factory.createImportClause(
      /*isTypeOnly*/
      false,
      defaultImportName,
      namedImports
    ),
    required,
    /*assertClause*/
    void 0
  ));
}
function getInfo17(sourceFile, program, pos) {
  const { parent: parent2 } = getTokenAtPosition(sourceFile, pos);
  if (!isRequireCall(
    parent2,
    /*requireStringLiteralLikeArgument*/
    true
  )) {
    Debug.failBadSyntaxKind(parent2);
  }
  const decl = cast(parent2.parent, isVariableDeclaration);
  const defaultImportName = tryCast(decl.name, isIdentifier);
  const namedImports = isObjectBindingPattern(decl.name) ? tryCreateNamedImportsFromObjectBindingPattern(decl.name) : void 0;
  if (defaultImportName || namedImports) {
    return {
      allowSyntheticDefaults: getAllowSyntheticDefaultImports(program.getCompilerOptions()),
      defaultImportName,
      namedImports,
      statement: cast(decl.parent.parent, isVariableStatement),
      required: first(parent2.arguments)
    };
  }
}
function tryCreateNamedImportsFromObjectBindingPattern(node) {
  const importSpecifiers = [];
  for (const element of node.elements) {
    if (!isIdentifier(element.name) || element.initializer) {
      return void 0;
    }
    importSpecifiers.push(factory.createImportSpecifier(
      /*isTypeOnly*/
      false,
      tryCast(element.propertyName, isIdentifier),
      element.name
    ));
  }
  if (importSpecifiers.length) {
    return factory.createNamedImports(importSpecifiers);
  }
}

// src/services/codefixes/useDefaultImport.ts
var fixId42 = "useDefaultImport";
var errorCodes53 = [Diagnostics.Import_may_be_converted_to_a_default_import.code];
registerCodeFix({
  errorCodes: errorCodes53,
  getCodeActions(context) {
    const { sourceFile, span: { start: start2 } } = context;
    const info = getInfo18(sourceFile, start2);
    if (!info)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, sourceFile, info, context.preferences));
    return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports)];
  },
  fixIds: [fixId42],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes53, (changes, diag2) => {
    const info = getInfo18(diag2.file, diag2.start);
    if (info)
      doChange35(changes, diag2.file, info, context.preferences);
  })
});
function getInfo18(sourceFile, pos) {
  const name = getTokenAtPosition(sourceFile, pos);
  if (!isIdentifier(name))
    return void 0;
  const { parent: parent2 } = name;
  if (isImportEqualsDeclaration(parent2) && isExternalModuleReference(parent2.moduleReference)) {
    return { importNode: parent2, name, moduleSpecifier: parent2.moduleReference.expression };
  } else if (isNamespaceImport(parent2)) {
    const importNode = parent2.parent.parent;
    return { importNode, name, moduleSpecifier: importNode.moduleSpecifier };
  }
}
function doChange35(changes, sourceFile, info, preferences) {
  changes.replaceNode(sourceFile, info.importNode, makeImport(
    info.name,
    /*namedImports*/
    void 0,
    info.moduleSpecifier,
    getQuotePreference(sourceFile, preferences)
  ));
}

// src/services/codefixes/useBigintLiteral.ts
var fixId43 = "useBigintLiteral";
var errorCodes54 = [
  Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code
];
registerCodeFix({
  errorCodes: errorCodes54,
  getCodeActions: function getCodeActionsToUseBigintLiteral(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange9(t, context.sourceFile, context.span));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId43, Diagnostics.Convert_all_to_bigint_numeric_literals)];
    }
  },
  fixIds: [fixId43],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes54, (changes, diag2) => makeChange9(changes, diag2.file, diag2));
  }
});
function makeChange9(changeTracker, sourceFile, span) {
  const numericLiteral = tryCast(getTokenAtPosition(sourceFile, span.start), isNumericLiteral);
  if (!numericLiteral) {
    return;
  }
  const newText = numericLiteral.getText(sourceFile) + "n";
  changeTracker.replaceNode(sourceFile, numericLiteral, factory.createBigIntLiteral(newText));
}

// src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts
var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
var fixId44 = fixIdAddMissingTypeof;
var errorCodes55 = [Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code];
registerCodeFix({
  errorCodes: errorCodes55,
  getCodeActions: function getCodeActionsToAddMissingTypeof(context) {
    const { sourceFile, span } = context;
    const importType = getImportTypeNode(sourceFile, span.start);
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, importType));
    return [createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof)];
  },
  fixIds: [fixId44],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start)))
});
function getImportTypeNode(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  Debug.assert(token.kind === 102 /* ImportKeyword */, "This token should be an ImportKeyword");
  Debug.assert(token.parent.kind === 204 /* ImportType */, "Token parent should be an ImportType");
  return token.parent;
}
function doChange36(changes, sourceFile, importType) {
  const newTypeNode = factory.updateImportTypeNode(
    importType,
    importType.argument,
    importType.assertions,
    importType.qualifier,
    importType.typeArguments,
    /*isTypeOf*/
    true
  );
  changes.replaceNode(sourceFile, importType, newTypeNode);
}

// src/services/codefixes/wrapJsxInFragment.ts
var fixID2 = "wrapJsxInFragment";
var errorCodes56 = [Diagnostics.JSX_expressions_must_have_one_parent_element.code];
registerCodeFix({
  errorCodes: errorCodes56,
  getCodeActions: function getCodeActionsToWrapJsxInFragment(context) {
    const { sourceFile, span } = context;
    const node = findNodeToFix(sourceFile, span.start);
    if (!node)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, node));
    return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)];
  },
  fixIds: [fixID2],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes56, (changes, diag2) => {
    const node = findNodeToFix(context.sourceFile, diag2.start);
    if (!node)
      return void 0;
    doChange37(changes, context.sourceFile, node);
  })
});
function findNodeToFix(sourceFile, pos) {
  const lessThanToken = getTokenAtPosition(sourceFile, pos);
  const firstJsxElementOrOpenElement = lessThanToken.parent;
  let binaryExpr = firstJsxElementOrOpenElement.parent;
  if (!isBinaryExpression(binaryExpr)) {
    binaryExpr = binaryExpr.parent;
    if (!isBinaryExpression(binaryExpr))
      return void 0;
  }
  if (!nodeIsMissing(binaryExpr.operatorToken))
    return void 0;
  return binaryExpr;
}
function doChange37(changeTracker, sf, node) {
  const jsx = flattenInvalidBinaryExpr(node);
  if (jsx)
    changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment()));
}
function flattenInvalidBinaryExpr(node) {
  const children = [];
  let current = node;
  while (true) {
    if (isBinaryExpression(current) && nodeIsMissing(current.operatorToken) && current.operatorToken.kind === 28 /* CommaToken */) {
      children.push(current.left);
      if (isJsxChild(current.right)) {
        children.push(current.right);
        return children;
      } else if (isBinaryExpression(current.right)) {
        current = current.right;
        continue;
      } else
        return void 0;
    } else
      return void 0;
  }
}

// src/services/codefixes/convertToMappedObjectType.ts
var fixId45 = "fixConvertToMappedObjectType";
var errorCodes57 = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code];
registerCodeFix({
  errorCodes: errorCodes57,
  getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) {
    const { sourceFile, span } = context;
    const info = getInfo19(sourceFile, span.start);
    if (!info)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, info));
    const name = idText(info.container.name);
    return [createCodeFixAction(fixId45, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId45, [Diagnostics.Convert_0_to_mapped_object_type, name])];
  },
  fixIds: [fixId45],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => {
    const info = getInfo19(diag2.file, diag2.start);
    if (info)
      doChange38(changes, diag2.file, info);
  })
});
function getInfo19(sourceFile, pos) {
  const token = getTokenAtPosition(sourceFile, pos);
  const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration);
  if (!indexSignature)
    return void 0;
  const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : tryCast(indexSignature.parent.parent, isTypeAliasDeclaration);
  if (!container)
    return void 0;
  return { indexSignature, container };
}
function createTypeAliasFromInterface(declaration, type) {
  return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type);
}
function doChange38(changes, sourceFile, { indexSignature, container }) {
  const members = isInterfaceDeclaration(container) ? container.members : container.type.members;
  const otherMembers = members.filter((member) => !isIndexSignatureDeclaration(member));
  const parameter = first(indexSignature.parameters);
  const mappedTypeParameter = factory.createTypeParameterDeclaration(
    /*modifiers*/
    void 0,
    cast(parameter.name, isIdentifier),
    parameter.type
  );
  const mappedIntersectionType = factory.createMappedTypeNode(
    hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(148 /* ReadonlyKeyword */) : void 0,
    mappedTypeParameter,
    /*nameType*/
    void 0,
    indexSignature.questionToken,
    indexSignature.type,
    /*members*/
    void 0
  );
  const intersectionType = factory.createIntersectionTypeNode([
    ...getAllSuperTypeNodes(container),
    mappedIntersectionType,
    ...otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray
  ]);
  changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
}

// src/services/codefixes/removeAccidentalCallParentheses.ts
var fixId46 = "removeAccidentalCallParentheses";
var errorCodes58 = [
  Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code
];
registerCodeFix({
  errorCodes: errorCodes58,
  getCodeActions(context) {
    const callExpression = findAncestor(getTokenAtPosition(context.sourceFile, context.span.start), isCallExpression);
    if (!callExpression) {
      return void 0;
    }
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      t.deleteRange(context.sourceFile, { pos: callExpression.expression.end, end: callExpression.end });
    });
    return [createCodeFixActionWithoutFixAll(fixId46, changes, Diagnostics.Remove_parentheses)];
  },
  fixIds: [fixId46]
});

// src/services/codefixes/removeUnnecessaryAwait.ts
var fixId47 = "removeUnnecessaryAwait";
var errorCodes59 = [
  Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code
];
registerCodeFix({
  errorCodes: errorCodes59,
  getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange10(t, context.sourceFile, context.span));
    if (changes.length > 0) {
      return [createCodeFixAction(fixId47, changes, Diagnostics.Remove_unnecessary_await, fixId47, Diagnostics.Remove_all_unnecessary_uses_of_await)];
    }
  },
  fixIds: [fixId47],
  getAllCodeActions: (context) => {
    return codeFixAll(context, errorCodes59, (changes, diag2) => makeChange10(changes, diag2.file, diag2));
  }
});
function makeChange10(changeTracker, sourceFile, span) {
  const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node) => node.kind === 135 /* AwaitKeyword */);
  const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression);
  if (!awaitExpression) {
    return;
  }
  let expressionToReplace = awaitExpression;
  const hasSurroundingParens = isParenthesizedExpression(awaitExpression.parent);
  if (hasSurroundingParens) {
    const leftMostExpression = getLeftmostExpression(
      awaitExpression.expression,
      /*stopAtCallExpressions*/
      false
    );
    if (isIdentifier(leftMostExpression)) {
      const precedingToken = findPrecedingToken(awaitExpression.parent.pos, sourceFile);
      if (precedingToken && precedingToken.kind !== 105 /* NewKeyword */) {
        expressionToReplace = awaitExpression.parent;
      }
    }
  }
  changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression);
}

// src/services/codefixes/splitTypeOnlyImport.ts
var errorCodes60 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code];
var fixId48 = "splitTypeOnlyImport";
registerCodeFix({
  errorCodes: errorCodes60,
  fixIds: [fixId48],
  getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => {
      return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context);
    });
    if (changes.length) {
      return [createCodeFixAction(fixId48, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId48, Diagnostics.Split_all_invalid_type_only_imports)];
    }
  },
  getAllCodeActions: (context) => codeFixAll(context, errorCodes60, (changes, error) => {
    splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error), context);
  })
});
function getImportDeclaration2(sourceFile, span) {
  return findAncestor(getTokenAtPosition(sourceFile, span.start), isImportDeclaration);
}
function splitTypeOnlyImport(changes, importDeclaration, context) {
  if (!importDeclaration) {
    return;
  }
  const importClause = Debug.checkDefined(importDeclaration.importClause);
  changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration(
    importDeclaration,
    importDeclaration.modifiers,
    factory.updateImportClause(
      importClause,
      importClause.isTypeOnly,
      importClause.name,
      /*namedBindings*/
      void 0
    ),
    importDeclaration.moduleSpecifier,
    importDeclaration.assertClause
  ));
  changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration(
    /*modifiers*/
    void 0,
    factory.updateImportClause(
      importClause,
      importClause.isTypeOnly,
      /*name*/
      void 0,
      importClause.namedBindings
    ),
    importDeclaration.moduleSpecifier,
    importDeclaration.assertClause
  ));
}

// src/services/codefixes/convertConstToLet.ts
var fixId49 = "fixConvertConstToLet";
var errorCodes61 = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];
registerCodeFix({
  errorCodes: errorCodes61,
  getCodeActions: function getCodeActionsToConvertConstToLet(context) {
    const { sourceFile, span, program } = context;
    const info = getInfo20(sourceFile, span.start, program);
    if (info === void 0)
      return;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info.token));
    return [createCodeFixActionMaybeFixAll(fixId49, changes, Diagnostics.Convert_const_to_let, fixId49, Diagnostics.Convert_all_const_to_let)];
  },
  getAllCodeActions: (context) => {
    const { program } = context;
    const seen = /* @__PURE__ */ new Map();
    return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => {
      eachDiagnostic(context, errorCodes61, (diag2) => {
        const info = getInfo20(diag2.file, diag2.start, program);
        if (info) {
          if (addToSeen(seen, getSymbolId(info.symbol))) {
            return doChange39(changes, diag2.file, info.token);
          }
        }
        return void 0;
      });
    }));
  },
  fixIds: [fixId49]
});
function getInfo20(sourceFile, pos, program) {
  var _a;
  const checker = program.getTypeChecker();
  const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos));
  if (symbol === void 0)
    return;
  const declaration = tryCast((_a = symbol == null ? void 0 : symbol.valueDeclaration) == null ? void 0 : _a.parent, isVariableDeclarationList);
  if (declaration === void 0)
    return;
  const constToken = findChildOfKind(declaration, 87 /* ConstKeyword */, sourceFile);
  if (constToken === void 0)
    return;
  return { symbol, token: constToken };
}
function doChange39(changes, sourceFile, token) {
  changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */));
}

// src/services/codefixes/fixExpectedComma.ts
var fixId50 = "fixExpectedComma";
var expectedErrorCode = Diagnostics._0_expected.code;
var errorCodes62 = [expectedErrorCode];
registerCodeFix({
  errorCodes: errorCodes62,
  getCodeActions(context) {
    const { sourceFile } = context;
    const info = getInfo21(sourceFile, context.span.start, context.errorCode);
    if (!info)
      return void 0;
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info));
    return [createCodeFixAction(
      fixId50,
      changes,
      [Diagnostics.Change_0_to_1, ";", ","],
      fixId50,
      [Diagnostics.Change_0_to_1, ";", ","]
    )];
  },
  fixIds: [fixId50],
  getAllCodeActions: (context) => codeFixAll(context, errorCodes62, (changes, diag2) => {
    const info = getInfo21(diag2.file, diag2.start, diag2.code);
    if (info)
      doChange40(changes, context.sourceFile, info);
  })
});
function getInfo21(sourceFile, pos, _) {
  const node = getTokenAtPosition(sourceFile, pos);
  return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { node } : void 0;
}
function doChange40(changes, sourceFile, { node }) {
  const newNode = factory.createToken(28 /* CommaToken */);
  changes.replaceNode(sourceFile, node, newNode);
}

// src/services/codefixes/fixAddVoidToPromise.ts
var fixName7 = "addVoidToPromise";
var fixId51 = "addVoidToPromise";
var errorCodes63 = [
  Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code,
  Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code
];
registerCodeFix({
  errorCodes: errorCodes63,
  fixIds: [fixId51],
  getCodeActions(context) {
    const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange11(t, context.sourceFile, context.span, context.program));
    if (changes.length > 0) {
      return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId51, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)];
    }
  },
  getAllCodeActions(context) {
    return codeFixAll(context, errorCodes63, (changes, diag2) => makeChange11(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set()));
  }
});
function makeChange11(changes, sourceFile, span, program, seen) {
  const node = getTokenAtPosition(sourceFile, span.start);
  if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0)
    return;
  const checker = program.getTypeChecker();
  const symbol = checker.getSymbolAtLocation(node);
  const decl = symbol == null ? void 0 : symbol.valueDeclaration;
  if (!decl || !isParameter(decl) || !isNewExpression(decl.parent.parent))
    return;
  if (seen == null ? void 0 : seen.has(decl))
    return;
  seen == null ? void 0 : seen.add(decl);
  const typeArguments = getEffectiveTypeArguments(decl.parent.parent);
  if (some(typeArguments)) {
    const typeArgument = typeArguments[0];
    const needsParens = !isUnionTypeNode(typeArgument) && !isParenthesizedTypeNode(typeArgument) && isParenthesizedTypeNode(factory.createUnionTypeNode([typeArgument, factory.createKeywordTypeNode(116 /* VoidKeyword */)]).types[0]);
    if (needsParens) {
      changes.insertText(sourceFile, typeArgument.pos, "(");
    }
    changes.insertText(sourceFile, typeArgument.end, needsParens ? ") | void" : " | void");
  } else {
    const signature = checker.getResolvedSignature(node.parent);
    const parameter = signature == null ? void 0 : signature.parameters[0];
    const parameterType = parameter && checker.getTypeOfSymbolAtLocation(parameter, decl.parent.parent);
    if (isInJSFile(decl)) {
      if (!parameterType || parameterType.flags & 3 /* AnyOrUnknown */) {
        changes.insertText(sourceFile, decl.parent.parent.end, `)`);
        changes.insertText(sourceFile, skipTrivia(sourceFile.text, decl.parent.parent.pos), `/** @type {Promise<void>} */(`);
      }
    } else {
      if (!parameterType || parameterType.flags & 2 /* Unknown */) {
        changes.insertText(sourceFile, decl.parent.parent.expression.end, "<void>");
      }
    }
  }
}
function getEffectiveTypeArguments(node) {
  var _a;
  if (isInJSFile(node)) {
    if (isParenthesizedExpression(node.parent)) {
      const jsDocType = (_a = getJSDocTypeTag(node.parent)) == null ? void 0 : _a.typeExpression.type;
      if (jsDocType && isTypeReferenceNode(jsDocType) && isIdentifier(jsDocType.typeName) && idText(jsDocType.typeName) === "Promise") {
        return jsDocType.typeArguments;
      }
    }
  } else {
    return node.typeArguments;
  }
}

// src/services/_namespaces/ts.Completions.ts
var ts_Completions_exports = {};
__export(ts_Completions_exports, {
  CompletionKind: () => CompletionKind,
  CompletionSource: () => CompletionSource,
  SortText: () => SortText,
  StringCompletions: () => ts_Completions_StringCompletions_exports,
  SymbolOriginInfoKind: () => SymbolOriginInfoKind,
  createCompletionDetails: () => createCompletionDetails,
  createCompletionDetailsForSymbol: () => createCompletionDetailsForSymbol,
  getCompletionEntriesFromSymbols: () => getCompletionEntriesFromSymbols,
  getCompletionEntryDetails: () => getCompletionEntryDetails,
  getCompletionEntrySymbol: () => getCompletionEntrySymbol,
  getCompletionsAtPosition: () => getCompletionsAtPosition,
  getPropertiesForObjectExpression: () => getPropertiesForObjectExpression,
  moduleSpecifierResolutionCacheAttemptLimit: () => moduleSpecifierResolutionCacheAttemptLimit,
  moduleSpecifierResolutionLimit: () => moduleSpecifierResolutionLimit
});

// src/services/completions.ts
var moduleSpecifierResolutionLimit = 100;
var moduleSpecifierResolutionCacheAttemptLimit = 1e3;
var SortText = {
  // Presets
  LocalDeclarationPriority: "10",
  LocationPriority: "11",
  OptionalMember: "12",
  MemberDeclaredBySpreadAssignment: "13",
  SuggestedClassMembers: "14",
  GlobalsOrKeywords: "15",
  AutoImportSuggestions: "16",
  ClassMemberSnippets: "17",
  JavascriptIdentifiers: "18",
  // Transformations
  Deprecated(sortText) {
    return "z" + sortText;
  },
  ObjectLiteralProperty(presetSortText, symbolDisplayName) {
    return `${presetSortText}\0${symbolDisplayName}\0`;
  },
  SortBelow(sortText) {
    return sortText + "1";
  }
};
var CompletionSource = /* @__PURE__ */ ((CompletionSource2) => {
  CompletionSource2["ThisProperty"] = "ThisProperty/";
  CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/";
  CompletionSource2["TypeOnlyAlias"] = "TypeOnlyAlias/";
  CompletionSource2["ObjectLiteralMethodSnippet"] = "ObjectLiteralMethodSnippet/";
  CompletionSource2["SwitchCases"] = "SwitchCases/";
  return CompletionSource2;
})(CompletionSource || {});
var SymbolOriginInfoKind = /* @__PURE__ */ ((SymbolOriginInfoKind2) => {
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ThisType"] = 1] = "ThisType";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMember"] = 2] = "SymbolMember";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Export"] = 4] = "Export";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Promise"] = 8] = "Promise";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Nullable"] = 16] = "Nullable";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ResolvedExport"] = 32] = "ResolvedExport";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["TypeOnlyAlias"] = 64] = "TypeOnlyAlias";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ObjectLiteralMethod"] = 128] = "ObjectLiteralMethod";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["Ignore"] = 256] = "Ignore";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["ComputedPropertyName"] = 512] = "ComputedPropertyName";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberNoExport"] = 2 /* SymbolMember */] = "SymbolMemberNoExport";
  SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberExport"] = 6] = "SymbolMemberExport";
  return SymbolOriginInfoKind2;
})(SymbolOriginInfoKind || {});
function originIsThisType(origin) {
  return !!(origin.kind & 1 /* ThisType */);
}
function originIsSymbolMember(origin) {
  return !!(origin.kind & 2 /* SymbolMember */);
}
function originIsExport(origin) {
  return !!(origin && origin.kind & 4 /* Export */);
}
function originIsResolvedExport(origin) {
  return !!(origin && origin.kind === 32 /* ResolvedExport */);
}
function originIncludesSymbolName(origin) {
  return originIsExport(origin) || originIsResolvedExport(origin) || originIsComputedPropertyName(origin);
}
function originIsPackageJsonImport(origin) {
  return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson;
}
function originIsPromise(origin) {
  return !!(origin.kind & 8 /* Promise */);
}
function originIsNullableMember(origin) {
  return !!(origin.kind & 16 /* Nullable */);
}
function originIsTypeOnlyAlias(origin) {
  return !!(origin && origin.kind & 64 /* TypeOnlyAlias */);
}
function originIsObjectLiteralMethod(origin) {
  return !!(origin && origin.kind & 128 /* ObjectLiteralMethod */);
}
function originIsIgnore(origin) {
  return !!(origin && origin.kind & 256 /* Ignore */);
}
function originIsComputedPropertyName(origin) {
  return !!(origin && origin.kind & 512 /* ComputedPropertyName */);
}
function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) {
  var _a, _b, _c;
  const start2 = timestamp();
  const needsFullResolution = isForImportStatementCompletion || moduleResolutionSupportsPackageJsonExportsAndImports(getEmitModuleResolutionKind(program.getCompilerOptions()));
  let skippedAny = false;
  let ambientCount = 0;
  let resolvedCount = 0;
  let resolvedFromCacheCount = 0;
  let cacheAttemptCount = 0;
  const result = cb({
    tryResolve,
    skippedAny: () => skippedAny,
    resolvedAny: () => resolvedCount > 0,
    resolvedBeyondLimit: () => resolvedCount > moduleSpecifierResolutionLimit
  });
  const hitRateMessage = cacheAttemptCount ? ` (${(resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1)}% hit rate)` : "";
  (_a = host.log) == null ? void 0 : _a.call(host, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`);
  (_b = host.log) == null ? void 0 : _b.call(host, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`);
  (_c = host.log) == null ? void 0 : _c.call(host, `${logPrefix}: ${timestamp() - start2}`);
  return result;
  function tryResolve(exportInfo, isFromAmbientModule) {
    if (isFromAmbientModule) {
      const result3 = resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite);
      if (result3) {
        ambientCount++;
      }
      return result3 || "failed";
    }
    const shouldResolveModuleSpecifier = needsFullResolution || preferences.allowIncompleteCompletions && resolvedCount < moduleSpecifierResolutionLimit;
    const shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < moduleSpecifierResolutionCacheAttemptLimit;
    const result2 = shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache ? resolver.getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, shouldGetModuleSpecifierFromCache) : void 0;
    if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result2) {
      skippedAny = true;
    }
    resolvedCount += (result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0;
    resolvedFromCacheCount += exportInfo.length - ((result2 == null ? void 0 : result2.computedWithoutCacheCount) || 0);
    if (shouldGetModuleSpecifierFromCache) {
      cacheAttemptCount++;
    }
    return result2 || (needsFullResolution ? "failed" : "skipped");
  }
}
function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) {
  var _a;
  const { previousToken } = getRelevantTokens(position, sourceFile);
  if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) {
    return void 0;
  }
  if (triggerCharacter === " ") {
    if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) {
      return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] };
    }
    return void 0;
  }
  const compilerOptions = program.getCompilerOptions();
  const checker = program.getTypeChecker();
  const incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) == null ? void 0 : _a.call(host) : void 0;
  if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && isIdentifier(previousToken)) {
    const incompleteContinuation = continuePreviousIncompleteResponse(incompleteCompletionsCache, sourceFile, previousToken, program, host, preferences, cancellationToken, position);
    if (incompleteContinuation) {
      return incompleteContinuation;
    }
  } else {
    incompleteCompletionsCache == null ? void 0 : incompleteCompletionsCache.clear();
  }
  const stringCompletions = ts_Completions_StringCompletions_exports.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences, includeSymbol);
  if (stringCompletions) {
    return stringCompletions;
  }
  if (previousToken && isBreakOrContinueStatement(previousToken.parent) && (previousToken.kind === 83 /* BreakKeyword */ || previousToken.kind === 88 /* ContinueKeyword */ || previousToken.kind === 80 /* Identifier */)) {
    return getLabelCompletionAtPosition(previousToken.parent);
  }
  const completionData = getCompletionData(
    program,
    log,
    sourceFile,
    compilerOptions,
    position,
    preferences,
    /*detailsEntryId*/
    void 0,
    host,
    formatContext,
    cancellationToken
  );
  if (!completionData) {
    return void 0;
  }
  switch (completionData.kind) {
    case 0 /* Data */:
      const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol);
      if (response == null ? void 0 : response.isIncomplete) {
        incompleteCompletionsCache == null ? void 0 : incompleteCompletionsCache.set(response);
      }
      return response;
    case 1 /* JsDocTagName */:
      return jsdocCompletionInfo([
        ...ts_JsDoc_exports.getJSDocTagNameCompletions(),
        ...getJSDocParameterCompletions(
          sourceFile,
          position,
          checker,
          compilerOptions,
          preferences,
          /*tagNameOnly*/
          true
        )
      ]);
    case 2 /* JsDocTag */:
      return jsdocCompletionInfo([
        ...ts_JsDoc_exports.getJSDocTagCompletions(),
        ...getJSDocParameterCompletions(
          sourceFile,
          position,
          checker,
          compilerOptions,
          preferences,
          /*tagNameOnly*/
          false
        )
      ]);
    case 3 /* JsDocParameterName */:
      return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocParameterNameCompletions(completionData.tag));
    case 4 /* Keywords */:
      return specificKeywordCompletionInfo(completionData.keywordCompletions, completionData.isNewIdentifierLocation);
    default:
      return Debug.assertNever(completionData);
  }
}
function compareCompletionEntries(entryInArray, entryToInsert) {
  var _a, _b;
  let result = compareStringsCaseSensitiveUI(entryInArray.sortText, entryToInsert.sortText);
  if (result === 0 /* EqualTo */) {
    result = compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name);
  }
  if (result === 0 /* EqualTo */ && ((_a = entryInArray.data) == null ? void 0 : _a.moduleSpecifier) && ((_b = entryToInsert.data) == null ? void 0 : _b.moduleSpecifier)) {
    result = compareNumberOfDirectorySeparators(
      entryInArray.data.moduleSpecifier,
      entryToInsert.data.moduleSpecifier
    );
  }
  if (result === 0 /* EqualTo */) {
    return -1 /* LessThan */;
  }
  return result;
}
function completionEntryDataIsResolved(data) {
  return !!(data == null ? void 0 : data.moduleSpecifier);
}
function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken, position) {
  const previousResponse = cache.get();
  if (!previousResponse)
    return void 0;
  const touchNode = getTouchingPropertyName(file, position);
  const lowerCaseTokenText = location.text.toLowerCase();
  const exportMap = getExportInfoMap(file, host, program, preferences, cancellationToken);
  const newEntries = resolvingModuleSpecifiers(
    "continuePreviousIncompleteResponse",
    host,
    ts_codefix_exports.createImportSpecifierResolver(file, program, host, preferences),
    program,
    location.getStart(),
    preferences,
    /*isForImportStatementCompletion*/
    false,
    isValidTypeOnlyAliasUseSite(location),
    (context) => {
      const entries = mapDefined(previousResponse.entries, (entry) => {
        var _a;
        if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) {
          return entry;
        }
        if (!charactersFuzzyMatchInString(entry.name, lowerCaseTokenText)) {
          return void 0;
        }
        const { origin } = Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host));
        const info = exportMap.get(file.path, entry.data.exportMapKey);
        const result = info && context.tryResolve(info, !isExternalModuleNameRelative(stripQuotes(origin.moduleSymbol.name)));
        if (result === "skipped")
          return entry;
        if (!result || result === "failed") {
          (_a = host.log) == null ? void 0 : _a.call(host, `Unexpected failure resolving auto import for '${entry.name}' from '${entry.source}'`);
          return void 0;
        }
        const newOrigin = {
          ...origin,
          kind: 32 /* ResolvedExport */,
          moduleSpecifier: result.moduleSpecifier
        };
        entry.data = originToCompletionEntryData(newOrigin);
        entry.source = getSourceFromOrigin(newOrigin);
        entry.sourceDisplay = [textPart(newOrigin.moduleSpecifier)];
        return entry;
      });
      if (!context.skippedAny()) {
        previousResponse.isIncomplete = void 0;
      }
      return entries;
    }
  );
  previousResponse.entries = newEntries;
  previousResponse.flags = (previousResponse.flags || 0) | 4 /* IsContinuation */;
  previousResponse.optionalReplacementSpan = getOptionalReplacementSpan(touchNode);
  return previousResponse;
}
function jsdocCompletionInfo(entries) {
  return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries };
}
function getJSDocParameterCompletions(sourceFile, position, checker, options, preferences, tagNameOnly) {
  const currentToken = getTokenAtPosition(sourceFile, position);
  if (!isJSDocTag(currentToken) && !isJSDoc(currentToken)) {
    return [];
  }
  const jsDoc = isJSDoc(currentToken) ? currentToken : currentToken.parent;
  if (!isJSDoc(jsDoc)) {
    return [];
  }
  const func = jsDoc.parent;
  if (!isFunctionLike(func)) {
    return [];
  }
  const isJs = isSourceFileJS(sourceFile);
  const isSnippet = preferences.includeCompletionsWithSnippetText || void 0;
  const paramTagCount = countWhere(jsDoc.tags, (tag) => isJSDocParameterTag(tag) && tag.getEnd() <= position);
  return mapDefined(func.parameters, (param) => {
    if (getJSDocParameterTags(param).length) {
      return void 0;
    }
    if (isIdentifier(param.name)) {
      const tabstopCounter = { tabstop: 1 };
      const paramName = param.name.text;
      let displayText = getJSDocParamAnnotation(
        paramName,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isObject*/
        false,
        /*isSnippet*/
        false,
        checker,
        options,
        preferences
      );
      let snippetText = isSnippet ? getJSDocParamAnnotation(
        paramName,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isObject*/
        false,
        /*isSnippet*/
        true,
        checker,
        options,
        preferences,
        tabstopCounter
      ) : void 0;
      if (tagNameOnly) {
        displayText = displayText.slice(1);
        if (snippetText)
          snippetText = snippetText.slice(1);
      }
      return {
        name: displayText,
        kind: "parameter" /* parameterElement */,
        sortText: SortText.LocationPriority,
        insertText: isSnippet ? snippetText : void 0,
        isSnippet
      };
    } else if (param.parent.parameters.indexOf(param) === paramTagCount) {
      const paramPath = `param${paramTagCount}`;
      const displayTextResult = generateJSDocParamTagsForDestructuring(
        paramPath,
        param.name,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isSnippet*/
        false,
        checker,
        options,
        preferences
      );
      const snippetTextResult = isSnippet ? generateJSDocParamTagsForDestructuring(
        paramPath,
        param.name,
        param.initializer,
        param.dotDotDotToken,
        isJs,
        /*isSnippet*/
        true,
        checker,
        options,
        preferences
      ) : void 0;
      let displayText = displayTextResult.join(getNewLineCharacter(options) + "* ");
      let snippetText = snippetTextResult == null ? void 0 : snippetTextResult.join(getNewLineCharacter(options) + "* ");
      if (tagNameOnly) {
        displayText = displayText.slice(1);
        if (snippetText)
          snippetText = snippetText.slice(1);
      }
      return {
        name: displayText,
        kind: "parameter" /* parameterElement */,
        sortText: SortText.LocationPriority,
        insertText: isSnippet ? snippetText : void 0,
        isSnippet
      };
    }
  });
}
function generateJSDocParamTagsForDestructuring(path, pattern, initializer, dotDotDotToken, isJs, isSnippet, checker, options, preferences) {
  if (!isJs) {
    return [
      getJSDocParamAnnotation(
        path,
        initializer,
        dotDotDotToken,
        isJs,
        /*isObject*/
        false,
        isSnippet,
        checker,
        options,
        preferences,
        { tabstop: 1 }
      )
    ];
  }
  return patternWorker(path, pattern, initializer, dotDotDotToken, { tabstop: 1 });
  function patternWorker(path2, pattern2, initializer2, dotDotDotToken2, counter) {
    if (isObjectBindingPattern(pattern2) && !dotDotDotToken2) {
      const oldTabstop = counter.tabstop;
      const childCounter = { tabstop: oldTabstop };
      const rootParam = getJSDocParamAnnotation(
        path2,
        initializer2,
        dotDotDotToken2,
        isJs,
        /*isObject*/
        true,
        isSnippet,
        checker,
        options,
        preferences,
        childCounter
      );
      let childTags = [];
      for (const element of pattern2.elements) {
        const elementTags = elementWorker(path2, element, childCounter);
        if (!elementTags) {
          childTags = void 0;
          break;
        } else {
          childTags.push(...elementTags);
        }
      }
      if (childTags) {
        counter.tabstop = childCounter.tabstop;
        return [rootParam, ...childTags];
      }
    }
    return [
      getJSDocParamAnnotation(
        path2,
        initializer2,
        dotDotDotToken2,
        isJs,
        /*isObject*/
        false,
        isSnippet,
        checker,
        options,
        preferences,
        counter
      )
    ];
  }
  function elementWorker(path2, element, counter) {
    if (!element.propertyName && isIdentifier(element.name) || isIdentifier(element.name)) {
      const propertyName = element.propertyName ? tryGetTextOfPropertyName(element.propertyName) : element.name.text;
      if (!propertyName) {
        return void 0;
      }
      const paramName = `${path2}.${propertyName}`;
      return [
        getJSDocParamAnnotation(
          paramName,
          element.initializer,
          element.dotDotDotToken,
          isJs,
          /*isObject*/
          false,
          isSnippet,
          checker,
          options,
          preferences,
          counter
        )
      ];
    } else if (element.propertyName) {
      const propertyName = tryGetTextOfPropertyName(element.propertyName);
      return propertyName && patternWorker(`${path2}.${propertyName}`, element.name, element.initializer, element.dotDotDotToken, counter);
    }
    return void 0;
  }
}
function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, isObject, isSnippet, checker, options, preferences, tabstopCounter) {
  if (isSnippet) {
    Debug.assertIsDefined(tabstopCounter);
  }
  if (initializer) {
    paramName = getJSDocParamNameWithInitializer(paramName, initializer);
  }
  if (isSnippet) {
    paramName = escapeSnippetText(paramName);
  }
  if (isJs) {
    let type = "*";
    if (isObject) {
      Debug.assert(!dotDotDotToken, `Cannot annotate a rest parameter with type 'Object'.`);
      type = "Object";
    } else {
      if (initializer) {
        const inferredType = checker.getTypeAtLocation(initializer.parent);
        if (!(inferredType.flags & (1 /* Any */ | 16384 /* Void */))) {
          const sourceFile = initializer.getSourceFile();
          const quotePreference = getQuotePreference(sourceFile, preferences);
          const builderFlags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */;
          const typeNode = checker.typeToTypeNode(inferredType, findAncestor(initializer, isFunctionLike), builderFlags);
          if (typeNode) {
            const printer = isSnippet ? createSnippetPrinter({
              removeComments: true,
              module: options.module,
              target: options.target
            }) : createPrinter({
              removeComments: true,
              module: options.module,
              target: options.target
            });
            setEmitFlags(typeNode, 1 /* SingleLine */);
            type = printer.printNode(4 /* Unspecified */, typeNode, sourceFile);
          }
        }
      }
      if (isSnippet && type === "*") {
        type = `\${${tabstopCounter.tabstop++}:${type}}`;
      }
    }
    const dotDotDot = !isObject && dotDotDotToken ? "..." : "";
    const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : "";
    return `@param {${dotDotDot}${type}} ${paramName} ${description3}`;
  } else {
    const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : "";
    return `@param ${paramName} ${description3}`;
  }
}
function getJSDocParamNameWithInitializer(paramName, initializer) {
  const initializerText = initializer.getText().trim();
  if (initializerText.includes("\n") || initializerText.length > 80) {
    return `[${paramName}]`;
  }
  return `[${paramName}=${initializerText}]`;
}
function keywordToCompletionEntry(keyword) {
  return {
    name: tokenToString(keyword),
    kind: "keyword" /* keyword */,
    kindModifiers: "" /* none */,
    sortText: SortText.GlobalsOrKeywords
  };
}
function specificKeywordCompletionInfo(entries, isNewIdentifierLocation) {
  return {
    isGlobalCompletion: false,
    isMemberCompletion: false,
    isNewIdentifierLocation,
    entries: entries.slice()
  };
}
function keywordCompletionData(keywordFilters, filterOutTsOnlyKeywords, isNewIdentifierLocation) {
  return {
    kind: 4 /* Keywords */,
    keywordCompletions: getKeywordCompletions(keywordFilters, filterOutTsOnlyKeywords),
    isNewIdentifierLocation
  };
}
function keywordFiltersFromSyntaxKind(keywordCompletion) {
  switch (keywordCompletion) {
    case 156 /* TypeKeyword */:
      return 8 /* TypeKeyword */;
    default:
      Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters");
  }
}
function getOptionalReplacementSpan(location) {
  return (location == null ? void 0 : location.kind) === 80 /* Identifier */ ? createTextSpanFromNode(location) : void 0;
}
function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol) {
  const {
    symbols,
    contextToken,
    completionKind,
    isInSnippetScope,
    isNewIdentifierLocation,
    location,
    propertyAccessToConvert,
    keywordFilters,
    symbolToOriginInfoMap,
    recommendedCompletion,
    isJsxInitializer,
    isTypeOnlyLocation,
    isJsxIdentifierExpected,
    isRightOfOpenTag,
    isRightOfDotOrQuestionDot,
    importStatementCompletion,
    insideJsDocTagTypeExpression,
    symbolToSortTextMap,
    hasUnresolvedAutoImports
  } = completionData;
  let literals = completionData.literals;
  const checker = program.getTypeChecker();
  if (getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) {
    const completionInfo = getJsxClosingTagCompletion(location, sourceFile);
    if (completionInfo) {
      return completionInfo;
    }
  }
  const caseClause = findAncestor(contextToken, isCaseClause);
  if (caseClause && (isCaseKeyword(contextToken) || isNodeDescendantOf(contextToken, caseClause.expression))) {
    const tracker = newCaseClauseTracker(checker, caseClause.parent.clauses);
    literals = literals.filter((literal) => !tracker.hasValue(literal));
    symbols.forEach((symbol, i) => {
      if (symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
        const value = checker.getConstantValue(symbol.valueDeclaration);
        if (value !== void 0 && tracker.hasValue(value)) {
          symbolToOriginInfoMap[i] = { kind: 256 /* Ignore */ };
        }
      }
    });
  }
  const entries = createSortedArray();
  const isChecked = isCheckedFile(sourceFile, compilerOptions);
  if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) {
    return void 0;
  }
  const uniqueNames = getCompletionEntriesFromSymbols(
    symbols,
    entries,
    /*replacementToken*/
    void 0,
    contextToken,
    location,
    position,
    sourceFile,
    host,
    program,
    getEmitScriptTarget(compilerOptions),
    log,
    completionKind,
    preferences,
    compilerOptions,
    formatContext,
    isTypeOnlyLocation,
    propertyAccessToConvert,
    isJsxIdentifierExpected,
    isJsxInitializer,
    importStatementCompletion,
    recommendedCompletion,
    symbolToOriginInfoMap,
    symbolToSortTextMap,
    isJsxIdentifierExpected,
    isRightOfOpenTag,
    includeSymbol
  );
  if (keywordFilters !== 0 /* None */) {
    for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile))) {
      if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !uniqueNames.has(keywordEntry.name)) {
        uniqueNames.add(keywordEntry.name);
        insertSorted(
          entries,
          keywordEntry,
          compareCompletionEntries,
          /*allowDuplicates*/
          true
        );
      }
    }
  }
  for (const keywordEntry of getContextualKeywords(contextToken, position)) {
    if (!uniqueNames.has(keywordEntry.name)) {
      uniqueNames.add(keywordEntry.name);
      insertSorted(
        entries,
        keywordEntry,
        compareCompletionEntries,
        /*allowDuplicates*/
        true
      );
    }
  }
  for (const literal of literals) {
    const literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal);
    uniqueNames.add(literalEntry.name);
    insertSorted(
      entries,
      literalEntry,
      compareCompletionEntries,
      /*allowDuplicates*/
      true
    );
  }
  if (!isChecked) {
    getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries);
  }
  let caseBlock;
  if (preferences.includeCompletionsWithInsertText && contextToken && !isRightOfOpenTag && !isRightOfDotOrQuestionDot && (caseBlock = findAncestor(contextToken, isCaseBlock))) {
    const cases = getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, compilerOptions, host, program, formatContext);
    if (cases) {
      entries.push(cases.entry);
    }
  }
  return {
    flags: completionData.flags,
    isGlobalCompletion: isInSnippetScope,
    isIncomplete: preferences.allowIncompleteCompletions && hasUnresolvedAutoImports ? true : void 0,
    isMemberCompletion: isMemberCompletionKind(completionKind),
    isNewIdentifierLocation,
    optionalReplacementSpan: getOptionalReplacementSpan(location),
    entries
  };
}
function isCheckedFile(sourceFile, compilerOptions) {
  return !isSourceFileJS(sourceFile) || !!isCheckJsEnabledForFile(sourceFile, compilerOptions);
}
function getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, options, host, program, formatContext) {
  const clauses = caseBlock.clauses;
  const checker = program.getTypeChecker();
  const switchType = checker.getTypeAtLocation(caseBlock.parent.expression);
  if (switchType && switchType.isUnion() && every(switchType.types, (type) => type.isLiteral())) {
    const tracker = newCaseClauseTracker(checker, clauses);
    const target = getEmitScriptTarget(options);
    const quotePreference = getQuotePreference(sourceFile, preferences);
    const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host);
    const elements = [];
    for (const type of switchType.types) {
      if (type.flags & 1024 /* EnumLiteral */) {
        Debug.assert(type.symbol, "An enum member type should have a symbol");
        Debug.assert(type.symbol.parent, "An enum member type should have a parent symbol (the enum symbol)");
        const enumValue = type.symbol.valueDeclaration && checker.getConstantValue(type.symbol.valueDeclaration);
        if (enumValue !== void 0) {
          if (tracker.hasValue(enumValue)) {
            continue;
          }
          tracker.addValue(enumValue);
        }
        const typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, caseBlock, target);
        if (!typeNode) {
          return void 0;
        }
        const expr = typeNodeToExpression(typeNode, target, quotePreference);
        if (!expr) {
          return void 0;
        }
        elements.push(expr);
      } else if (!tracker.hasValue(type.value)) {
        switch (typeof type.value) {
          case "object":
            elements.push(type.value.negative ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createBigIntLiteral({ negative: false, base10Value: type.value.base10Value })) : factory.createBigIntLiteral(type.value));
            break;
          case "number":
            elements.push(type.value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-type.value)) : factory.createNumericLiteral(type.value));
            break;
          case "string":
            elements.push(factory.createStringLiteral(type.value, quotePreference === 0 /* Single */));
            break;
        }
      }
    }
    if (elements.length === 0) {
      return void 0;
    }
    const newClauses = map(elements, (element) => factory.createCaseClause(element, []));
    const newLineChar = getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options);
    const printer = createSnippetPrinter({
      removeComments: true,
      module: options.module,
      target: options.target,
      newLine: getNewLineKind(newLineChar)
    });
    const printNode = formatContext ? (node) => printer.printAndFormatNode(4 /* Unspecified */, node, sourceFile, formatContext) : (node) => printer.printNode(4 /* Unspecified */, node, sourceFile);
    const insertText = map(newClauses, (clause, i) => {
      if (preferences.includeCompletionsWithSnippetText) {
        return `${printNode(clause)}$${i + 1}`;
      }
      return `${printNode(clause)}`;
    }).join(newLineChar);
    const firstClause = printer.printNode(4 /* Unspecified */, newClauses[0], sourceFile);
    return {
      entry: {
        name: `${firstClause} ...`,
        kind: "" /* unknown */,
        sortText: SortText.GlobalsOrKeywords,
        insertText,
        hasAction: importAdder.hasFixes() || void 0,
        source: "SwitchCases/" /* SwitchCases */,
        isSnippet: preferences.includeCompletionsWithSnippetText ? true : void 0
      },
      importAdder
    };
  }
  return void 0;
}
function typeNodeToExpression(typeNode, languageVersion, quotePreference) {
  switch (typeNode.kind) {
    case 182 /* TypeReference */:
      const typeName = typeNode.typeName;
      return entityNameToExpression(typeName, languageVersion, quotePreference);
    case 198 /* IndexedAccessType */:
      const objectExpression = typeNodeToExpression(typeNode.objectType, languageVersion, quotePreference);
      const indexExpression = typeNodeToExpression(typeNode.indexType, languageVersion, quotePreference);
      return objectExpression && indexExpression && factory.createElementAccessExpression(objectExpression, indexExpression);
    case 200 /* LiteralType */:
      const literal = typeNode.literal;
      switch (literal.kind) {
        case 11 /* StringLiteral */:
          return factory.createStringLiteral(literal.text, quotePreference === 0 /* Single */);
        case 9 /* NumericLiteral */:
          return factory.createNumericLiteral(literal.text, literal.numericLiteralFlags);
      }
      return void 0;
    case 195 /* ParenthesizedType */:
      const exp = typeNodeToExpression(typeNode.type, languageVersion, quotePreference);
      return exp && (isIdentifier(exp) ? exp : factory.createParenthesizedExpression(exp));
    case 185 /* TypeQuery */:
      return entityNameToExpression(typeNode.exprName, languageVersion, quotePreference);
    case 204 /* ImportType */:
      Debug.fail(`We should not get an import type after calling 'codefix.typeToAutoImportableTypeNode'.`);
  }
  return void 0;
}
function entityNameToExpression(entityName, languageVersion, quotePreference) {
  if (isIdentifier(entityName)) {
    return entityName;
  }
  const unescapedName = unescapeLeadingUnderscores(entityName.right.escapedText);
  if (canUsePropertyAccess(unescapedName, languageVersion)) {
    return factory.createPropertyAccessExpression(
      entityNameToExpression(entityName.left, languageVersion, quotePreference),
      unescapedName
    );
  } else {
    return factory.createElementAccessExpression(
      entityNameToExpression(entityName.left, languageVersion, quotePreference),
      factory.createStringLiteral(unescapedName, quotePreference === 0 /* Single */)
    );
  }
}
function isMemberCompletionKind(kind) {
  switch (kind) {
    case 0 /* ObjectPropertyDeclaration */:
    case 3 /* MemberLike */:
    case 2 /* PropertyAccess */:
      return true;
    default:
      return false;
  }
}
function getJsxClosingTagCompletion(location, sourceFile) {
  const jsxClosingElement = findAncestor(location, (node) => {
    switch (node.kind) {
      case 286 /* JsxClosingElement */:
        return true;
      case 44 /* SlashToken */:
      case 32 /* GreaterThanToken */:
      case 80 /* Identifier */:
      case 210 /* PropertyAccessExpression */:
        return false;
      default:
        return "quit";
    }
  });
  if (jsxClosingElement) {
    const hasClosingAngleBracket = !!findChildOfKind(jsxClosingElement, 32 /* GreaterThanToken */, sourceFile);
    const tagName = jsxClosingElement.parent.openingElement.tagName;
    const closingTag = tagName.getText(sourceFile);
    const fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">");
    const replacementSpan = createTextSpanFromNode(jsxClosingElement.tagName);
    const entry = {
      name: fullClosingTag,
      kind: "class" /* classElement */,
      kindModifiers: void 0,
      sortText: SortText.LocationPriority
    };
    return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] };
  }
  return;
}
function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) {
  getNameTable(sourceFile).forEach((pos, name) => {
    if (pos === position) {
      return;
    }
    const realName = unescapeLeadingUnderscores(name);
    if (!uniqueNames.has(realName) && isIdentifierText(realName, target)) {
      uniqueNames.add(realName);
      insertSorted(entries, {
        name: realName,
        kind: "warning" /* warning */,
        kindModifiers: "",
        sortText: SortText.JavascriptIdentifiers,
        isFromUncheckedFile: true
      }, compareCompletionEntries);
    }
  });
}
function completionNameForLiteral(sourceFile, preferences, literal) {
  return typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : isString(literal) ? quote(sourceFile, preferences, literal) : JSON.stringify(literal);
}
function createCompletionEntryForLiteral(sourceFile, preferences, literal) {
  return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority };
}
function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol) {
  let insertText;
  let replacementSpan = getReplacementSpanForContextToken(replacementToken);
  let data;
  let isSnippet;
  let source = getSourceFromOrigin(origin);
  let sourceDisplay;
  let hasAction;
  let labelDetails;
  const typeChecker = program.getTypeChecker();
  const insertQuestionDot = origin && originIsNullableMember(origin);
  const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
  if (origin && originIsThisType(origin)) {
    insertText = needsConvertPropertyAccess ? `this${insertQuestionDot ? "?." : ""}[${quotePropertyName(sourceFile, preferences, name)}]` : `this${insertQuestionDot ? "?." : "."}${name}`;
  } else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) {
    insertText = useBraces ? needsConvertPropertyAccess ? `[${quotePropertyName(sourceFile, preferences, name)}]` : `[${name}]` : name;
    if (insertQuestionDot || propertyAccessToConvert.questionDotToken) {
      insertText = `?.${insertText}`;
    }
    const dot = findChildOfKind(propertyAccessToConvert, 25 /* DotToken */, sourceFile) || findChildOfKind(propertyAccessToConvert, 29 /* QuestionDotToken */, sourceFile);
    if (!dot) {
      return void 0;
    }
    const end = startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end;
    replacementSpan = createTextSpanFromBounds(dot.getStart(sourceFile), end);
  }
  if (isJsxInitializer) {
    if (insertText === void 0)
      insertText = name;
    insertText = `{${insertText}}`;
    if (typeof isJsxInitializer !== "boolean") {
      replacementSpan = createTextSpanFromNode(isJsxInitializer, sourceFile);
    }
  }
  if (origin && originIsPromise(origin) && propertyAccessToConvert) {
    if (insertText === void 0)
      insertText = name;
    const precedingToken = findPrecedingToken(propertyAccessToConvert.pos, sourceFile);
    let awaitText = "";
    if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
      awaitText = ";";
    }
    awaitText += `(await ${propertyAccessToConvert.expression.getText()})`;
    insertText = needsConvertPropertyAccess ? `${awaitText}${insertText}` : `${awaitText}${insertQuestionDot ? "?." : "."}${insertText}`;
    const isInAwaitExpression = tryCast(propertyAccessToConvert.parent, isAwaitExpression);
    const wrapNode = isInAwaitExpression ? propertyAccessToConvert.parent : propertyAccessToConvert.expression;
    replacementSpan = createTextSpanFromBounds(wrapNode.getStart(sourceFile), propertyAccessToConvert.end);
  }
  if (originIsResolvedExport(origin)) {
    sourceDisplay = [textPart(origin.moduleSpecifier)];
    if (importStatementCompletion) {
      ({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences));
      isSnippet = preferences.includeCompletionsWithSnippetText ? true : void 0;
    }
  }
  if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) {
    hasAction = true;
  }
  if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* MemberLike */ && isClassLikeMemberCompletion(symbol, location, sourceFile)) {
    let importAdder;
    ({ insertText, isSnippet, importAdder, replacementSpan } = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext));
    sortText = SortText.ClassMemberSnippets;
    if (importAdder == null ? void 0 : importAdder.hasFixes()) {
      hasAction = true;
      source = "ClassMemberSnippet/" /* ClassMemberSnippet */;
    }
  }
  if (origin && originIsObjectLiteralMethod(origin)) {
    ({ insertText, isSnippet, labelDetails } = origin);
    if (!preferences.useLabelDetailsInCompletionEntries) {
      name = name + labelDetails.detail;
      labelDetails = void 0;
    }
    source = "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */;
    sortText = SortText.SortBelow(sortText);
  }
  if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer)) {
    let useBraces2 = preferences.jsxAttributeCompletionStyle === "braces";
    const type = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
    if (preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & 528 /* BooleanLike */) && !(type.flags & 1048576 /* Union */ && find(type.types, (type2) => !!(type2.flags & 528 /* BooleanLike */)))) {
      if (type.flags & 402653316 /* StringLike */ || type.flags & 1048576 /* Union */ && every(type.types, (type2) => !!(type2.flags & (402653316 /* StringLike */ | 32768 /* Undefined */) || isStringAndEmptyAnonymousObjectIntersection(type2)))) {
        insertText = `${escapeSnippetText(name)}=${quote(sourceFile, preferences, "$1")}`;
        isSnippet = true;
      } else {
        useBraces2 = true;
      }
    }
    if (useBraces2) {
      insertText = `${escapeSnippetText(name)}={$1}`;
      isSnippet = true;
    }
  }
  if (insertText !== void 0 && !preferences.includeCompletionsWithInsertText) {
    return void 0;
  }
  if (originIsExport(origin) || originIsResolvedExport(origin)) {
    data = originToCompletionEntryData(origin);
    hasAction = !importStatementCompletion;
  }
  return {
    name,
    kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location),
    kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol),
    sortText,
    source,
    hasAction: hasAction ? true : void 0,
    isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || void 0,
    insertText,
    replacementSpan,
    sourceDisplay,
    labelDetails,
    isSnippet,
    isPackageJsonImport: originIsPackageJsonImport(origin) || void 0,
    isImportStatementCompletion: !!importStatementCompletion || void 0,
    data,
    ...includeSymbol ? { symbol } : void 0
  };
}
function isClassLikeMemberCompletion(symbol, location, sourceFile) {
  if (isInJSFile(location)) {
    return false;
  }
  const memberFlags = 106500 /* ClassMember */ & 900095 /* EnumMemberExcludes */;
  return !!(symbol.flags & memberFlags) && (isClassLike(location) || location.parent && location.parent.parent && isClassElement(location.parent) && location === location.parent.name && location.parent.getLastToken(sourceFile) === location.parent.name && isClassLike(location.parent.parent) || location.parent && isSyntaxList(location) && isClassLike(location.parent));
}
function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext) {
  const classLikeDeclaration = findAncestor(location, isClassLike);
  if (!classLikeDeclaration) {
    return { insertText: name };
  }
  let isSnippet;
  let replacementSpan;
  let insertText = name;
  const checker = program.getTypeChecker();
  const sourceFile = location.getSourceFile();
  const printer = createSnippetPrinter({
    removeComments: true,
    module: options.module,
    target: options.target,
    omitTrailingSemicolon: false,
    newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options))
  });
  const importAdder = ts_codefix_exports.createImportAdder(sourceFile, program, preferences, host);
  let body;
  if (preferences.includeCompletionsWithSnippetText) {
    isSnippet = true;
    const emptyStmt = factory.createEmptyStatement();
    body = factory.createBlock(
      [emptyStmt],
      /*multiLine*/
      true
    );
    setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 });
  } else {
    body = factory.createBlock(
      [],
      /*multiLine*/
      true
    );
  }
  let modifiers = 0 /* None */;
  const { modifiers: presentModifiers, span: modifiersSpan } = getPresentModifiers(contextToken, sourceFile, position);
  const isAbstract = !!(presentModifiers & 256 /* Abstract */);
  const completionNodes = [];
  ts_codefix_exports.addNewNodeForMemberSymbol(
    symbol,
    classLikeDeclaration,
    sourceFile,
    { program, host },
    preferences,
    importAdder,
    // `addNewNodeForMemberSymbol` calls this callback function for each new member node
    // it adds for the given member symbol.
    // We store these member nodes in the `completionNodes` array.
    // Note: there might be:
    //  - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member;
    //  - One node;
    //  - More than one node if the member is overloaded (e.g. a method with overload signatures).
    (node) => {
      let requiredModifiers = 0 /* None */;
      if (isAbstract) {
        requiredModifiers |= 256 /* Abstract */;
      }
      if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */) {
        requiredModifiers |= 16384 /* Override */;
      }
      if (!completionNodes.length) {
        modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers;
      }
      node = factory.updateModifiers(node, modifiers);
      completionNodes.push(node);
    },
    body,
    ts_codefix_exports.PreserveOptionalFlags.Property,
    isAbstract
  );
  if (completionNodes.length) {
    const format = 1 /* MultiLine */ | 131072 /* NoTrailingNewLine */;
    replacementSpan = modifiersSpan;
    if (formatContext) {
      insertText = printer.printAndFormatSnippetList(
        format,
        factory.createNodeArray(completionNodes),
        sourceFile,
        formatContext
      );
    } else {
      insertText = printer.printSnippetList(
        format,
        factory.createNodeArray(completionNodes),
        sourceFile
      );
    }
  }
  return { insertText, isSnippet, importAdder, replacementSpan };
}
function getPresentModifiers(contextToken, sourceFile, position) {
  if (!contextToken || getLineAndCharacterOfPosition(sourceFile, position).line > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line) {
    return { modifiers: 0 /* None */ };
  }
  let modifiers = 0 /* None */;
  let span;
  let contextMod;
  if (contextMod = isModifierLike2(contextToken)) {
    modifiers |= modifierToFlag(contextMod);
    span = createTextSpanFromNode(contextToken);
  }
  if (isPropertyDeclaration(contextToken.parent)) {
    modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 126975 /* Modifier */;
    span = createTextSpanFromNode(contextToken.parent);
  }
  return { modifiers, span };
}
function isModifierLike2(node) {
  if (isModifier(node)) {
    return node.kind;
  }
  if (isIdentifier(node)) {
    const originalKeywordKind = identifierToKeywordKind(node);
    if (originalKeywordKind && isModifierKind(originalKeywordKind)) {
      return originalKeywordKind;
    }
  }
  return void 0;
}
function getEntryForObjectLiteralMethodCompletion(symbol, name, enclosingDeclaration, program, host, options, preferences, formatContext) {
  const isSnippet = preferences.includeCompletionsWithSnippetText || void 0;
  let insertText = name;
  const sourceFile = enclosingDeclaration.getSourceFile();
  const method = createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences);
  if (!method) {
    return void 0;
  }
  const printer = createSnippetPrinter({
    removeComments: true,
    module: options.module,
    target: options.target,
    omitTrailingSemicolon: false,
    newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options))
  });
  if (formatContext) {
    insertText = printer.printAndFormatSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray(
      [method],
      /*hasTrailingComma*/
      true
    ), sourceFile, formatContext);
  } else {
    insertText = printer.printSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray(
      [method],
      /*hasTrailingComma*/
      true
    ), sourceFile);
  }
  const signaturePrinter = createPrinter({
    removeComments: true,
    module: options.module,
    target: options.target,
    omitTrailingSemicolon: true
  });
  const methodSignature = factory.createMethodSignature(
    /*modifiers*/
    void 0,
    /*name*/
    "",
    method.questionToken,
    method.typeParameters,
    method.parameters,
    method.type
  );
  const labelDetails = { detail: signaturePrinter.printNode(4 /* Unspecified */, methodSignature, sourceFile) };
  return { isSnippet, insertText, labelDetails };
}
function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences) {
  const declarations = symbol.getDeclarations();
  if (!(declarations && declarations.length)) {
    return void 0;
  }
  const checker = program.getTypeChecker();
  const declaration = declarations[0];
  const name = getSynthesizedDeepClone(
    getNameOfDeclaration(declaration),
    /*includeTrivia*/
    false
  );
  const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
  const quotePreference = getQuotePreference(sourceFile, preferences);
  const builderFlags = 33554432 /* OmitThisParameter */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */);
  switch (declaration.kind) {
    case 170 /* PropertySignature */:
    case 171 /* PropertyDeclaration */:
    case 172 /* MethodSignature */:
    case 173 /* MethodDeclaration */: {
      let effectiveType = type.flags & 1048576 /* Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* Subtype */) : type;
      if (effectiveType.flags & 1048576 /* Union */) {
        const functionTypes = filter(effectiveType.types, (type2) => checker.getSignaturesOfType(type2, 0 /* Call */).length > 0);
        if (functionTypes.length === 1) {
          effectiveType = functionTypes[0];
        } else {
          return void 0;
        }
      }
      const signatures = checker.getSignaturesOfType(effectiveType, 0 /* Call */);
      if (signatures.length !== 1) {
        return void 0;
      }
      const typeNode = checker.typeToTypeNode(effectiveType, enclosingDeclaration, builderFlags, ts_codefix_exports.getNoopSymbolTrackerWithResolver({ program, host }));
      if (!typeNode || !isFunctionTypeNode(typeNode)) {
        return void 0;
      }
      let body;
      if (preferences.includeCompletionsWithSnippetText) {
        const emptyStmt = factory.createEmptyStatement();
        body = factory.createBlock(
          [emptyStmt],
          /*multiLine*/
          true
        );
        setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 });
      } else {
        body = factory.createBlock(
          [],
          /*multiLine*/
          true
        );
      }
      const parameters = typeNode.parameters.map((typedParam) => factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        typedParam.dotDotDotToken,
        typedParam.name,
        /*questionToken*/
        void 0,
        /*type*/
        void 0,
        typedParam.initializer
      ));
      return factory.createMethodDeclaration(
        /*modifiers*/
        void 0,
        /*asteriskToken*/
        void 0,
        name,
        /*questionToken*/
        void 0,
        /*typeParameters*/
        void 0,
        parameters,
        /*type*/
        void 0,
        body
      );
    }
    default:
      return void 0;
  }
}
function createSnippetPrinter(printerOptions) {
  let escapes;
  const baseWriter = ts_textChanges_exports.createWriter(getNewLineCharacter(printerOptions));
  const printer = createPrinter(printerOptions, baseWriter);
  const writer = {
    ...baseWriter,
    write: (s) => escapingWrite(s, () => baseWriter.write(s)),
    nonEscapingWrite: baseWriter.write,
    writeLiteral: (s) => escapingWrite(s, () => baseWriter.writeLiteral(s)),
    writeStringLiteral: (s) => escapingWrite(s, () => baseWriter.writeStringLiteral(s)),
    writeSymbol: (s, symbol) => escapingWrite(s, () => baseWriter.writeSymbol(s, symbol)),
    writeParameter: (s) => escapingWrite(s, () => baseWriter.writeParameter(s)),
    writeComment: (s) => escapingWrite(s, () => baseWriter.writeComment(s)),
    writeProperty: (s) => escapingWrite(s, () => baseWriter.writeProperty(s))
  };
  return {
    printSnippetList,
    printAndFormatSnippetList,
    printNode,
    printAndFormatNode
  };
  function escapingWrite(s, write) {
    const escaped = escapeSnippetText(s);
    if (escaped !== s) {
      const start2 = baseWriter.getTextPos();
      write();
      const end = baseWriter.getTextPos();
      escapes = append(escapes || (escapes = []), { newText: escaped, span: { start: start2, length: end - start2 } });
    } else {
      write();
    }
  }
  function printSnippetList(format, list, sourceFile) {
    const unescaped = printUnescapedSnippetList(format, list, sourceFile);
    return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped;
  }
  function printUnescapedSnippetList(format, list, sourceFile) {
    escapes = void 0;
    writer.clear();
    printer.writeList(format, list, sourceFile, writer);
    return writer.getText();
  }
  function printAndFormatSnippetList(format, list, sourceFile, formatContext) {
    const syntheticFile = {
      text: printUnescapedSnippetList(
        format,
        list,
        sourceFile
      ),
      getLineAndCharacterOfPosition(pos) {
        return getLineAndCharacterOfPosition(this, pos);
      }
    };
    const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
    const changes = flatMap(list, (node) => {
      const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node);
      return ts_formatting_exports.formatNodeGivenIndentation(
        nodeWithPos,
        syntheticFile,
        sourceFile.languageVariant,
        /* indentation */
        0,
        /* delta */
        0,
        { ...formatContext, options: formatOptions }
      );
    });
    const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes;
    return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges);
  }
  function printNode(hint, node, sourceFile) {
    const unescaped = printUnescapedNode(hint, node, sourceFile);
    return escapes ? ts_textChanges_exports.applyChanges(unescaped, escapes) : unescaped;
  }
  function printUnescapedNode(hint, node, sourceFile) {
    escapes = void 0;
    writer.clear();
    printer.writeNode(hint, node, sourceFile, writer);
    return writer.getText();
  }
  function printAndFormatNode(hint, node, sourceFile, formatContext) {
    const syntheticFile = {
      text: printUnescapedNode(
        hint,
        node,
        sourceFile
      ),
      getLineAndCharacterOfPosition(pos) {
        return getLineAndCharacterOfPosition(this, pos);
      }
    };
    const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
    const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node);
    const changes = ts_formatting_exports.formatNodeGivenIndentation(
      nodeWithPos,
      syntheticFile,
      sourceFile.languageVariant,
      /* indentation */
      0,
      /* delta */
      0,
      { ...formatContext, options: formatOptions }
    );
    const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes;
    return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges);
  }
}
function originToCompletionEntryData(origin) {
  const ambientModuleName = origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name);
  const isPackageJsonImport = origin.isFromPackageJson ? true : void 0;
  if (originIsResolvedExport(origin)) {
    const resolvedData = {
      exportName: origin.exportName,
      exportMapKey: origin.exportMapKey,
      moduleSpecifier: origin.moduleSpecifier,
      ambientModuleName,
      fileName: origin.fileName,
      isPackageJsonImport
    };
    return resolvedData;
  }
  const unresolvedData = {
    exportName: origin.exportName,
    exportMapKey: origin.exportMapKey,
    fileName: origin.fileName,
    ambientModuleName: origin.fileName ? void 0 : stripQuotes(origin.moduleSymbol.name),
    isPackageJsonImport: origin.isFromPackageJson ? true : void 0
  };
  return unresolvedData;
}
function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) {
  const isDefaultExport = data.exportName === "default" /* Default */;
  const isFromPackageJson = !!data.isPackageJsonImport;
  if (completionEntryDataIsResolved(data)) {
    const resolvedOrigin = {
      kind: 32 /* ResolvedExport */,
      exportName: data.exportName,
      exportMapKey: data.exportMapKey,
      moduleSpecifier: data.moduleSpecifier,
      symbolName: completionName,
      fileName: data.fileName,
      moduleSymbol,
      isDefaultExport,
      isFromPackageJson
    };
    return resolvedOrigin;
  }
  const unresolvedOrigin = {
    kind: 4 /* Export */,
    exportName: data.exportName,
    exportMapKey: data.exportMapKey,
    symbolName: completionName,
    fileName: data.fileName,
    moduleSymbol,
    isDefaultExport,
    isFromPackageJson
  };
  return unresolvedOrigin;
}
function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences) {
  const replacementSpan = importStatementCompletion.replacementSpan;
  const quotedModuleSpecifier = escapeSnippetText(quote(sourceFile, preferences, origin.moduleSpecifier));
  const exportKind = origin.isDefaultExport ? 1 /* Default */ : origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : 0 /* Named */;
  const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : "";
  const importKind = ts_codefix_exports.getImportKind(
    sourceFile,
    exportKind,
    options,
    /*forceImportKeyword*/
    true
  );
  const isImportSpecifierTypeOnly = importStatementCompletion.couldBeTypeOnlyImportSpecifier;
  const topLevelTypeOnlyText = importStatementCompletion.isTopLevelTypeOnly ? ` ${tokenToString(156 /* TypeKeyword */)} ` : " ";
  const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(156 /* TypeKeyword */)} ` : "";
  const suffix = useSemicolons ? ";" : "";
  switch (importKind) {
    case 3 /* CommonJS */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` };
    case 1 /* Default */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` };
    case 2 /* Namespace */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` };
    case 0 /* Named */:
      return { replacementSpan, insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` };
  }
}
function quotePropertyName(sourceFile, preferences, name) {
  if (/^\d+$/.test(name)) {
    return name;
  }
  return quote(sourceFile, preferences, name);
}
function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) {
  return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion;
}
function getSourceFromOrigin(origin) {
  if (originIsExport(origin)) {
    return stripQuotes(origin.moduleSymbol.name);
  }
  if (originIsResolvedExport(origin)) {
    return origin.moduleSpecifier;
  }
  if ((origin == null ? void 0 : origin.kind) === 1 /* ThisType */) {
    return "ThisProperty/" /* ThisProperty */;
  }
  if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) {
    return "TypeOnlyAlias/" /* TypeOnlyAlias */;
  }
}
function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, position, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) {
  const start2 = timestamp();
  const variableOrParameterDeclaration = getVariableOrParameterDeclaration(contextToken, location);
  const useSemicolons = probablyUsesSemicolons(sourceFile);
  const typeChecker = program.getTypeChecker();
  const uniques = /* @__PURE__ */ new Map();
  for (let i = 0; i < symbols.length; i++) {
    const symbol = symbols[i];
    const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i];
    const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected);
    if (!info || uniques.get(info.name) && (!origin || !originIsObjectLiteralMethod(origin)) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) {
      continue;
    }
    const { name, needsConvertPropertyAccess } = info;
    const originalSortText = (symbolToSortTextMap == null ? void 0 : symbolToSortTextMap[getSymbolId(symbol)]) ?? SortText.LocationPriority;
    const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText;
    const entry = createCompletionEntry(
      symbol,
      sortText,
      replacementToken,
      contextToken,
      location,
      position,
      sourceFile,
      host,
      program,
      name,
      needsConvertPropertyAccess,
      origin,
      recommendedCompletion,
      propertyAccessToConvert,
      isJsxInitializer,
      importStatementCompletion,
      useSemicolons,
      compilerOptions,
      preferences,
      kind,
      formatContext,
      isJsxIdentifierExpected,
      isRightOfOpenTag,
      includeSymbol
    );
    if (!entry) {
      continue;
    }
    const shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === void 0 && !some(symbol.declarations, (d) => d.getSourceFile() === location.getSourceFile()));
    uniques.set(name, shouldShadowLaterSymbols);
    insertSorted(
      entries,
      entry,
      compareCompletionEntries,
      /*allowDuplicates*/
      true
    );
  }
  log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start2));
  return {
    has: (name) => uniques.has(name),
    add: (name) => uniques.set(name, true)
  };
  function shouldIncludeSymbol(symbol, symbolToSortTextMap2) {
    var _a;
    let allFlags = symbol.flags;
    if (!isSourceFile(location)) {
      if (isExportAssignment(location.parent)) {
        return true;
      }
      if (tryCast(variableOrParameterDeclaration, isVariableDeclaration) && symbol.valueDeclaration === variableOrParameterDeclaration) {
        return false;
      }
      const symbolDeclaration = symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]);
      if (variableOrParameterDeclaration && symbolDeclaration && (isTypeParameterDeclaration(variableOrParameterDeclaration) && isTypeParameterDeclaration(symbolDeclaration) || isParameter(variableOrParameterDeclaration) && isParameter(symbolDeclaration))) {
        const symbolDeclarationPos = symbolDeclaration.pos;
        const parameters = isParameter(variableOrParameterDeclaration) ? variableOrParameterDeclaration.parent.parameters : isInferTypeNode(variableOrParameterDeclaration.parent) ? void 0 : variableOrParameterDeclaration.parent.typeParameters;
        if (symbolDeclarationPos >= variableOrParameterDeclaration.pos && parameters && symbolDeclarationPos < parameters.end) {
          return false;
        }
      }
      const symbolOrigin = skipAlias(symbol, typeChecker);
      if (!!sourceFile.externalModuleIndicator && !compilerOptions.allowUmdGlobalAccess && symbolToSortTextMap2[getSymbolId(symbol)] === SortText.GlobalsOrKeywords && (symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions || symbolToSortTextMap2[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) {
        return false;
      }
      allFlags |= getCombinedLocalAndExportSymbolFlags(symbolOrigin);
      if (isInRightSideOfInternalImportEqualsDeclaration(location)) {
        return !!(allFlags & 1920 /* Namespace */);
      }
      if (isTypeOnlyLocation) {
        return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker);
      }
    }
    return !!(allFlags & 111551 /* Value */);
  }
}
function getLabelCompletionAtPosition(node) {
  const entries = getLabelStatementCompletions(node);
  if (entries.length) {
    return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries };
  }
}
function getLabelStatementCompletions(node) {
  const entries = [];
  const uniques = /* @__PURE__ */ new Map();
  let current = node;
  while (current) {
    if (isFunctionLike(current)) {
      break;
    }
    if (isLabeledStatement(current)) {
      const name = current.label.text;
      if (!uniques.has(name)) {
        uniques.set(name, true);
        entries.push({
          name,
          kindModifiers: "" /* none */,
          kind: "label" /* label */,
          sortText: SortText.LocationPriority
        });
      }
    }
    current = current.parent;
  }
  return entries;
}
function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) {
  if (entryId.source === "SwitchCases/" /* SwitchCases */) {
    return { type: "cases" };
  }
  if (entryId.data) {
    const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host);
    if (autoImport) {
      const { contextToken: contextToken2, previousToken: previousToken2 } = getRelevantTokens(position, sourceFile);
      return {
        type: "symbol",
        symbol: autoImport.symbol,
        location: getTouchingPropertyName(sourceFile, position),
        previousToken: previousToken2,
        contextToken: contextToken2,
        isJsxInitializer: false,
        isTypeOnlyLocation: false,
        origin: autoImport.origin
      };
    }
  }
  const compilerOptions = program.getCompilerOptions();
  const completionData = getCompletionData(
    program,
    log,
    sourceFile,
    compilerOptions,
    position,
    { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true },
    entryId,
    host,
    /*formatContext*/
    void 0
  );
  if (!completionData) {
    return { type: "none" };
  }
  if (completionData.kind !== 0 /* Data */) {
    return { type: "request", request: completionData };
  }
  const { symbols, literals, location, completionKind, symbolToOriginInfoMap, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } = completionData;
  const literal = find(literals, (l) => completionNameForLiteral(sourceFile, preferences, l) === entryId.name);
  if (literal !== void 0)
    return { type: "literal", literal };
  return firstDefined(symbols, (symbol, index) => {
    const origin = symbolToOriginInfoMap[index];
    const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected);
    return info && info.name === entryId.name && (entryId.source === "ClassMemberSnippet/" /* ClassMemberSnippet */ && symbol.flags & 106500 /* ClassMember */ || entryId.source === "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ && symbol.flags & (4 /* Property */ | 8192 /* Method */) || getSourceFromOrigin(origin) === entryId.source) ? { type: "symbol", symbol, location, origin, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } : void 0;
  }) || { type: "none" };
}
function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  const { name, source, data } = entryId;
  const { previousToken, contextToken } = getRelevantTokens(position, sourceFile);
  if (isInString(sourceFile, position, previousToken)) {
    return ts_Completions_StringCompletions_exports.getStringLiteralCompletionDetails(name, sourceFile, position, previousToken, typeChecker, compilerOptions, host, cancellationToken, preferences);
  }
  const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
  switch (symbolCompletion.type) {
    case "request": {
      const { request } = symbolCompletion;
      switch (request.kind) {
        case 1 /* JsDocTagName */:
          return ts_JsDoc_exports.getJSDocTagNameCompletionDetails(name);
        case 2 /* JsDocTag */:
          return ts_JsDoc_exports.getJSDocTagCompletionDetails(name);
        case 3 /* JsDocParameterName */:
          return ts_JsDoc_exports.getJSDocParameterNameCompletionDetails(name);
        case 4 /* Keywords */:
          return some(request.keywordCompletions, (c) => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0;
        default:
          return Debug.assertNever(request);
      }
    }
    case "symbol": {
      const { symbol, location, contextToken: contextToken2, origin, previousToken: previousToken2 } = symbolCompletion;
      const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken2, formatContext, preferences, data, source, cancellationToken);
      const symbolName2 = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name;
      return createCompletionDetailsForSymbol(symbol, symbolName2, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay);
    }
    case "literal": {
      const { literal } = symbolCompletion;
      return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */, typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */);
    }
    case "cases": {
      const { entry, importAdder } = getExhaustiveCaseSnippets(
        contextToken.parent,
        sourceFile,
        preferences,
        program.getCompilerOptions(),
        host,
        program,
        /*formatContext*/
        void 0
      );
      if (importAdder.hasFixes()) {
        const changes = ts_textChanges_exports.ChangeTracker.with(
          { host, formatContext, preferences },
          importAdder.writeFixes
        );
        return {
          name: entry.name,
          kind: "" /* unknown */,
          kindModifiers: "",
          displayParts: [],
          sourceDisplay: void 0,
          codeActions: [{
            changes,
            description: diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name])
          }]
        };
      }
      return {
        name: entry.name,
        kind: "" /* unknown */,
        kindModifiers: "",
        displayParts: [],
        sourceDisplay: void 0
      };
    }
    case "none":
      return allKeywordsCompletions().some((c) => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0;
    default:
      Debug.assertNever(symbolCompletion);
  }
}
function createSimpleDetails(name, kind, kind2) {
  return createCompletionDetails(name, "" /* none */, kind, [displayPart(name, kind2)]);
}
function createCompletionDetailsForSymbol(symbol, name, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) {
  const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(
    cancellationToken,
    (checker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */)
  );
  return createCompletionDetails(name, ts_SymbolDisplay_exports.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
}
function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
  return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source, sourceDisplay: source };
}
function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) {
  if (data == null ? void 0 : data.moduleSpecifier) {
    if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementSpan) {
      return { codeActions: void 0, sourceDisplay: [textPart(data.moduleSpecifier)] };
    }
  }
  if (source === "ClassMemberSnippet/" /* ClassMemberSnippet */) {
    const { importAdder } = getEntryForMemberCompletion(
      host,
      program,
      compilerOptions,
      preferences,
      name,
      symbol,
      location,
      position,
      contextToken,
      formatContext
    );
    if (importAdder) {
      const changes = ts_textChanges_exports.ChangeTracker.with(
        { host, formatContext, preferences },
        importAdder.writeFixes
      );
      return {
        sourceDisplay: void 0,
        codeActions: [{
          changes,
          description: diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name])
        }]
      };
    }
  }
  if (originIsTypeOnlyAlias(origin)) {
    const codeAction2 = ts_codefix_exports.getPromoteTypeOnlyCompletionAction(
      sourceFile,
      origin.declaration.name,
      program,
      host,
      formatContext,
      preferences
    );
    Debug.assertIsDefined(codeAction2, "Expected to have a code action for promoting type-only alias");
    return { codeActions: [codeAction2], sourceDisplay: void 0 };
  }
  if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) {
    return { codeActions: void 0, sourceDisplay: void 0 };
  }
  const checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker();
  const { moduleSymbol } = origin;
  const targetSymbol = checker.getMergedSymbol(skipAlias(symbol.exportSymbol || symbol, checker));
  const isJsxOpeningTagName = (contextToken == null ? void 0 : contextToken.kind) === 30 /* LessThanToken */ && isJsxOpeningLikeElement(contextToken.parent);
  const { moduleSpecifier, codeAction } = ts_codefix_exports.getImportCompletionAction(
    targetSymbol,
    moduleSymbol,
    data == null ? void 0 : data.exportMapKey,
    sourceFile,
    name,
    isJsxOpeningTagName,
    host,
    program,
    formatContext,
    previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position,
    preferences,
    cancellationToken
  );
  Debug.assert(!(data == null ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier);
  return { sourceDisplay: [textPart(moduleSpecifier)], codeActions: [codeAction] };
}
function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) {
  const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
  return completion.type === "symbol" ? completion.symbol : void 0;
}
var CompletionKind = /* @__PURE__ */ ((CompletionKind2) => {
  CompletionKind2[CompletionKind2["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
  CompletionKind2[CompletionKind2["Global"] = 1] = "Global";
  CompletionKind2[CompletionKind2["PropertyAccess"] = 2] = "PropertyAccess";
  CompletionKind2[CompletionKind2["MemberLike"] = 3] = "MemberLike";
  CompletionKind2[CompletionKind2["String"] = 4] = "String";
  CompletionKind2[CompletionKind2["None"] = 5] = "None";
  return CompletionKind2;
})(CompletionKind || {});
function getRecommendedCompletion(previousToken, contextualType, checker) {
  return firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), (type) => {
    const symbol = type && type.symbol;
    return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, previousToken, checker) : void 0;
  });
}
function getContextualType(previousToken, position, sourceFile, checker) {
  const { parent: parent2 } = previousToken;
  switch (previousToken.kind) {
    case 80 /* Identifier */:
      return getContextualTypeFromParent(previousToken, checker);
    case 64 /* EqualsToken */:
      switch (parent2.kind) {
        case 259 /* VariableDeclaration */:
          return checker.getContextualType(parent2.initializer);
        case 225 /* BinaryExpression */:
          return checker.getTypeAtLocation(parent2.left);
        case 290 /* JsxAttribute */:
          return checker.getContextualTypeForJsxAttribute(parent2);
        default:
          return void 0;
      }
    case 105 /* NewKeyword */:
      return checker.getContextualType(parent2);
    case 84 /* CaseKeyword */:
      const caseClause = tryCast(parent2, isCaseClause);
      return caseClause ? getSwitchedType(caseClause, checker) : void 0;
    case 19 /* OpenBraceToken */:
      return isJsxExpression(parent2) && !isJsxElement(parent2.parent) && !isJsxFragment(parent2.parent) ? checker.getContextualTypeForJsxAttribute(parent2.parent) : void 0;
    default:
      const argInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(previousToken, position, sourceFile);
      return argInfo ? (
        // At `,`, treat this as the next argument after the comma.
        checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 28 /* CommaToken */ ? 1 : 0))
      ) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? (
        // completion at `x ===/**/` should be for the right side
        checker.getTypeAtLocation(parent2.left)
      ) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken);
  }
}
function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) {
  const chain = checker.getAccessibleSymbolChain(
    symbol,
    enclosingDeclaration,
    /*meaning*/
    67108863 /* All */,
    /*useOnlyExternalAliasing*/
    false
  );
  if (chain)
    return first(chain);
  return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
  var _a;
  return !!((_a = symbol.declarations) == null ? void 0 : _a.some((d) => d.kind === 311 /* SourceFile */));
}
function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  const inCheckedFile = isCheckedFile(sourceFile, compilerOptions);
  let start2 = timestamp();
  let currentToken = getTokenAtPosition(sourceFile, position);
  log("getCompletionData: Get current token: " + (timestamp() - start2));
  start2 = timestamp();
  const insideComment = isInComment(sourceFile, position, currentToken);
  log("getCompletionData: Is inside comment: " + (timestamp() - start2));
  let insideJsDocTagTypeExpression = false;
  let isInSnippetScope = false;
  if (insideComment) {
    if (hasDocComment(sourceFile, position)) {
      if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
        return { kind: 1 /* JsDocTagName */ };
      } else {
        const lineStart = getLineStartPositionForPosition(position, sourceFile);
        if (!/[^\*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) {
          return { kind: 2 /* JsDocTag */ };
        }
      }
    }
    const tag = getJsDocTagAtPosition(currentToken, position);
    if (tag) {
      if (tag.tagName.pos <= position && position <= tag.tagName.end) {
        return { kind: 1 /* JsDocTagName */ };
      }
      const typeExpression = tryGetTypeExpressionFromTag(tag);
      if (typeExpression) {
        currentToken = getTokenAtPosition(sourceFile, position);
        if (!currentToken || !isDeclarationName(currentToken) && (currentToken.parent.kind !== 354 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken)) {
          insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression);
        }
      }
      if (!insideJsDocTagTypeExpression && isJSDocParameterTag(tag) && (nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
        return { kind: 3 /* JsDocParameterName */, tag };
      }
    }
    if (!insideJsDocTagTypeExpression) {
      log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
      return void 0;
    }
  }
  start2 = timestamp();
  const isJsOnlyLocation = !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile);
  const tokens = getRelevantTokens(position, sourceFile);
  const previousToken = tokens.previousToken;
  let contextToken = tokens.contextToken;
  log("getCompletionData: Get previous token: " + (timestamp() - start2));
  let node = currentToken;
  let propertyAccessToConvert;
  let isRightOfDot = false;
  let isRightOfQuestionDot = false;
  let isRightOfOpenTag = false;
  let isStartingCloseTag = false;
  let isJsxInitializer = false;
  let isJsxIdentifierExpected = false;
  let importStatementCompletion;
  let location = getTouchingPropertyName(sourceFile, position);
  let keywordFilters = 0 /* None */;
  let isNewIdentifierLocation = false;
  let flags = 0 /* None */;
  if (contextToken) {
    const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken);
    if (importStatementCompletionInfo.keywordCompletion) {
      if (importStatementCompletionInfo.isKeywordOnlyCompletion) {
        return {
          kind: 4 /* Keywords */,
          keywordCompletions: [keywordToCompletionEntry(importStatementCompletionInfo.keywordCompletion)],
          isNewIdentifierLocation: importStatementCompletionInfo.isNewIdentifierLocation
        };
      }
      keywordFilters = keywordFiltersFromSyntaxKind(importStatementCompletionInfo.keywordCompletion);
    }
    if (importStatementCompletionInfo.replacementSpan && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) {
      flags |= 2 /* IsImportStatementCompletion */;
      importStatementCompletion = importStatementCompletionInfo;
      isNewIdentifierLocation = importStatementCompletionInfo.isNewIdentifierLocation;
    }
    if (!importStatementCompletionInfo.replacementSpan && isCompletionListBlocker(contextToken)) {
      log("Returning an empty list because completion was requested in an invalid position.");
      return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierDefinitionLocation()) : void 0;
    }
    let parent2 = contextToken.parent;
    if (contextToken.kind === 25 /* DotToken */ || contextToken.kind === 29 /* QuestionDotToken */) {
      isRightOfDot = contextToken.kind === 25 /* DotToken */;
      isRightOfQuestionDot = contextToken.kind === 29 /* QuestionDotToken */;
      switch (parent2.kind) {
        case 210 /* PropertyAccessExpression */:
          propertyAccessToConvert = parent2;
          node = propertyAccessToConvert.expression;
          const leftmostAccessExpression = getLeftmostAccessExpression(propertyAccessToConvert);
          if (nodeIsMissing(leftmostAccessExpression) || (isCallExpression(node) || isFunctionLike(node)) && node.end === contextToken.pos && node.getChildCount(sourceFile) && last(node.getChildren(sourceFile)).kind !== 22 /* CloseParenToken */) {
            return void 0;
          }
          break;
        case 165 /* QualifiedName */:
          node = parent2.left;
          break;
        case 266 /* ModuleDeclaration */:
          node = parent2.name;
          break;
        case 204 /* ImportType */:
          node = parent2;
          break;
        case 235 /* MetaProperty */:
          node = parent2.getFirstToken(sourceFile);
          Debug.assert(node.kind === 102 /* ImportKeyword */ || node.kind === 105 /* NewKeyword */);
          break;
        default:
          return void 0;
      }
    } else if (!importStatementCompletion) {
      if (parent2 && parent2.kind === 210 /* PropertyAccessExpression */) {
        contextToken = parent2;
        parent2 = parent2.parent;
      }
      if (currentToken.parent === location) {
        switch (currentToken.kind) {
          case 32 /* GreaterThanToken */:
            if (currentToken.parent.kind === 283 /* JsxElement */ || currentToken.parent.kind === 285 /* JsxOpeningElement */) {
              location = currentToken;
            }
            break;
          case 44 /* SlashToken */:
            if (currentToken.parent.kind === 284 /* JsxSelfClosingElement */) {
              location = currentToken;
            }
            break;
        }
      }
      switch (parent2.kind) {
        case 286 /* JsxClosingElement */:
          if (contextToken.kind === 44 /* SlashToken */) {
            isStartingCloseTag = true;
            location = contextToken;
          }
          break;
        case 225 /* BinaryExpression */:
          if (!binaryExpressionMayBeOpenTag(parent2)) {
            break;
          }
        case 284 /* JsxSelfClosingElement */:
        case 283 /* JsxElement */:
        case 285 /* JsxOpeningElement */:
          isJsxIdentifierExpected = true;
          if (contextToken.kind === 30 /* LessThanToken */) {
            isRightOfOpenTag = true;
            location = contextToken;
          }
          break;
        case 293 /* JsxExpression */:
        case 292 /* JsxSpreadAttribute */:
          if (previousToken.kind === 20 /* CloseBraceToken */ || previousToken.kind === 80 /* Identifier */ && previousToken.parent.kind === 290 /* JsxAttribute */) {
            isJsxIdentifierExpected = true;
          }
          break;
        case 290 /* JsxAttribute */:
          if (parent2.initializer === previousToken && previousToken.end < position) {
            isJsxIdentifierExpected = true;
            break;
          }
          switch (previousToken.kind) {
            case 64 /* EqualsToken */:
              isJsxInitializer = true;
              break;
            case 80 /* Identifier */:
              isJsxIdentifierExpected = true;
              if (parent2 !== previousToken.parent && !parent2.initializer && findChildOfKind(parent2, 64 /* EqualsToken */, sourceFile)) {
                isJsxInitializer = previousToken;
              }
          }
          break;
      }
    }
  }
  const semanticStart = timestamp();
  let completionKind = 5 /* None */;
  let isNonContextualObjectLiteral = false;
  let hasUnresolvedAutoImports = false;
  let symbols = [];
  let importSpecifierResolver;
  const symbolToOriginInfoMap = [];
  const symbolToSortTextMap = [];
  const seenPropertySymbols = /* @__PURE__ */ new Map();
  const isTypeOnlyLocation = isTypeOnlyCompletion();
  const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => {
    return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host);
  });
  if (isRightOfDot || isRightOfQuestionDot) {
    getTypeScriptMemberSymbols();
  } else if (isRightOfOpenTag) {
    symbols = typeChecker.getJsxIntrinsicTagNamesAt(location);
    Debug.assertEachIsDefined(symbols, "getJsxIntrinsicTagNames() should all be defined");
    tryGetGlobalSymbols();
    completionKind = 1 /* Global */;
    keywordFilters = 0 /* None */;
  } else if (isStartingCloseTag) {
    const tagName = contextToken.parent.parent.openingElement.tagName;
    const tagSymbol = typeChecker.getSymbolAtLocation(tagName);
    if (tagSymbol) {
      symbols = [tagSymbol];
    }
    completionKind = 1 /* Global */;
    keywordFilters = 0 /* None */;
  } else {
    if (!tryGetGlobalSymbols()) {
      return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierLocation) : void 0;
    }
  }
  log("getCompletionData: Semantic work: " + (timestamp() - semanticStart));
  const contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
  const isLiteralExpected = !tryCast(previousToken, isStringLiteralLike) && !isJsxIdentifierExpected;
  const literals = !isLiteralExpected ? [] : mapDefined(
    contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]),
    (t) => t.isLiteral() && !(t.flags & 1024 /* EnumLiteral */) ? t.value : void 0
  );
  const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
  return {
    kind: 0 /* Data */,
    symbols,
    completionKind,
    isInSnippetScope,
    propertyAccessToConvert,
    isNewIdentifierLocation,
    location,
    keywordFilters,
    literals,
    symbolToOriginInfoMap,
    recommendedCompletion,
    previousToken,
    contextToken,
    isJsxInitializer,
    insideJsDocTagTypeExpression,
    symbolToSortTextMap,
    isTypeOnlyLocation,
    isJsxIdentifierExpected,
    isRightOfOpenTag,
    isRightOfDotOrQuestionDot: isRightOfDot || isRightOfQuestionDot,
    importStatementCompletion,
    hasUnresolvedAutoImports,
    flags
  };
  function isTagWithTypeExpression(tag) {
    switch (tag.kind) {
      case 347 /* JSDocParameterTag */:
      case 354 /* JSDocPropertyTag */:
      case 348 /* JSDocReturnTag */:
      case 350 /* JSDocTypeTag */:
      case 352 /* JSDocTypedefTag */:
      case 355 /* JSDocThrowsTag */:
      case 356 /* JSDocSatisfiesTag */:
        return true;
      case 351 /* JSDocTemplateTag */:
        return !!tag.constraint;
      default:
        return false;
    }
  }
  function tryGetTypeExpressionFromTag(tag) {
    if (isTagWithTypeExpression(tag)) {
      const typeExpression = isJSDocTemplateTag(tag) ? tag.constraint : tag.typeExpression;
      return typeExpression && typeExpression.kind === 315 /* JSDocTypeExpression */ ? typeExpression : void 0;
    }
    if (isJSDocAugmentsTag(tag) || isJSDocImplementsTag(tag)) {
      return tag.class;
    }
    return void 0;
  }
  function getTypeScriptMemberSymbols() {
    completionKind = 2 /* PropertyAccess */;
    const isImportType = isLiteralImportTypeNode(node);
    const isTypeLocation = isImportType && !node.isTypeOf || isPartOfTypeNode(node.parent) || isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
    const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node);
    if (isEntityName(node) || isImportType || isPropertyAccessExpression(node)) {
      const isNamespaceName = isModuleDeclaration(node.parent);
      if (isNamespaceName)
        isNewIdentifierLocation = true;
      let symbol = typeChecker.getSymbolAtLocation(node);
      if (symbol) {
        symbol = skipAlias(symbol, typeChecker);
        if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) {
          const exportedSymbols = typeChecker.getExportsOfModule(symbol);
          Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined");
          const isValidValueAccess = (symbol2) => typeChecker.isValidPropertyAccess(isImportType ? node : node.parent, symbol2.name);
          const isValidTypeAccess = (symbol2) => symbolCanBeReferencedAtTypeLocation(symbol2, typeChecker);
          const isValidAccess = isNamespaceName ? (symbol2) => {
            var _a;
            return !!(symbol2.flags & 1920 /* Namespace */) && !((_a = symbol2.declarations) == null ? void 0 : _a.every((d) => d.parent === node.parent));
          } : isRhsOfImportDeclaration ? (
            // Any kind is allowed when dotting off namespace in internal import equals declaration
            (symbol2) => isValidTypeAccess(symbol2) || isValidValueAccess(symbol2)
          ) : isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess;
          for (const exportedSymbol of exportedSymbols) {
            if (isValidAccess(exportedSymbol)) {
              symbols.push(exportedSymbol);
            }
          }
          if (!isTypeLocation && !insideJsDocTagTypeExpression && symbol.declarations && symbol.declarations.some((d) => d.kind !== 311 /* SourceFile */ && d.kind !== 266 /* ModuleDeclaration */ && d.kind !== 265 /* EnumDeclaration */)) {
            let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType();
            let insertQuestionDot = false;
            if (type.isNullableType()) {
              const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false;
              if (canCorrectToQuestionDot || isRightOfQuestionDot) {
                type = type.getNonNullableType();
                if (canCorrectToQuestionDot) {
                  insertQuestionDot = true;
                }
              }
            }
            addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
          }
          return;
        }
      }
    }
    if (!isTypeLocation) {
      typeChecker.tryGetThisTypeAt(
        node,
        /*includeGlobalThis*/
        false
      );
      let type = typeChecker.getTypeAtLocation(node).getNonOptionalType();
      let insertQuestionDot = false;
      if (type.isNullableType()) {
        const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false;
        if (canCorrectToQuestionDot || isRightOfQuestionDot) {
          type = type.getNonNullableType();
          if (canCorrectToQuestionDot) {
            insertQuestionDot = true;
          }
        }
      }
      addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
    }
  }
  function addTypeProperties(type, insertAwait, insertQuestionDot) {
    isNewIdentifierLocation = !!type.getStringIndexType();
    if (isRightOfQuestionDot && some(type.getCallSignatures())) {
      isNewIdentifierLocation = true;
    }
    const propertyAccess = node.kind === 204 /* ImportType */ ? node : node.parent;
    if (inCheckedFile) {
      for (const symbol of type.getApparentProperties()) {
        if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
          addPropertySymbol(
            symbol,
            /*insertAwait*/
            false,
            insertQuestionDot
          );
        }
      }
    } else {
      symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), (s) => typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s)));
    }
    if (insertAwait && preferences.includeCompletionsWithInsertText) {
      const promiseType = typeChecker.getPromisedTypeOfPromise(type);
      if (promiseType) {
        for (const symbol of promiseType.getApparentProperties()) {
          if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) {
            addPropertySymbol(
              symbol,
              /*insertAwait*/
              true,
              insertQuestionDot
            );
          }
        }
      }
    }
  }
  function addPropertySymbol(symbol, insertAwait, insertQuestionDot) {
    var _a;
    const computedPropertyName = firstDefined(symbol.declarations, (decl) => tryCast(getNameOfDeclaration(decl), isComputedPropertyName));
    if (computedPropertyName) {
      const leftMostName = getLeftMostName(computedPropertyName.expression);
      const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
      const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
      if (firstAccessibleSymbol && addToSeen(seenPropertySymbols, getSymbolId(firstAccessibleSymbol))) {
        const index = symbols.length;
        symbols.push(firstAccessibleSymbol);
        const moduleSymbol = firstAccessibleSymbol.parent;
        if (!moduleSymbol || !isExternalModuleSymbol(moduleSymbol) || typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) {
          symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) };
        } else {
          const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? (_a = getSourceFileOfModule(moduleSymbol)) == null ? void 0 : _a.fileName : void 0;
          const { moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{
            exportKind: 0 /* Named */,
            moduleFileName: fileName,
            isFromPackageJson: false,
            moduleSymbol,
            symbol: firstAccessibleSymbol,
            targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags
          }], position, isValidTypeOnlyAliasUseSite(location)) || {};
          if (moduleSpecifier) {
            const origin = {
              kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */),
              moduleSymbol,
              isDefaultExport: false,
              symbolName: firstAccessibleSymbol.name,
              exportName: firstAccessibleSymbol.name,
              fileName,
              moduleSpecifier
            };
            symbolToOriginInfoMap[index] = origin;
          }
        }
      } else if (preferences.includeCompletionsWithInsertText) {
        addSymbolOriginInfo(symbol);
        addSymbolSortInfo(symbol);
        symbols.push(symbol);
      }
    } else {
      addSymbolOriginInfo(symbol);
      addSymbolSortInfo(symbol);
      symbols.push(symbol);
    }
    function addSymbolSortInfo(symbol2) {
      if (isStaticProperty(symbol2)) {
        symbolToSortTextMap[getSymbolId(symbol2)] = SortText.LocalDeclarationPriority;
      }
    }
    function addSymbolOriginInfo(symbol2) {
      if (preferences.includeCompletionsWithInsertText) {
        if (insertAwait && addToSeen(seenPropertySymbols, getSymbolId(symbol2))) {
          symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) };
        } else if (insertQuestionDot) {
          symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ };
        }
      }
    }
    function getNullableSymbolOriginInfoKind(kind) {
      return insertQuestionDot ? kind | 16 /* Nullable */ : kind;
    }
  }
  function getLeftMostName(e) {
    return isIdentifier(e) ? e : isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : void 0;
  }
  function tryGetGlobalSymbols() {
    const result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() || (getGlobalCompletions(), 1 /* Success */);
    return result === 1 /* Success */;
  }
  function tryGetConstructorCompletion() {
    if (!tryGetConstructorLikeCompletionContainer(contextToken))
      return 0 /* Continue */;
    completionKind = 5 /* None */;
    isNewIdentifierLocation = true;
    keywordFilters = 4 /* ConstructorParameterKeywords */;
    return 1 /* Success */;
  }
  function tryGetJsxCompletionSymbols() {
    const jsxContainer = tryGetContainingJsxElement(contextToken);
    const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes);
    if (!attrsType)
      return 0 /* Continue */;
    const completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */);
    symbols = concatenate(symbols, filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties));
    setSortTextToOptionalMember();
    completionKind = 3 /* MemberLike */;
    isNewIdentifierLocation = false;
    return 1 /* Success */;
  }
  function tryGetImportCompletionSymbols() {
    if (!importStatementCompletion)
      return 0 /* Continue */;
    isNewIdentifierLocation = true;
    collectAutoImports();
    return 1 /* Success */;
  }
  function getGlobalCompletions() {
    keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
    completionKind = 1 /* Global */;
    isNewIdentifierLocation = isNewIdentifierDefinitionLocation();
    if (previousToken !== contextToken) {
      Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
    }
    const adjustedPosition = previousToken !== contextToken ? previousToken.getStart() : position;
    const scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
    isInSnippetScope = isSnippetScope(scopeNode);
    const symbolMeanings = (isTypeOnlyLocation ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
    const typeOnlyAliasNeedsPromotion = previousToken && !isValidTypeOnlyAliasUseSite(previousToken);
    symbols = concatenate(symbols, typeChecker.getSymbolsInScope(scopeNode, symbolMeanings));
    Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined");
    for (let i = 0; i < symbols.length; i++) {
      const symbol = symbols[i];
      if (!typeChecker.isArgumentsSymbol(symbol) && !some(symbol.declarations, (d) => d.getSourceFile() === sourceFile)) {
        symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
      }
      if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */)) {
        const typeOnlyAliasDeclaration = symbol.declarations && find(symbol.declarations, isTypeOnlyImportDeclaration);
        if (typeOnlyAliasDeclaration) {
          const origin = { kind: 64 /* TypeOnlyAlias */, declaration: typeOnlyAliasDeclaration };
          symbolToOriginInfoMap[i] = origin;
        }
      }
    }
    if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 311 /* SourceFile */) {
      const thisType = typeChecker.tryGetThisTypeAt(
        scopeNode,
        /*includeGlobalThis*/
        false,
        isClassLike(scopeNode.parent) ? scopeNode : void 0
      );
      if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) {
        for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) {
          symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ };
          symbols.push(symbol);
          symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers;
        }
      }
    }
    collectAutoImports();
    if (isTypeOnlyLocation) {
      keywordFilters = contextToken && isAssertionExpression(contextToken.parent) ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */;
    }
  }
  function shouldOfferImportCompletions() {
    if (importStatementCompletion)
      return true;
    if (isNonContextualObjectLiteral)
      return false;
    if (!preferences.includeCompletionsForModuleExports)
      return false;
    if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator)
      return true;
    if (compilerOptionsIndicateEsModules(program.getCompilerOptions()))
      return true;
    return programContainsModules(program);
  }
  function isSnippetScope(scopeNode) {
    switch (scopeNode.kind) {
      case 311 /* SourceFile */:
      case 227 /* TemplateExpression */:
      case 293 /* JsxExpression */:
      case 240 /* Block */:
        return true;
      default:
        return isStatement(scopeNode);
    }
  }
  function isTypeOnlyCompletion() {
    return insideJsDocTagTypeExpression || !!importStatementCompletion && isTypeOnlyImportOrExportDeclaration(location.parent) || !isContextTokenValueLocation(contextToken) && (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) || isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken));
  }
  function isContextTokenValueLocation(contextToken2) {
    return contextToken2 && (contextToken2.kind === 114 /* TypeOfKeyword */ && (contextToken2.parent.kind === 185 /* TypeQuery */ || isTypeOfExpression(contextToken2.parent)) || contextToken2.kind === 131 /* AssertsKeyword */ && contextToken2.parent.kind === 181 /* TypePredicate */);
  }
  function isContextTokenTypeLocation(contextToken2) {
    if (contextToken2) {
      const parentKind = contextToken2.parent.kind;
      switch (contextToken2.kind) {
        case 59 /* ColonToken */:
          return parentKind === 171 /* PropertyDeclaration */ || parentKind === 170 /* PropertySignature */ || parentKind === 168 /* Parameter */ || parentKind === 259 /* VariableDeclaration */ || isFunctionLikeKind(parentKind);
        case 64 /* EqualsToken */:
          return parentKind === 264 /* TypeAliasDeclaration */;
        case 130 /* AsKeyword */:
          return parentKind === 233 /* AsExpression */;
        case 30 /* LessThanToken */:
          return parentKind === 182 /* TypeReference */ || parentKind === 215 /* TypeAssertionExpression */;
        case 96 /* ExtendsKeyword */:
          return parentKind === 167 /* TypeParameter */;
        case 152 /* SatisfiesKeyword */:
          return parentKind === 237 /* SatisfiesExpression */;
      }
    }
    return false;
  }
  function collectAutoImports() {
    var _a, _b;
    if (!shouldOfferImportCompletions())
      return;
    Debug.assert(!(detailsEntryId == null ? void 0 : detailsEntryId.data), "Should not run 'collectAutoImports' when faster path is available via `data`");
    if (detailsEntryId && !detailsEntryId.source) {
      return;
    }
    flags |= 1 /* MayIncludeAutoImports */;
    const isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken && importStatementCompletion;
    const lowerCaseTokenText = isAfterTypeOnlyImportSpecifierModifier ? "" : previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : "";
    const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host);
    const exportInfo = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken);
    const packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) == null ? void 0 : _b.call(host);
    const packageJsonFilter = detailsEntryId ? void 0 : createPackageJsonImportFilter(sourceFile, preferences, host);
    resolvingModuleSpecifiers(
      "collectAutoImports",
      host,
      importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences)),
      program,
      position,
      preferences,
      !!importStatementCompletion,
      isValidTypeOnlyAliasUseSite(location),
      (context) => {
        exportInfo.search(
          sourceFile.path,
          /*preferCapitalized*/
          isRightOfOpenTag,
          (symbolName2, targetFlags) => {
            if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings())))
              return false;
            if (!detailsEntryId && isStringANonContextualKeyword(symbolName2))
              return false;
            if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */))
              return false;
            if (isTypeOnlyLocation && !(targetFlags & (1536 /* Module */ | 788968 /* Type */)))
              return false;
            const firstChar = symbolName2.charCodeAt(0);
            if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */))
              return false;
            if (detailsEntryId)
              return true;
            return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText);
          },
          (info, symbolName2, isFromAmbientModule, exportMapKey) => {
            if (detailsEntryId && !some(info, (i) => detailsEntryId.source === stripQuotes(i.moduleSymbol.name))) {
              return;
            }
            info = filter(info, isImportableExportInfo);
            if (!info.length) {
              return;
            }
            const result = context.tryResolve(info, isFromAmbientModule) || {};
            if (result === "failed")
              return;
            let exportInfo2 = info[0], moduleSpecifier;
            if (result !== "skipped") {
              ({ exportInfo: exportInfo2 = info[0], moduleSpecifier } = result);
            }
            const isDefaultExport = exportInfo2.exportKind === 1 /* Default */;
            const symbol = isDefaultExport && getLocalSymbolForExportDefault(exportInfo2.symbol) || exportInfo2.symbol;
            pushAutoImportSymbol(symbol, {
              kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */,
              moduleSpecifier,
              symbolName: symbolName2,
              exportMapKey,
              exportName: exportInfo2.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo2.symbol.name,
              fileName: exportInfo2.moduleFileName,
              isDefaultExport,
              moduleSymbol: exportInfo2.moduleSymbol,
              isFromPackageJson: exportInfo2.isFromPackageJson
            });
          }
        );
        hasUnresolvedAutoImports = context.skippedAny();
        flags |= context.resolvedAny() ? 8 /* ResolvedModuleSpecifiers */ : 0;
        flags |= context.resolvedBeyondLimit() ? 16 /* ResolvedModuleSpecifiersBeyondLimit */ : 0;
      }
    );
    function isImportableExportInfo(info) {
      const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile);
      if (!moduleFile) {
        const moduleName = stripQuotes(info.moduleSymbol.name);
        if (ts_JsTyping_exports.nodeCoreModules.has(moduleName) && startsWith(moduleName, "node:") !== shouldUseUriStyleNodeCoreModules(sourceFile, program)) {
          return false;
        }
        return packageJsonFilter ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) : true;
      }
      return isImportableFile(
        info.isFromPackageJson ? packageJsonAutoImportProvider : program,
        sourceFile,
        moduleFile,
        preferences,
        packageJsonFilter,
        getModuleSpecifierResolutionHost(info.isFromPackageJson),
        moduleSpecifierCache
      );
    }
  }
  function pushAutoImportSymbol(symbol, origin) {
    const symbolId = getSymbolId(symbol);
    if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) {
      return;
    }
    symbolToOriginInfoMap[symbols.length] = origin;
    symbolToSortTextMap[symbolId] = importStatementCompletion ? SortText.LocationPriority : SortText.AutoImportSuggestions;
    symbols.push(symbol);
  }
  function collectObjectLiteralMethodSymbols(members, enclosingDeclaration) {
    if (isInJSFile(location)) {
      return;
    }
    members.forEach((member) => {
      if (!isObjectLiteralMethodSymbol(member)) {
        return;
      }
      const displayName = getCompletionEntryDisplayNameForSymbol(
        member,
        getEmitScriptTarget(compilerOptions),
        /*origin*/
        void 0,
        0 /* ObjectPropertyDeclaration */,
        /*jsxIdentifierExpected*/
        false
      );
      if (!displayName) {
        return;
      }
      const { name } = displayName;
      const entryProps = getEntryForObjectLiteralMethodCompletion(
        member,
        name,
        enclosingDeclaration,
        program,
        host,
        compilerOptions,
        preferences,
        formatContext
      );
      if (!entryProps) {
        return;
      }
      const origin = { kind: 128 /* ObjectLiteralMethod */, ...entryProps };
      flags |= 32 /* MayIncludeMethodSnippets */;
      symbolToOriginInfoMap[symbols.length] = origin;
      symbols.push(member);
    });
  }
  function isObjectLiteralMethodSymbol(symbol) {
    if (!(symbol.flags & (4 /* Property */ | 8192 /* Method */))) {
      return false;
    }
    return true;
  }
  function getScopeNode(initialToken, position2, sourceFile2) {
    let scope = initialToken;
    while (scope && !positionBelongsToNode(scope, position2, sourceFile2)) {
      scope = scope.parent;
    }
    return scope;
  }
  function isCompletionListBlocker(contextToken2) {
    const start3 = timestamp();
    const result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) || isSolelyIdentifierDefinitionLocation(contextToken2) || isDotOfNumericLiteral(contextToken2) || isInJsxText(contextToken2) || isBigIntLiteral(contextToken2);
    log("getCompletionsAtPosition: isCompletionListBlocker: " + (timestamp() - start3));
    return result;
  }
  function isInJsxText(contextToken2) {
    if (contextToken2.kind === 12 /* JsxText */) {
      return true;
    }
    if (contextToken2.kind === 32 /* GreaterThanToken */ && contextToken2.parent) {
      if (location === contextToken2.parent && (location.kind === 285 /* JsxOpeningElement */ || location.kind === 284 /* JsxSelfClosingElement */)) {
        return false;
      }
      if (contextToken2.parent.kind === 285 /* JsxOpeningElement */) {
        return location.parent.kind !== 285 /* JsxOpeningElement */;
      }
      if (contextToken2.parent.kind === 286 /* JsxClosingElement */ || contextToken2.parent.kind === 284 /* JsxSelfClosingElement */) {
        return !!contextToken2.parent.parent && contextToken2.parent.parent.kind === 283 /* JsxElement */;
      }
    }
    return false;
  }
  function isNewIdentifierDefinitionLocation() {
    if (contextToken) {
      const containingNodeKind = contextToken.parent.kind;
      const tokenKind = keywordForNode(contextToken);
      switch (tokenKind) {
        case 28 /* CommaToken */:
          return containingNodeKind === 212 /* CallExpression */ || containingNodeKind === 175 /* Constructor */ || containingNodeKind === 213 /* NewExpression */ || containingNodeKind === 208 /* ArrayLiteralExpression */ || containingNodeKind === 225 /* BinaryExpression */ || containingNodeKind === 183 /* FunctionType */ || containingNodeKind === 209 /* ObjectLiteralExpression */;
        case 21 /* OpenParenToken */:
          return containingNodeKind === 212 /* CallExpression */ || containingNodeKind === 175 /* Constructor */ || containingNodeKind === 213 /* NewExpression */ || containingNodeKind === 216 /* ParenthesizedExpression */ || containingNodeKind === 195 /* ParenthesizedType */;
        case 23 /* OpenBracketToken */:
          return containingNodeKind === 208 /* ArrayLiteralExpression */ || containingNodeKind === 180 /* IndexSignature */ || containingNodeKind === 166 /* ComputedPropertyName */;
        case 144 /* ModuleKeyword */:
        case 145 /* NamespaceKeyword */:
        case 102 /* ImportKeyword */:
          return true;
        case 25 /* DotToken */:
          return containingNodeKind === 266 /* ModuleDeclaration */;
        case 19 /* OpenBraceToken */:
          return containingNodeKind === 262 /* ClassDeclaration */ || containingNodeKind === 209 /* ObjectLiteralExpression */;
        case 64 /* EqualsToken */:
          return containingNodeKind === 259 /* VariableDeclaration */ || containingNodeKind === 225 /* BinaryExpression */;
        case 16 /* TemplateHead */:
          return containingNodeKind === 227 /* TemplateExpression */;
        case 17 /* TemplateMiddle */:
          return containingNodeKind === 238 /* TemplateSpan */;
        case 134 /* AsyncKeyword */:
          return containingNodeKind === 173 /* MethodDeclaration */ || containingNodeKind === 303 /* ShorthandPropertyAssignment */;
        case 42 /* AsteriskToken */:
          return containingNodeKind === 173 /* MethodDeclaration */;
      }
      if (isClassMemberCompletionKeyword(tokenKind)) {
        return true;
      }
    }
    return false;
  }
  function isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) {
    return (isRegularExpressionLiteral(contextToken2) || isStringTextContainingNode(contextToken2)) && (rangeContainsPositionExclusive(contextToken2, position) || position === contextToken2.end && (!!contextToken2.isUnterminated || isRegularExpressionLiteral(contextToken2)));
  }
  function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() {
    const typeLiteralNode = tryGetTypeLiteralNode(contextToken);
    if (!typeLiteralNode)
      return 0 /* Continue */;
    const intersectionTypeNode = isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : void 0;
    const containerTypeNode = intersectionTypeNode || typeLiteralNode;
    const containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker);
    if (!containerExpectedType)
      return 0 /* Continue */;
    const containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode);
    const members = getPropertiesForCompletion(containerExpectedType, typeChecker);
    const existingMembers = getPropertiesForCompletion(containerActualType, typeChecker);
    const existingMemberEscapedNames = /* @__PURE__ */ new Set();
    existingMembers.forEach((s) => existingMemberEscapedNames.add(s.escapedName));
    symbols = concatenate(symbols, filter(members, (s) => !existingMemberEscapedNames.has(s.escapedName)));
    completionKind = 0 /* ObjectPropertyDeclaration */;
    isNewIdentifierLocation = true;
    return 1 /* Success */;
  }
  function tryGetObjectLikeCompletionSymbols() {
    const symbolsStartIndex = symbols.length;
    const objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
    if (!objectLikeContainer)
      return 0 /* Continue */;
    completionKind = 0 /* ObjectPropertyDeclaration */;
    let typeMembers;
    let existingMembers;
    if (objectLikeContainer.kind === 209 /* ObjectLiteralExpression */) {
      const instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker);
      if (instantiatedType === void 0) {
        if (objectLikeContainer.flags & 33554432 /* InWithStatement */) {
          return 2 /* Fail */;
        }
        isNonContextualObjectLiteral = true;
        return 0 /* Continue */;
      }
      const completionsType = typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */);
      const hasStringIndexType = (completionsType || instantiatedType).getStringIndexType();
      const hasNumberIndextype = (completionsType || instantiatedType).getNumberIndexType();
      isNewIdentifierLocation = !!hasStringIndexType || !!hasNumberIndextype;
      typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker);
      existingMembers = objectLikeContainer.properties;
      if (typeMembers.length === 0) {
        if (!hasNumberIndextype) {
          isNonContextualObjectLiteral = true;
          return 0 /* Continue */;
        }
      }
    } else {
      Debug.assert(objectLikeContainer.kind === 205 /* ObjectBindingPattern */);
      isNewIdentifierLocation = false;
      const rootDeclaration = getRootDeclaration(objectLikeContainer.parent);
      if (!isVariableLike(rootDeclaration))
        return Debug.fail("Root declaration is not variable-like.");
      let canGetType = hasInitializer(rootDeclaration) || !!getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 249 /* ForOfStatement */;
      if (!canGetType && rootDeclaration.kind === 168 /* Parameter */) {
        if (isExpression(rootDeclaration.parent)) {
          canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
        } else if (rootDeclaration.parent.kind === 173 /* MethodDeclaration */ || rootDeclaration.parent.kind === 177 /* SetAccessor */) {
          canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
        }
      }
      if (canGetType) {
        const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
        if (!typeForObject)
          return 2 /* Fail */;
        typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((propertySymbol) => {
          return typeChecker.isPropertyAccessible(
            objectLikeContainer,
            /*isSuper*/
            false,
            /*isWrite*/
            false,
            typeForObject,
            propertySymbol
          );
        });
        existingMembers = objectLikeContainer.elements;
      }
    }
    if (typeMembers && typeMembers.length > 0) {
      const filteredMembers = filterObjectMembersList(typeMembers, Debug.checkDefined(existingMembers));
      symbols = concatenate(symbols, filteredMembers);
      setSortTextToOptionalMember();
      if (objectLikeContainer.kind === 209 /* ObjectLiteralExpression */ && preferences.includeCompletionsWithObjectLiteralMethodSnippets && preferences.includeCompletionsWithInsertText) {
        transformObjectLiteralMembersSortText(symbolsStartIndex);
        collectObjectLiteralMethodSymbols(filteredMembers, objectLikeContainer);
      }
    }
    return 1 /* Success */;
  }
  function tryGetImportOrExportClauseCompletionSymbols() {
    if (!contextToken)
      return 0 /* Continue */;
    const namedImportsOrExports = contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ? tryCast(contextToken.parent, isNamedImportsOrExports) : isTypeKeywordTokenOrIdentifier(contextToken) ? tryCast(contextToken.parent.parent, isNamedImportsOrExports) : void 0;
    if (!namedImportsOrExports)
      return 0 /* Continue */;
    if (!isTypeKeywordTokenOrIdentifier(contextToken)) {
      keywordFilters = 8 /* TypeKeyword */;
    }
    const { moduleSpecifier } = namedImportsOrExports.kind === 274 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent;
    if (!moduleSpecifier) {
      isNewIdentifierLocation = true;
      return namedImportsOrExports.kind === 274 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */;
    }
    const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier);
    if (!moduleSpecifierSymbol) {
      isNewIdentifierLocation = true;
      return 2 /* Fail */;
    }
    completionKind = 3 /* MemberLike */;
    isNewIdentifierLocation = false;
    const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
    const existing = new Set(namedImportsOrExports.elements.filter((n) => !isCurrentlyEditingNode(n)).map((n) => (n.propertyName || n.name).escapedText));
    const uniques = exports.filter((e) => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName));
    symbols = concatenate(symbols, uniques);
    if (!uniques.length) {
      keywordFilters = 0 /* None */;
    }
    return 1 /* Success */;
  }
  function tryGetLocalNamedExportCompletionSymbols() {
    var _a;
    const namedExports = contextToken && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */) ? tryCast(contextToken.parent, isNamedExports) : void 0;
    if (!namedExports) {
      return 0 /* Continue */;
    }
    const localsContainer = findAncestor(namedExports, or(isSourceFile, isModuleDeclaration));
    completionKind = 5 /* None */;
    isNewIdentifierLocation = false;
    (_a = localsContainer.locals) == null ? void 0 : _a.forEach((symbol, name) => {
      var _a2, _b;
      symbols.push(symbol);
      if ((_b = (_a2 = localsContainer.symbol) == null ? void 0 : _a2.exports) == null ? void 0 : _b.has(name)) {
        symbolToSortTextMap[getSymbolId(symbol)] = SortText.OptionalMember;
      }
    });
    return 1 /* Success */;
  }
  function tryGetClassLikeCompletionSymbols() {
    const decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position);
    if (!decl)
      return 0 /* Continue */;
    completionKind = 3 /* MemberLike */;
    isNewIdentifierLocation = true;
    keywordFilters = contextToken.kind === 42 /* AsteriskToken */ ? 0 /* None */ : isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
    if (!isClassLike(decl))
      return 1 /* Success */;
    const classElement = contextToken.kind === 27 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent;
    let classElementModifierFlags = isClassElement(classElement) ? getEffectiveModifierFlags(classElement) : 0 /* None */;
    if (contextToken.kind === 80 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) {
      switch (contextToken.getText()) {
        case "private":
          classElementModifierFlags = classElementModifierFlags | 8 /* Private */;
          break;
        case "static":
          classElementModifierFlags = classElementModifierFlags | 32 /* Static */;
          break;
        case "override":
          classElementModifierFlags = classElementModifierFlags | 16384 /* Override */;
          break;
      }
    }
    if (isClassStaticBlockDeclaration(classElement)) {
      classElementModifierFlags |= 32 /* Static */;
    }
    if (!(classElementModifierFlags & 8 /* Private */)) {
      const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl);
      const baseSymbols = flatMap(baseTypeNodes, (baseTypeNode) => {
        const type = typeChecker.getTypeAtLocation(baseTypeNode);
        return classElementModifierFlags & 32 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type);
      });
      symbols = concatenate(symbols, filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags));
      forEach(symbols, (symbol, index) => {
        const declaration = symbol == null ? void 0 : symbol.valueDeclaration;
        if (declaration && isClassElement(declaration) && declaration.name && isComputedPropertyName(declaration.name)) {
          const origin = {
            kind: 512 /* ComputedPropertyName */,
            symbolName: typeChecker.symbolToString(symbol)
          };
          symbolToOriginInfoMap[index] = origin;
        }
      });
    }
    return 1 /* Success */;
  }
  function isConstructorParameterCompletion(node2) {
    return !!node2.parent && isParameter(node2.parent) && isConstructorDeclaration(node2.parent.parent) && (isParameterPropertyModifier(node2.kind) || isDeclarationName(node2));
  }
  function tryGetConstructorLikeCompletionContainer(contextToken2) {
    if (contextToken2) {
      const parent2 = contextToken2.parent;
      switch (contextToken2.kind) {
        case 21 /* OpenParenToken */:
        case 28 /* CommaToken */:
          return isConstructorDeclaration(contextToken2.parent) ? contextToken2.parent : void 0;
        default:
          if (isConstructorParameterCompletion(contextToken2)) {
            return parent2.parent;
          }
      }
    }
    return void 0;
  }
  function tryGetFunctionLikeBodyCompletionContainer(contextToken2) {
    if (contextToken2) {
      let prev;
      const container = findAncestor(contextToken2.parent, (node2) => {
        if (isClassLike(node2)) {
          return "quit";
        }
        if (isFunctionLikeDeclaration(node2) && prev === node2.body) {
          return true;
        }
        prev = node2;
        return false;
      });
      return container && container;
    }
  }
  function tryGetContainingJsxElement(contextToken2) {
    if (contextToken2) {
      const parent2 = contextToken2.parent;
      switch (contextToken2.kind) {
        case 32 /* GreaterThanToken */:
        case 31 /* LessThanSlashToken */:
        case 44 /* SlashToken */:
        case 80 /* Identifier */:
        case 210 /* PropertyAccessExpression */:
        case 291 /* JsxAttributes */:
        case 290 /* JsxAttribute */:
        case 292 /* JsxSpreadAttribute */:
          if (parent2 && (parent2.kind === 284 /* JsxSelfClosingElement */ || parent2.kind === 285 /* JsxOpeningElement */)) {
            if (contextToken2.kind === 32 /* GreaterThanToken */) {
              const precedingToken = findPrecedingToken(
                contextToken2.pos,
                sourceFile,
                /*startNode*/
                void 0
              );
              if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */)
                break;
            }
            return parent2;
          } else if (parent2.kind === 290 /* JsxAttribute */) {
            return parent2.parent.parent;
          }
          break;
        case 11 /* StringLiteral */:
          if (parent2 && (parent2.kind === 290 /* JsxAttribute */ || parent2.kind === 292 /* JsxSpreadAttribute */)) {
            return parent2.parent.parent;
          }
          break;
        case 20 /* CloseBraceToken */:
          if (parent2 && parent2.kind === 293 /* JsxExpression */ && parent2.parent && parent2.parent.kind === 290 /* JsxAttribute */) {
            return parent2.parent.parent.parent;
          }
          if (parent2 && parent2.kind === 292 /* JsxSpreadAttribute */) {
            return parent2.parent.parent;
          }
          break;
      }
    }
    return void 0;
  }
  function isSolelyIdentifierDefinitionLocation(contextToken2) {
    const parent2 = contextToken2.parent;
    const containingNodeKind = parent2.kind;
    switch (contextToken2.kind) {
      case 28 /* CommaToken */:
        return containingNodeKind === 259 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken2) || containingNodeKind === 242 /* VariableStatement */ || containingNodeKind === 265 /* EnumDeclaration */ || // enum a { foo, |
        isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 263 /* InterfaceDeclaration */ || // interface A<T, |
        containingNodeKind === 206 /* ArrayBindingPattern */ || // var [x, y|
        containingNodeKind === 264 /* TypeAliasDeclaration */ || // type Map, K, |
        // class A<T, |
        // var C = class D<T, |
        isClassLike(parent2) && !!parent2.typeParameters && parent2.typeParameters.end >= contextToken2.pos;
      case 25 /* DotToken */:
        return containingNodeKind === 206 /* ArrayBindingPattern */;
      case 59 /* ColonToken */:
        return containingNodeKind === 207 /* BindingElement */;
      case 23 /* OpenBracketToken */:
        return containingNodeKind === 206 /* ArrayBindingPattern */;
      case 21 /* OpenParenToken */:
        return containingNodeKind === 298 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind);
      case 19 /* OpenBraceToken */:
        return containingNodeKind === 265 /* EnumDeclaration */;
      case 30 /* LessThanToken */:
        return containingNodeKind === 262 /* ClassDeclaration */ || // class A< |
        containingNodeKind === 230 /* ClassExpression */ || // var C = class D< |
        containingNodeKind === 263 /* InterfaceDeclaration */ || // interface A< |
        containingNodeKind === 264 /* TypeAliasDeclaration */ || // type List< |
        isFunctionLikeKind(containingNodeKind);
      case 126 /* StaticKeyword */:
        return containingNodeKind === 171 /* PropertyDeclaration */ && !isClassLike(parent2.parent);
      case 26 /* DotDotDotToken */:
        return containingNodeKind === 168 /* Parameter */ || !!parent2.parent && parent2.parent.kind === 206 /* ArrayBindingPattern */;
      case 125 /* PublicKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
        return containingNodeKind === 168 /* Parameter */ && !isConstructorDeclaration(parent2.parent);
      case 130 /* AsKeyword */:
        return containingNodeKind === 275 /* ImportSpecifier */ || containingNodeKind === 280 /* ExportSpecifier */ || containingNodeKind === 273 /* NamespaceImport */;
      case 139 /* GetKeyword */:
      case 153 /* SetKeyword */:
        return !isFromObjectTypeDeclaration(contextToken2);
      case 80 /* Identifier */:
        if (containingNodeKind === 275 /* ImportSpecifier */ && contextToken2 === parent2.name && contextToken2.text === "type") {
          return false;
        }
        break;
      case 86 /* ClassKeyword */:
      case 94 /* EnumKeyword */:
      case 120 /* InterfaceKeyword */:
      case 100 /* FunctionKeyword */:
      case 115 /* VarKeyword */:
      case 102 /* ImportKeyword */:
      case 121 /* LetKeyword */:
      case 87 /* ConstKeyword */:
      case 140 /* InferKeyword */:
        return true;
      case 156 /* TypeKeyword */:
        return containingNodeKind !== 275 /* ImportSpecifier */;
      case 42 /* AsteriskToken */:
        return isFunctionLike(contextToken2.parent) && !isMethodDeclaration(contextToken2.parent);
    }
    if (isClassMemberCompletionKeyword(keywordForNode(contextToken2)) && isFromObjectTypeDeclaration(contextToken2)) {
      return false;
    }
    if (isConstructorParameterCompletion(contextToken2)) {
      if (!isIdentifier(contextToken2) || isParameterPropertyModifier(keywordForNode(contextToken2)) || isCurrentlyEditingNode(contextToken2)) {
        return false;
      }
    }
    switch (keywordForNode(contextToken2)) {
      case 128 /* AbstractKeyword */:
      case 86 /* ClassKeyword */:
      case 87 /* ConstKeyword */:
      case 138 /* DeclareKeyword */:
      case 94 /* EnumKeyword */:
      case 100 /* FunctionKeyword */:
      case 120 /* InterfaceKeyword */:
      case 121 /* LetKeyword */:
      case 123 /* PrivateKeyword */:
      case 124 /* ProtectedKeyword */:
      case 125 /* PublicKeyword */:
      case 126 /* StaticKeyword */:
      case 115 /* VarKeyword */:
        return true;
      case 134 /* AsyncKeyword */:
        return isPropertyDeclaration(contextToken2.parent);
    }
    const ancestorClassLike = findAncestor(contextToken2.parent, isClassLike);
    if (ancestorClassLike && contextToken2 === previousToken && isPreviousPropertyDeclarationTerminated(contextToken2, position)) {
      return false;
    }
    const ancestorPropertyDeclaraion = getAncestor(contextToken2.parent, 171 /* PropertyDeclaration */);
    if (ancestorPropertyDeclaraion && contextToken2 !== previousToken && isClassLike(previousToken.parent.parent) && position <= previousToken.end) {
      if (isPreviousPropertyDeclarationTerminated(contextToken2, previousToken.end)) {
        return false;
      } else if (contextToken2.kind !== 64 /* EqualsToken */ && (isInitializedProperty(ancestorPropertyDeclaraion) || hasType(ancestorPropertyDeclaraion))) {
        return true;
      }
    }
    return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent) || isTypeParameterDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end));
  }
  function isPreviousPropertyDeclarationTerminated(contextToken2, position2) {
    return contextToken2.kind !== 64 /* EqualsToken */ && (contextToken2.kind === 27 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile));
  }
  function isFunctionLikeButNotConstructor(kind) {
    return isFunctionLikeKind(kind) && kind !== 175 /* Constructor */;
  }
  function isDotOfNumericLiteral(contextToken2) {
    if (contextToken2.kind === 9 /* NumericLiteral */) {
      const text = contextToken2.getFullText();
      return text.charAt(text.length - 1) === ".";
    }
    return false;
  }
  function isVariableDeclarationListButNotTypeArgument(node2) {
    return node2.parent.kind === 260 /* VariableDeclarationList */ && !isPossiblyTypeArgumentPosition(node2, sourceFile, typeChecker);
  }
  function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
    if (existingMembers.length === 0) {
      return contextualMemberSymbols;
    }
    const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set();
    const existingMemberNames = /* @__PURE__ */ new Set();
    for (const m of existingMembers) {
      if (m.kind !== 302 /* PropertyAssignment */ && m.kind !== 303 /* ShorthandPropertyAssignment */ && m.kind !== 207 /* BindingElement */ && m.kind !== 173 /* MethodDeclaration */ && m.kind !== 176 /* GetAccessor */ && m.kind !== 177 /* SetAccessor */ && m.kind !== 304 /* SpreadAssignment */) {
        continue;
      }
      if (isCurrentlyEditingNode(m)) {
        continue;
      }
      let existingName;
      if (isSpreadAssignment(m)) {
        setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment);
      } else if (isBindingElement(m) && m.propertyName) {
        if (m.propertyName.kind === 80 /* Identifier */) {
          existingName = m.propertyName.escapedText;
        }
      } else {
        const name = getNameOfDeclaration(m);
        existingName = name && isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0;
      }
      if (existingName !== void 0) {
        existingMemberNames.add(existingName);
      }
    }
    const filteredSymbols = contextualMemberSymbols.filter((m) => !existingMemberNames.has(m.escapedName));
    setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
    return filteredSymbols;
  }
  function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) {
    const expression = declaration.expression;
    const symbol = typeChecker.getSymbolAtLocation(expression);
    const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression);
    const properties = type && type.properties;
    if (properties) {
      properties.forEach((property) => {
        membersDeclaredBySpreadAssignment.add(property.name);
      });
    }
  }
  function setSortTextToOptionalMember() {
    symbols.forEach((m) => {
      if (m.flags & 16777216 /* Optional */) {
        const symbolId = getSymbolId(m);
        symbolToSortTextMap[symbolId] = symbolToSortTextMap[symbolId] ?? SortText.OptionalMember;
      }
    });
  }
  function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) {
    if (membersDeclaredBySpreadAssignment.size === 0) {
      return;
    }
    for (const contextualMemberSymbol of contextualMemberSymbols) {
      if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) {
        symbolToSortTextMap[getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment;
      }
    }
  }
  function transformObjectLiteralMembersSortText(start3) {
    for (let i = start3; i < symbols.length; i++) {
      const symbol = symbols[i];
      const symbolId = getSymbolId(symbol);
      const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i];
      const target = getEmitScriptTarget(compilerOptions);
      const displayName = getCompletionEntryDisplayNameForSymbol(
        symbol,
        target,
        origin,
        0 /* ObjectPropertyDeclaration */,
        /*jsxIdentifierExpected*/
        false
      );
      if (displayName) {
        const originalSortText = symbolToSortTextMap[symbolId] ?? SortText.LocationPriority;
        const { name } = displayName;
        symbolToSortTextMap[symbolId] = SortText.ObjectLiteralProperty(originalSortText, name);
      }
    }
  }
  function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) {
    const existingMemberNames = /* @__PURE__ */ new Set();
    for (const m of existingMembers) {
      if (m.kind !== 171 /* PropertyDeclaration */ && m.kind !== 173 /* MethodDeclaration */ && m.kind !== 176 /* GetAccessor */ && m.kind !== 177 /* SetAccessor */) {
        continue;
      }
      if (isCurrentlyEditingNode(m)) {
        continue;
      }
      if (hasEffectiveModifier(m, 8 /* Private */)) {
        continue;
      }
      if (isStatic(m) !== !!(currentClassElementModifierFlags & 32 /* Static */)) {
        continue;
      }
      const existingName = getPropertyNameForPropertyNameNode(m.name);
      if (existingName) {
        existingMemberNames.add(existingName);
      }
    }
    return baseSymbols.filter((propertySymbol) => !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)));
  }
  function filterJsxAttributes(symbols2, attributes) {
    const seenNames = /* @__PURE__ */ new Set();
    const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set();
    for (const attr of attributes) {
      if (isCurrentlyEditingNode(attr)) {
        continue;
      }
      if (attr.kind === 290 /* JsxAttribute */) {
        seenNames.add(getEscapedTextOfJsxAttributeName(attr.name));
      } else if (isJsxSpreadAttribute(attr)) {
        setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment);
      }
    }
    const filteredSymbols = symbols2.filter((a) => !seenNames.has(a.escapedName));
    setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
    return filteredSymbols;
  }
  function isCurrentlyEditingNode(node2) {
    return node2.getStart(sourceFile) <= position && position <= node2.getEnd();
  }
}
function tryGetObjectLikeCompletionContainer(contextToken) {
  if (contextToken) {
    const { parent: parent2 } = contextToken;
    switch (contextToken.kind) {
      case 19 /* OpenBraceToken */:
      case 28 /* CommaToken */:
        if (isObjectLiteralExpression(parent2) || isObjectBindingPattern(parent2)) {
          return parent2;
        }
        break;
      case 42 /* AsteriskToken */:
        return isMethodDeclaration(parent2) ? tryCast(parent2.parent, isObjectLiteralExpression) : void 0;
      case 134 /* AsyncKeyword */:
        return tryCast(parent2.parent, isObjectLiteralExpression);
      case 80 /* Identifier */:
        return contextToken.text === "async" && isShorthandPropertyAssignment(contextToken.parent) ? contextToken.parent.parent : void 0;
    }
  }
  return void 0;
}
function getRelevantTokens(position, sourceFile) {
  const previousToken = findPrecedingToken(position, sourceFile);
  if (previousToken && position <= previousToken.end && (isMemberName(previousToken) || isKeyword(previousToken.kind))) {
    const contextToken = findPrecedingToken(
      previousToken.getFullStart(),
      sourceFile,
      /*startNode*/
      void 0
    );
    return { contextToken, previousToken };
  }
  return { contextToken: previousToken, previousToken };
}
function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) {
  const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program;
  const checker = containingProgram.getTypeChecker();
  const moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : void 0;
  if (!moduleSymbol)
    return void 0;
  let symbol = data.exportName === "export=" /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol);
  if (!symbol)
    return void 0;
  const isDefaultExport = data.exportName === "default" /* Default */;
  symbol = isDefaultExport && getLocalSymbolForExportDefault(symbol) || symbol;
  return { symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) };
}
function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) {
  if (originIsIgnore(origin)) {
    return void 0;
  }
  const name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name;
  if (name === void 0 || symbol.flags & 1536 /* Module */ && isSingleOrDoubleQuote(name.charCodeAt(0)) || isKnownSymbol(symbol)) {
    return void 0;
  }
  const validNameResult = { name, needsConvertPropertyAccess: false };
  if (isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) {
    return validNameResult;
  }
  switch (kind) {
    case 3 /* MemberLike */:
      return originIsComputedPropertyName(origin) ? { name: origin.symbolName, needsConvertPropertyAccess: false } : void 0;
    case 0 /* ObjectPropertyDeclaration */:
      return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
    case 2 /* PropertyAccess */:
    case 1 /* Global */:
      return name.charCodeAt(0) === 32 /* space */ ? void 0 : { name, needsConvertPropertyAccess: true };
    case 5 /* None */:
    case 4 /* String */:
      return validNameResult;
    default:
      Debug.assertNever(kind);
  }
}
var _keywordCompletions = [];
var allKeywordsCompletions = memoize(() => {
  const res = [];
  for (let i = 83 /* FirstKeyword */; i <= 164 /* LastKeyword */; i++) {
    res.push({
      name: tokenToString(i),
      kind: "keyword" /* keyword */,
      kindModifiers: "" /* none */,
      sortText: SortText.GlobalsOrKeywords
    });
  }
  return res;
});
function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
  if (!filterOutTsOnlyKeywords)
    return getTypescriptKeywordCompletions(keywordFilter);
  const index = keywordFilter + 8 /* Last */ + 1;
  return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter).filter((entry) => !isTypeScriptOnlyKeyword(stringToToken(entry.name))));
}
function getTypescriptKeywordCompletions(keywordFilter) {
  return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter((entry) => {
    const kind = stringToToken(entry.name);
    switch (keywordFilter) {
      case 0 /* None */:
        return false;
      case 1 /* All */:
        return isFunctionLikeBodyKeyword(kind) || kind === 138 /* DeclareKeyword */ || kind === 144 /* ModuleKeyword */ || kind === 156 /* TypeKeyword */ || kind === 145 /* NamespaceKeyword */ || kind === 128 /* AbstractKeyword */ || isTypeKeyword(kind) && kind !== 157 /* UndefinedKeyword */;
      case 5 /* FunctionLikeBodyKeywords */:
        return isFunctionLikeBodyKeyword(kind);
      case 2 /* ClassElementKeywords */:
        return isClassMemberCompletionKeyword(kind);
      case 3 /* InterfaceElementKeywords */:
        return isInterfaceOrTypeLiteralCompletionKeyword(kind);
      case 4 /* ConstructorParameterKeywords */:
        return isParameterPropertyModifier(kind);
      case 6 /* TypeAssertionKeywords */:
        return isTypeKeyword(kind) || kind === 87 /* ConstKeyword */;
      case 7 /* TypeKeywords */:
        return isTypeKeyword(kind);
      case 8 /* TypeKeyword */:
        return kind === 156 /* TypeKeyword */;
      default:
        return Debug.assertNever(keywordFilter);
    }
  }));
}
function isTypeScriptOnlyKeyword(kind) {
  switch (kind) {
    case 128 /* AbstractKeyword */:
    case 133 /* AnyKeyword */:
    case 162 /* BigIntKeyword */:
    case 136 /* BooleanKeyword */:
    case 138 /* DeclareKeyword */:
    case 94 /* EnumKeyword */:
    case 161 /* GlobalKeyword */:
    case 119 /* ImplementsKeyword */:
    case 140 /* InferKeyword */:
    case 120 /* InterfaceKeyword */:
    case 142 /* IsKeyword */:
    case 143 /* KeyOfKeyword */:
    case 144 /* ModuleKeyword */:
    case 145 /* NamespaceKeyword */:
    case 146 /* NeverKeyword */:
    case 150 /* NumberKeyword */:
    case 151 /* ObjectKeyword */:
    case 163 /* OverrideKeyword */:
    case 123 /* PrivateKeyword */:
    case 124 /* ProtectedKeyword */:
    case 125 /* PublicKeyword */:
    case 148 /* ReadonlyKeyword */:
    case 154 /* StringKeyword */:
    case 155 /* SymbolKeyword */:
    case 156 /* TypeKeyword */:
    case 158 /* UniqueKeyword */:
    case 159 /* UnknownKeyword */:
      return true;
    default:
      return false;
  }
}
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
  return kind === 148 /* ReadonlyKeyword */;
}
function isClassMemberCompletionKeyword(kind) {
  switch (kind) {
    case 128 /* AbstractKeyword */:
    case 129 /* AccessorKeyword */:
    case 137 /* ConstructorKeyword */:
    case 139 /* GetKeyword */:
    case 153 /* SetKeyword */:
    case 134 /* AsyncKeyword */:
    case 138 /* DeclareKeyword */:
    case 163 /* OverrideKeyword */:
      return true;
    default:
      return isClassMemberModifier(kind);
  }
}
function isFunctionLikeBodyKeyword(kind) {
  return kind === 134 /* AsyncKeyword */ || kind === 135 /* AwaitKeyword */ || kind === 130 /* AsKeyword */ || kind === 152 /* SatisfiesKeyword */ || kind === 156 /* TypeKeyword */ || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
}
function keywordForNode(node) {
  return isIdentifier(node) ? identifierToKeywordKind(node) ?? 0 /* Unknown */ : node.kind;
}
function getContextualKeywords(contextToken, position) {
  const entries = [];
  if (contextToken) {
    const file = contextToken.getSourceFile();
    const parent2 = contextToken.parent;
    const tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line;
    const currentLine = file.getLineAndCharacterOfPosition(position).line;
    if ((isImportDeclaration(parent2) || isExportDeclaration(parent2) && parent2.moduleSpecifier) && contextToken === parent2.moduleSpecifier && tokenLine === currentLine) {
      entries.push({
        name: tokenToString(132 /* AssertKeyword */),
        kind: "keyword" /* keyword */,
        kindModifiers: "" /* none */,
        sortText: SortText.GlobalsOrKeywords
      });
    }
  }
  return entries;
}
function getJsDocTagAtPosition(node, position) {
  return findAncestor(node, (n) => isJSDocTag(n) && rangeContainsPosition(n, position) ? true : isJSDoc(n) ? "quit" : false);
}
function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) {
  const hasCompletionsType = completionsType && completionsType !== contextualType;
  const type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */) ? checker.getUnionType([contextualType, completionsType]) : contextualType;
  const properties = getApparentProperties(type, obj, checker);
  return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties;
  function hasDeclarationOtherThanSelf(member) {
    if (!length(member.declarations))
      return true;
    return some(member.declarations, (decl) => decl.parent !== obj);
  }
}
function getApparentProperties(type, node, checker) {
  if (!type.isUnion())
    return type.getApparentProperties();
  return checker.getAllPossiblePropertiesOfTypes(filter(type.types, (memberType) => !(memberType.flags & 402784252 /* Primitive */ || checker.isArrayLikeType(memberType) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, node) || checker.typeHasCallOrConstructSignatures(memberType) || memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties()))));
}
function containsNonPublicProperties(props) {
  return some(props, (p) => !!(getDeclarationModifierFlagsFromSymbol(p) & 24 /* NonPublicAccessibilityModifier */));
}
function getPropertiesForCompletion(type, checker) {
  return type.isUnion() ? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") : Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
}
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) {
  switch (location.kind) {
    case 357 /* SyntaxList */:
      return tryCast(location.parent, isObjectTypeDeclaration);
    case 1 /* EndOfFileToken */:
      const cls = tryCast(lastOrUndefined(cast(location.parent, isSourceFile).statements), isObjectTypeDeclaration);
      if (cls && !findChildOfKind(cls, 20 /* CloseBraceToken */, sourceFile)) {
        return cls;
      }
      break;
    case 80 /* Identifier */: {
      const originalKeywordKind = identifierToKeywordKind(location);
      if (originalKeywordKind) {
        return void 0;
      }
      if (isPropertyDeclaration(location.parent) && location.parent.initializer === location) {
        return void 0;
      }
      if (isFromObjectTypeDeclaration(location)) {
        return findAncestor(location, isObjectTypeDeclaration);
      }
    }
  }
  if (!contextToken)
    return void 0;
  if (location.kind === 137 /* ConstructorKeyword */ || isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location)) {
    return findAncestor(contextToken, isClassLike);
  }
  switch (contextToken.kind) {
    case 64 /* EqualsToken */:
      return void 0;
    case 27 /* SemicolonToken */:
    case 20 /* CloseBraceToken */:
      return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : tryCast(location, isObjectTypeDeclaration);
    case 19 /* OpenBraceToken */:
    case 28 /* CommaToken */:
      return tryCast(contextToken.parent, isObjectTypeDeclaration);
    default:
      if (isObjectTypeDeclaration(location)) {
        if (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) {
          return location;
        }
        const isValidKeyword = isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
        return isValidKeyword(contextToken.kind) || contextToken.kind === 42 /* AsteriskToken */ || isIdentifier(contextToken) && isValidKeyword(identifierToKeywordKind(contextToken) ?? 0 /* Unknown */) ? contextToken.parent.parent : void 0;
      }
      return void 0;
  }
}
function tryGetTypeLiteralNode(node) {
  if (!node)
    return void 0;
  const parent2 = node.parent;
  switch (node.kind) {
    case 19 /* OpenBraceToken */:
      if (isTypeLiteralNode(parent2)) {
        return parent2;
      }
      break;
    case 27 /* SemicolonToken */:
    case 28 /* CommaToken */:
    case 80 /* Identifier */:
      if (parent2.kind === 170 /* PropertySignature */ && isTypeLiteralNode(parent2.parent)) {
        return parent2.parent;
      }
      break;
  }
  return void 0;
}
function getConstraintOfTypeArgumentProperty(node, checker) {
  if (!node)
    return void 0;
  if (isTypeNode(node) && isTypeReferenceType(node.parent)) {
    return checker.getTypeArgumentConstraint(node);
  }
  const t = getConstraintOfTypeArgumentProperty(node.parent, checker);
  if (!t)
    return void 0;
  switch (node.kind) {
    case 170 /* PropertySignature */:
      return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName);
    case 192 /* IntersectionType */:
    case 186 /* TypeLiteral */:
    case 191 /* UnionType */:
      return t;
  }
}
function isFromObjectTypeDeclaration(node) {
  return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent);
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
  switch (triggerCharacter) {
    case ".":
    case "@":
      return true;
    case '"':
    case "'":
    case "`":
      return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
    case "#":
      return !!contextToken && isPrivateIdentifier(contextToken) && !!getContainingClass(contextToken);
    case "<":
      return !!contextToken && contextToken.kind === 30 /* LessThanToken */ && (!isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
    case "/":
      return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 44 /* SlashToken */ && isJsxClosingElement(contextToken.parent));
    case " ":
      return !!contextToken && isImportKeyword(contextToken) && contextToken.parent.kind === 311 /* SourceFile */;
    default:
      return Debug.assertNever(triggerCharacter);
  }
}
function binaryExpressionMayBeOpenTag({ left }) {
  return nodeIsMissing(left);
}
function isProbablyGlobalType(type, sourceFile, checker) {
  const selfSymbol = checker.resolveName(
    "self",
    /*location*/
    void 0,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  );
  if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) {
    return true;
  }
  const globalSymbol = checker.resolveName(
    "global",
    /*location*/
    void 0,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  );
  if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) {
    return true;
  }
  const globalThisSymbol = checker.resolveName(
    "globalThis",
    /*location*/
    void 0,
    111551 /* Value */,
    /*excludeGlobals*/
    false
  );
  if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) {
    return true;
  }
  return false;
}
function isStaticProperty(symbol) {
  return !!(symbol.valueDeclaration && getEffectiveModifierFlags(symbol.valueDeclaration) & 32 /* Static */ && isClassLike(symbol.valueDeclaration.parent));
}
function tryGetObjectLiteralContextualType(node, typeChecker) {
  const type = typeChecker.getContextualType(node);
  if (type) {
    return type;
  }
  const parent2 = walkUpParenthesizedExpressions(node.parent);
  if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && node === parent2.left) {
    return typeChecker.getTypeAtLocation(parent2);
  }
  if (isExpression(parent2)) {
    return typeChecker.getContextualType(parent2);
  }
  return void 0;
}
function getImportStatementCompletionInfo(contextToken) {
  var _a, _b, _c;
  let keywordCompletion;
  let isKeywordOnlyCompletion = false;
  const candidate = getCandidate();
  return {
    isKeywordOnlyCompletion,
    keywordCompletion,
    isNewIdentifierLocation: !!(candidate || keywordCompletion === 156 /* TypeKeyword */),
    isTopLevelTypeOnly: !!((_b = (_a = tryCast(candidate, isImportDeclaration)) == null ? void 0 : _a.importClause) == null ? void 0 : _b.isTypeOnly) || !!((_c = tryCast(candidate, isImportEqualsDeclaration)) == null ? void 0 : _c.isTypeOnly),
    couldBeTypeOnlyImportSpecifier: !!candidate && couldBeTypeOnlyImportSpecifier(candidate, contextToken),
    replacementSpan: getSingleLineReplacementSpanForImportCompletionNode(candidate)
  };
  function getCandidate() {
    const parent2 = contextToken.parent;
    if (isImportEqualsDeclaration(parent2)) {
      keywordCompletion = contextToken.kind === 156 /* TypeKeyword */ ? void 0 : 156 /* TypeKeyword */;
      return isModuleSpecifierMissingOrEmpty(parent2.moduleReference) ? parent2 : void 0;
    }
    if (couldBeTypeOnlyImportSpecifier(parent2, contextToken) && canCompleteFromNamedBindings(parent2.parent)) {
      return parent2;
    }
    if (isNamedImports(parent2) || isNamespaceImport(parent2)) {
      if (!parent2.parent.isTypeOnly && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 102 /* ImportKeyword */ || contextToken.kind === 28 /* CommaToken */)) {
        keywordCompletion = 156 /* TypeKeyword */;
      }
      if (canCompleteFromNamedBindings(parent2)) {
        if (contextToken.kind === 20 /* CloseBraceToken */ || contextToken.kind === 80 /* Identifier */) {
          isKeywordOnlyCompletion = true;
          keywordCompletion = 160 /* FromKeyword */;
        } else {
          return parent2.parent.parent;
        }
      }
      return void 0;
    }
    if (isImportKeyword(contextToken) && isSourceFile(parent2)) {
      keywordCompletion = 156 /* TypeKeyword */;
      return contextToken;
    }
    if (isImportKeyword(contextToken) && isImportDeclaration(parent2)) {
      keywordCompletion = 156 /* TypeKeyword */;
      return isModuleSpecifierMissingOrEmpty(parent2.moduleSpecifier) ? parent2 : void 0;
    }
    return void 0;
  }
}
function getSingleLineReplacementSpanForImportCompletionNode(node) {
  var _a;
  if (!node)
    return void 0;
  const top = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration)) ?? node;
  const sourceFile = top.getSourceFile();
  if (rangeIsOnSingleLine(top, sourceFile)) {
    return createTextSpanFromNode(top, sourceFile);
  }
  Debug.assert(top.kind !== 102 /* ImportKeyword */ && top.kind !== 275 /* ImportSpecifier */);
  const potentialSplitPoint = top.kind === 271 /* ImportDeclaration */ ? getPotentiallyInvalidImportSpecifier((_a = top.importClause) == null ? void 0 : _a.namedBindings) ?? top.moduleSpecifier : top.moduleReference;
  const withoutModuleSpecifier = {
    pos: top.getFirstToken().getStart(),
    end: potentialSplitPoint.pos
  };
  if (rangeIsOnSingleLine(withoutModuleSpecifier, sourceFile)) {
    return createTextSpanFromRange(withoutModuleSpecifier);
  }
}
function getPotentiallyInvalidImportSpecifier(namedBindings) {
  var _a;
  return find(
    (_a = tryCast(namedBindings, isNamedImports)) == null ? void 0 : _a.elements,
    (e) => {
      var _a2;
      return !e.propertyName && isStringANonContextualKeyword(e.name.text) && ((_a2 = findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) == null ? void 0 : _a2.kind) !== 28 /* CommaToken */;
    }
  );
}
function couldBeTypeOnlyImportSpecifier(importSpecifier, contextToken) {
  return isImportSpecifier(importSpecifier) && (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && isTypeKeywordTokenOrIdentifier(contextToken));
}
function canCompleteFromNamedBindings(namedBindings) {
  if (!isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier) || namedBindings.parent.name) {
    return false;
  }
  if (isNamedImports(namedBindings)) {
    const invalidNamedImport = getPotentiallyInvalidImportSpecifier(namedBindings);
    const validImports = invalidNamedImport ? namedBindings.elements.indexOf(invalidNamedImport) : namedBindings.elements.length;
    return validImports < 2;
  }
  return true;
}
function isModuleSpecifierMissingOrEmpty(specifier) {
  var _a;
  if (nodeIsMissing(specifier))
    return true;
  return !((_a = tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)) == null ? void 0 : _a.text);
}
function getVariableOrParameterDeclaration(contextToken, location) {
  if (!contextToken)
    return;
  const possiblyParameterDeclaration = findAncestor(contextToken, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent));
  const possiblyVariableDeclaration = findAncestor(location, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node));
  return possiblyParameterDeclaration || possiblyVariableDeclaration;
}
function isArrowFunctionBody(node) {
  return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || // const a = () => /**/;
  node.kind === 39 /* EqualsGreaterThanToken */);
}
function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Map()) {
  return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(skipAlias(symbol.exportSymbol || symbol, checker));
  function nonAliasCanBeReferencedAtTypeLocation(symbol2) {
    return !!(symbol2.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */) && addToSeen(seenModules, getSymbolId(symbol2)) && checker.getExportsOfModule(symbol2).some((e) => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules));
  }
}
function isDeprecated(symbol, checker) {
  const declarations = skipAlias(symbol, checker).declarations;
  return !!length(declarations) && every(declarations, isDeprecatedDeclaration);
}
function charactersFuzzyMatchInString(identifierString, lowercaseCharacters) {
  if (lowercaseCharacters.length === 0) {
    return true;
  }
  let matchedFirstCharacter = false;
  let prevChar;
  let characterIndex = 0;
  const len = identifierString.length;
  for (let strIndex = 0; strIndex < len; strIndex++) {
    const strChar = identifierString.charCodeAt(strIndex);
    const testChar = lowercaseCharacters.charCodeAt(characterIndex);
    if (strChar === testChar || strChar === toUpperCharCode(testChar)) {
      matchedFirstCharacter || (matchedFirstCharacter = prevChar === void 0 || // Beginning of word
      97 /* a */ <= prevChar && prevChar <= 122 /* z */ && 65 /* A */ <= strChar && strChar <= 90 /* Z */ || // camelCase transition
      prevChar === 95 /* _ */ && strChar !== 95 /* _ */);
      if (matchedFirstCharacter) {
        characterIndex++;
      }
      if (characterIndex === lowercaseCharacters.length) {
        return true;
      }
    }
    prevChar = strChar;
  }
  return false;
}
function toUpperCharCode(charCode) {
  if (97 /* a */ <= charCode && charCode <= 122 /* z */) {
    return charCode - 32;
  }
  return charCode;
}

// src/services/_namespaces/ts.Completions.StringCompletions.ts
var ts_Completions_StringCompletions_exports = {};
__export(ts_Completions_StringCompletions_exports, {
  getStringLiteralCompletionDetails: () => getStringLiteralCompletionDetails,
  getStringLiteralCompletions: () => getStringLiteralCompletions
});

// src/services/stringCompletions.ts
var kindPrecedence = {
  ["directory" /* directory */]: 0,
  ["script" /* scriptElement */]: 1,
  ["external module name" /* externalModuleName */]: 2
};
function createNameAndKindSet() {
  const map2 = /* @__PURE__ */ new Map();
  function add(value) {
    const existing = map2.get(value.name);
    if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) {
      map2.set(value.name, value);
    }
  }
  return {
    add,
    has: map2.has.bind(map2),
    values: map2.values.bind(map2)
  };
}
function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences, includeSymbol) {
  if (isInReferenceComment(sourceFile, position)) {
    const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host);
    return entries && convertPathCompletions(entries);
  }
  if (isInString(sourceFile, position, contextToken)) {
    if (!contextToken || !isStringLiteralLike(contextToken))
      return void 0;
    const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences);
    return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol);
  }
}
function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol) {
  if (completion === void 0) {
    return void 0;
  }
  const optionalReplacementSpan = createTextSpanFromStringLiteralLikeContent(contextToken);
  switch (completion.kind) {
    case 0 /* Paths */:
      return convertPathCompletions(completion.paths);
    case 1 /* Properties */: {
      const entries = createSortedArray();
      getCompletionEntriesFromSymbols(
        completion.symbols,
        entries,
        contextToken,
        contextToken,
        sourceFile,
        position,
        sourceFile,
        host,
        program,
        99 /* ESNext */,
        log,
        4 /* String */,
        preferences,
        options,
        /*formatContext*/
        void 0,
        /*isTypeOnlyLocation*/
        void 0,
        /*propertyAccessToConvert*/
        void 0,
        /*jsxIdentifierExpected*/
        void 0,
        /*isJsxInitializer*/
        void 0,
        /*importStatementCompletion*/
        void 0,
        /*recommendedCompletion*/
        void 0,
        /*symbolToOriginInfoMap*/
        void 0,
        /*symbolToSortTextMap*/
        void 0,
        /*isJsxIdentifierExpected*/
        void 0,
        /*isRightOfOpenTag*/
        void 0,
        includeSymbol
      );
      return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries };
    }
    case 2 /* Types */: {
      const entries = completion.types.map((type) => ({
        name: type.value,
        kindModifiers: "" /* none */,
        kind: "string" /* string */,
        sortText: SortText.LocationPriority,
        replacementSpan: getReplacementSpanForContextToken(contextToken)
      }));
      return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, optionalReplacementSpan, entries };
    }
    default:
      return Debug.assertNever(completion);
  }
}
function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) {
  if (!contextToken || !isStringLiteralLike(contextToken))
    return void 0;
  const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences);
  return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken);
}
function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
  switch (completion.kind) {
    case 0 /* Paths */: {
      const match = find(completion.paths, (p) => p.name === name);
      return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]);
    }
    case 1 /* Properties */: {
      const match = find(completion.symbols, (s) => s.name === name);
      return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken);
    }
    case 2 /* Types */:
      return find(completion.types, (t) => t.value === name) ? createCompletionDetails(name, "" /* none */, "string" /* string */, [textPart(name)]) : void 0;
    default:
      return Debug.assertNever(completion);
  }
}
function convertPathCompletions(pathCompletions) {
  const isGlobalCompletion = false;
  const isNewIdentifierLocation = true;
  const entries = pathCompletions.map(({ name, kind, span, extension }) => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span }));
  return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries };
}
function kindModifiersFromExtension(extension) {
  switch (extension) {
    case ".d.ts" /* Dts */:
      return ".d.ts" /* dtsModifier */;
    case ".js" /* Js */:
      return ".js" /* jsModifier */;
    case ".json" /* Json */:
      return ".json" /* jsonModifier */;
    case ".jsx" /* Jsx */:
      return ".jsx" /* jsxModifier */;
    case ".ts" /* Ts */:
      return ".ts" /* tsModifier */;
    case ".tsx" /* Tsx */:
      return ".tsx" /* tsxModifier */;
    case ".d.mts" /* Dmts */:
      return ".d.mts" /* dmtsModifier */;
    case ".mjs" /* Mjs */:
      return ".mjs" /* mjsModifier */;
    case ".mts" /* Mts */:
      return ".mts" /* mtsModifier */;
    case ".d.cts" /* Dcts */:
      return ".d.cts" /* dctsModifier */;
    case ".cjs" /* Cjs */:
      return ".cjs" /* cjsModifier */;
    case ".cts" /* Cts */:
      return ".cts" /* ctsModifier */;
    case ".tsbuildinfo" /* TsBuildInfo */:
      return Debug.fail(`Extension ${".tsbuildinfo" /* TsBuildInfo */} is unsupported.`);
    case void 0:
      return "" /* none */;
    default:
      return Debug.assertNever(extension);
  }
}
function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) {
  const parent2 = walkUpParentheses(node.parent);
  switch (parent2.kind) {
    case 200 /* LiteralType */: {
      const grandParent = walkUpParentheses(parent2.parent);
      if (grandParent.kind === 204 /* ImportType */) {
        return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) };
      }
      return fromUnionableLiteralType(grandParent);
    }
    case 302 /* PropertyAssignment */:
      if (isObjectLiteralExpression(parent2.parent) && parent2.name === node) {
        return stringLiteralCompletionsForObjectLiteral(typeChecker, parent2.parent);
      }
      return fromContextualType() || fromContextualType(0 /* None */);
    case 211 /* ElementAccessExpression */: {
      const { expression, argumentExpression } = parent2;
      if (node === skipParentheses(argumentExpression)) {
        return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
      }
      return void 0;
    }
    case 212 /* CallExpression */:
    case 213 /* NewExpression */:
    case 290 /* JsxAttribute */:
      if (!isRequireCallArgument(node) && !isImportCall(parent2)) {
        const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 290 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile);
        return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(0 /* None */);
      }
    case 271 /* ImportDeclaration */:
    case 277 /* ExportDeclaration */:
    case 282 /* ExternalModuleReference */:
      return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) };
    case 295 /* CaseClause */:
      const tracker = newCaseClauseTracker(typeChecker, parent2.parent.clauses);
      const contextualTypes = fromContextualType();
      if (!contextualTypes) {
        return;
      }
      const literals = contextualTypes.types.filter((literal) => !tracker.hasValue(literal.value));
      return { kind: 2 /* Types */, types: literals, isNewIdentifier: false };
    default:
      return fromContextualType() || fromContextualType(0 /* None */);
  }
  function fromUnionableLiteralType(grandParent) {
    switch (grandParent.kind) {
      case 232 /* ExpressionWithTypeArguments */:
      case 182 /* TypeReference */: {
        const typeArgument = findAncestor(parent2, (n) => n.parent === grandParent);
        if (typeArgument) {
          return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false };
        }
        return void 0;
      }
      case 198 /* IndexedAccessType */:
        const { indexType, objectType } = grandParent;
        if (!rangeContainsPosition(indexType, position)) {
          return void 0;
        }
        return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType));
      case 191 /* UnionType */: {
        const result = fromUnionableLiteralType(walkUpParentheses(grandParent.parent));
        if (!result) {
          return void 0;
        }
        const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent2);
        if (result.kind === 1 /* Properties */) {
          return { kind: 1 /* Properties */, symbols: result.symbols.filter((sym) => !contains(alreadyUsedTypes, sym.name)), hasIndexSignature: result.hasIndexSignature };
        }
        return { kind: 2 /* Types */, types: result.types.filter((t) => !contains(alreadyUsedTypes, t.value)), isNewIdentifier: false };
      }
      default:
        return void 0;
    }
  }
  function fromContextualType(contextFlags = 4 /* Completions */) {
    const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags));
    if (!types.length) {
      return;
    }
    return { kind: 2 /* Types */, types, isNewIdentifier: false };
  }
}
function walkUpParentheses(node) {
  switch (node.kind) {
    case 195 /* ParenthesizedType */:
      return walkUpParenthesizedTypes(node);
    case 216 /* ParenthesizedExpression */:
      return walkUpParenthesizedExpressions(node);
    default:
      return node;
  }
}
function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
  return mapDefined(union.types, (type) => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0);
}
function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker) {
  let isNewIdentifier = false;
  const uniques = /* @__PURE__ */ new Map();
  const candidates = [];
  const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg;
  checker.getResolvedSignatureForStringLiteralCompletions(call, editingArgument, candidates);
  const types = flatMap(candidates, (candidate) => {
    if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length)
      return;
    let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex);
    if (isJsxOpeningLikeElement(call)) {
      const propType = checker.getTypeOfPropertyOfType(type, getTextOfJsxAttributeName(editingArgument.name));
      if (propType) {
        type = propType;
      }
    }
    isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */);
    return getStringLiteralTypes(type, uniques);
  });
  return length(types) ? { kind: 2 /* Types */, types, isNewIdentifier } : void 0;
}
function stringLiteralCompletionsFromProperties(type) {
  return type && {
    kind: 1 /* Properties */,
    symbols: filter(type.getApparentProperties(), (prop) => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))),
    hasIndexSignature: hasIndexSignature(type)
  };
}
function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpression) {
  const contextualType = checker.getContextualType(objectLiteralExpression);
  if (!contextualType)
    return void 0;
  const completionsType = checker.getContextualType(objectLiteralExpression, 4 /* Completions */);
  const symbols = getPropertiesForObjectExpression(
    contextualType,
    completionsType,
    objectLiteralExpression,
    checker
  );
  return {
    kind: 1 /* Properties */,
    symbols,
    hasIndexSignature: hasIndexSignature(contextualType)
  };
}
function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Map()) {
  if (!type)
    return emptyArray;
  type = skipConstraint(type);
  return type.isUnion() ? flatMap(type.types, (t) => getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && addToSeen(uniques, type.value) ? [type] : emptyArray;
}
function nameAndKind(name, kind, extension) {
  return { name, kind, extension };
}
function directoryResult(name) {
  return nameAndKind(
    name,
    "directory" /* directory */,
    /*extension*/
    void 0
  );
}
function addReplacementSpans(text, textStart, names) {
  const span = getDirectoryFragmentTextSpan(text, textStart);
  const wholeSpan = text.length === 0 ? void 0 : createTextSpan(textStart, text.length);
  return names.map(({ name, kind, extension }) => Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span });
}
function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) {
  return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences));
}
function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) {
  const literalValue = normalizeSlashes(node.text);
  const mode = isStringLiteralLike(node) ? getModeForUsageLocation(sourceFile, node) : void 0;
  const scriptPath = sourceFile.path;
  const scriptDirectory = getDirectoryPath(scriptPath);
  const extensionOptions = getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile, typeChecker, preferences, mode);
  return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, extensionOptions, typeChecker);
}
function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile, typeChecker, preferences, resolutionMode) {
  return {
    extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker)),
    referenceKind,
    importingSourceFile,
    endingPreference: preferences == null ? void 0 : preferences.importModuleSpecifierEnding,
    resolutionMode
  };
}
function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) {
  if (compilerOptions.rootDirs) {
    return getCompletionEntriesForDirectoryFragmentWithRootDirs(
      compilerOptions.rootDirs,
      literalValue,
      scriptDirectory,
      extensionOptions,
      compilerOptions,
      host,
      scriptPath
    );
  } else {
    return arrayFrom(getCompletionEntriesForDirectoryFragment(
      literalValue,
      scriptDirectory,
      extensionOptions,
      host,
      /*moduleSpecifierIsRelative*/
      false,
      scriptPath
    ).values());
  }
}
function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) {
  const ambientModulesExtensions = !typeChecker ? [] : mapDefined(
    typeChecker.getAmbientModules(),
    (module2) => {
      const name = module2.name.slice(1, -1);
      if (!name.startsWith("*.") || name.includes("/"))
        return;
      return name.slice(1);
    }
  );
  const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions];
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  return moduleResolutionUsesNodeModules(moduleResolution) ? getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) : extensions;
}
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
  rootDirs = rootDirs.map((rootDirectory) => normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory)));
  const relativeDirectory = firstDefined(rootDirs, (rootDirectory) => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0);
  return deduplicate(
    [...rootDirs.map((rootDirectory) => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory],
    equateStringsCaseSensitive,
    compareStringsCaseSensitive
  );
}
function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
  const basePath = compilerOptions.project || host.getCurrentDirectory();
  const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
  const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
  return flatMap(baseDirectories, (baseDirectory) => arrayFrom(getCompletionEntriesForDirectoryFragment(
    fragment,
    baseDirectory,
    extensionOptions,
    host,
    /*moduleSpecifierIsRelative*/
    true,
    exclude
  ).values()));
}
function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) {
  var _a;
  if (fragment === void 0) {
    fragment = "";
  }
  fragment = normalizeSlashes(fragment);
  if (!hasTrailingDirectorySeparator(fragment)) {
    fragment = getDirectoryPath(fragment);
  }
  if (fragment === "") {
    fragment = "." + directorySeparator;
  }
  fragment = ensureTrailingDirectorySeparator(fragment);
  const absolutePath = resolvePath(scriptDirectory, fragment);
  const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath);
  if (!moduleSpecifierIsRelative) {
    const packageJsonPath = findPackageJson(baseDirectory, host);
    if (packageJsonPath) {
      const packageJson = readJson(packageJsonPath, host);
      const typesVersions = packageJson.typesVersions;
      if (typeof typesVersions === "object") {
        const versionPaths = (_a = getPackageJsonTypesVersionsPaths(typesVersions)) == null ? void 0 : _a.paths;
        if (versionPaths) {
          const packageDirectory = getDirectoryPath(packageJsonPath);
          const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length);
          if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) {
            return result;
          }
        }
      }
    }
  }
  const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
  if (!tryDirectoryExists(host, baseDirectory))
    return result;
  const files = tryReadDirectory(
    host,
    baseDirectory,
    extensionOptions.extensionsToSearch,
    /*exclude*/
    void 0,
    /*include*/
    ["./*"]
  );
  if (files) {
    for (let filePath of files) {
      filePath = normalizePath(filePath);
      if (exclude && comparePaths(filePath, exclude, scriptDirectory, ignoreCase) === 0 /* EqualTo */) {
        continue;
      }
      const { name, extension } = getFilenameWithExtensionOption(getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions);
      result.add(nameAndKind(name, "script" /* scriptElement */, extension));
    }
  }
  const directories = tryGetDirectories(host, baseDirectory);
  if (directories) {
    for (const directory of directories) {
      const directoryName = getBaseFileName(normalizePath(directory));
      if (directoryName !== "@types") {
        result.add(directoryResult(directoryName));
      }
    }
  }
  return result;
}
function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions) {
  const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name);
  if (nonJsResult) {
    return { name: nonJsResult, extension: tryGetExtensionFromPath2(nonJsResult) };
  }
  if (extensionOptions.referenceKind === 0 /* Filename */) {
    return { name, extension: tryGetExtensionFromPath2(name) };
  }
  const endingPreference = getModuleSpecifierEndingPreference(extensionOptions.endingPreference, extensionOptions.resolutionMode, compilerOptions, extensionOptions.importingSourceFile);
  if (endingPreference === 3 /* TsExtension */) {
    if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) {
      return { name, extension: tryGetExtensionFromPath2(name) };
    }
    const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions);
    return outputExtension2 ? { name: changeExtension(name, outputExtension2), extension: outputExtension2 } : { name, extension: tryGetExtensionFromPath2(name) };
  }
  if ((endingPreference === 0 /* Minimal */ || endingPreference === 1 /* Index */) && fileExtensionIsOneOf(name, [".js" /* Js */, ".jsx" /* Jsx */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */])) {
    return { name: removeFileExtension(name), extension: tryGetExtensionFromPath2(name) };
  }
  const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions);
  return outputExtension ? { name: changeExtension(name, outputExtension), extension: outputExtension } : { name, extension: tryGetExtensionFromPath2(name) };
}
function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) {
  const getPatternsForKey = (key) => paths[key];
  const comparePaths2 = (a, b) => {
    const patternA = tryParsePattern(a);
    const patternB = tryParsePattern(b);
    const lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length;
    const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length;
    return compareValues(lengthB, lengthA);
  };
  return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, getOwnKeys(paths), getPatternsForKey, comparePaths2);
}
function addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths2) {
  let pathResults = [];
  let matchedPath;
  for (const key of keys) {
    if (key === ".")
      continue;
    const keyWithoutLeadingDotSlash = key.replace(/^\.\//, "");
    const patterns = getPatternsForKey(key);
    if (patterns) {
      const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash);
      if (!pathPattern)
        continue;
      const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment);
      const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(key, matchedPath) === -1 /* LessThan */);
      if (isLongestMatch) {
        matchedPath = key;
        pathResults = pathResults.filter((r) => !r.matchedPattern);
      }
      if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(key, matchedPath) !== 1 /* GreaterThan */) {
        pathResults.push({
          matchedPattern: isMatch,
          results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host).map(({ name, kind, extension }) => nameAndKind(name, kind, extension))
        });
      }
    }
  }
  pathResults.forEach((pathResult) => pathResult.results.forEach((r) => result.add(r)));
  return matchedPath !== void 0;
}
function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, extensionOptions, typeChecker) {
  const { baseUrl, paths } = compilerOptions;
  const result = createNameAndKindSet();
  const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
  if (baseUrl) {
    const absolute = normalizePath(combinePaths(host.getCurrentDirectory(), baseUrl));
    getCompletionEntriesForDirectoryFragment(
      fragment,
      absolute,
      extensionOptions,
      host,
      /*moduleSpecifierIsRelative*/
      false,
      /*exclude*/
      void 0,
      result
    );
  }
  if (paths) {
    const absolute = getPathsBasePath(compilerOptions, host);
    addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths);
  }
  const fragmentDirectory = getFragmentDirectory(fragment);
  for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) {
    result.add(nameAndKind(
      ambientName,
      "external module name" /* externalModuleName */,
      /*extension*/
      void 0
    ));
  }
  getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result);
  if (moduleResolutionUsesNodeModules(moduleResolution)) {
    let foundGlobal = false;
    if (fragmentDirectory === void 0) {
      for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) {
        const moduleResult = nameAndKind(
          moduleName,
          "external module name" /* externalModuleName */,
          /*extension*/
          void 0
        );
        if (!result.has(moduleResult.name)) {
          foundGlobal = true;
          result.add(moduleResult);
        }
      }
    }
    if (!foundGlobal) {
      let ancestorLookup = (ancestor) => {
        const nodeModules = combinePaths(ancestor, "node_modules");
        if (tryDirectoryExists(host, nodeModules)) {
          getCompletionEntriesForDirectoryFragment(
            fragment,
            nodeModules,
            extensionOptions,
            host,
            /*moduleSpecifierIsRelative*/
            false,
            /*exclude*/
            void 0,
            result
          );
        }
      };
      if (fragmentDirectory && getResolvePackageJsonExports(compilerOptions)) {
        const nodeModulesDirectoryLookup = ancestorLookup;
        ancestorLookup = (ancestor) => {
          const components = getPathComponents(fragment);
          components.shift();
          let packagePath = components.shift();
          if (!packagePath) {
            return nodeModulesDirectoryLookup(ancestor);
          }
          if (startsWith(packagePath, "@")) {
            const subName = components.shift();
            if (!subName) {
              return nodeModulesDirectoryLookup(ancestor);
            }
            packagePath = combinePaths(packagePath, subName);
          }
          const packageDirectory = combinePaths(ancestor, "node_modules", packagePath);
          const packageFile = combinePaths(packageDirectory, "package.json");
          if (tryFileExists(host, packageFile)) {
            const packageJson = readJson(packageFile, host);
            const exports = packageJson.exports;
            if (exports) {
              if (typeof exports !== "object" || exports === null) {
                return;
              }
              const keys = getOwnKeys(exports);
              const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : "");
              const conditions = mode === 99 /* ESNext */ ? ["node", "import", "types"] : ["node", "require", "types"];
              addCompletionEntriesFromPathsOrExports(
                result,
                fragmentSubpath,
                packageDirectory,
                extensionOptions,
                host,
                keys,
                (key) => singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)),
                comparePatternKeys
              );
              return;
            }
          }
          return nodeModulesDirectoryLookup(ancestor);
        };
      }
      forEachAncestorDirectory(scriptPath, ancestorLookup);
    }
  }
  return arrayFrom(result.values());
}
function getPatternFromFirstMatchingCondition(target, conditions) {
  if (typeof target === "string") {
    return target;
  }
  if (target && typeof target === "object" && !isArray(target)) {
    for (const condition in target) {
      if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) {
        const pattern = target[condition];
        return getPatternFromFirstMatchingCondition(pattern, conditions);
      }
    }
  }
}
function getFragmentDirectory(fragment) {
  return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0;
}
function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, host) {
  if (!endsWith(path, "*")) {
    return !stringContains(path, "*") ? justPathMappingName(path, "script" /* scriptElement */) : emptyArray;
  }
  const pathPrefix = path.slice(0, path.length - 1);
  const remainingFragment = tryRemovePrefix(fragment, pathPrefix);
  if (remainingFragment === void 0) {
    const starIsFullPathComponent = path[path.length - 2] === "/";
    return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */) : flatMap(patterns, (pattern) => {
      var _a;
      return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest }));
    });
  }
  return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host));
  function justPathMappingName(name, kind) {
    return startsWith(name, fragment) ? [{ name: removeTrailingDirectorySeparator(name), kind, extension: void 0 }] : emptyArray;
  }
}
function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) {
  if (!host.readDirectory) {
    return void 0;
  }
  const parsed = tryParsePattern(pattern);
  if (parsed === void 0 || isString(parsed)) {
    return void 0;
  }
  const normalizedPrefix = resolvePath(parsed.prefix);
  const normalizedPrefixDirectory = hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : getDirectoryPath(normalizedPrefix);
  const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix);
  const fragmentHasPath = containsSlash(fragment);
  const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0;
  const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
  const normalizedSuffix = normalizePath(parsed.suffix);
  const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory));
  const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase;
  const includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*";
  const matches = mapDefined(tryReadDirectory(
    host,
    baseDirectory,
    extensionOptions.extensionsToSearch,
    /*exclude*/
    void 0,
    [includeGlob]
  ), (match) => {
    const trimmedWithPattern = trimPrefixAndSuffix(match);
    if (trimmedWithPattern) {
      if (containsSlash(trimmedWithPattern)) {
        return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]);
      }
      const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions);
      return nameAndKind(name, "script" /* scriptElement */, extension);
    }
  });
  const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir));
  return [...matches, ...directories];
  function trimPrefixAndSuffix(path) {
    const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix);
    return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner);
  }
}
function withoutStartAndEnd(s, start2, end) {
  return startsWith(s, start2) && endsWith(s, end) ? s.slice(start2.length, s.length - end.length) : void 0;
}
function removeLeadingDirectorySeparator(path) {
  return path[0] === directorySeparator ? path.slice(1) : path;
}
function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) {
  const ambientModules = checker.getAmbientModules().map((sym) => stripQuotes(sym.name));
  const nonRelativeModuleNames = ambientModules.filter((moduleName) => startsWith(moduleName, fragment) && moduleName.indexOf("*") < 0);
  if (fragmentDirectory !== void 0) {
    const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory);
    return nonRelativeModuleNames.map((nonRelativeModuleName) => removePrefix(nonRelativeModuleName, moduleNameWithSeparator));
  }
  return nonRelativeModuleNames;
}
function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
  const token = getTokenAtPosition(sourceFile, position);
  const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
  const range = commentRanges && find(commentRanges, (commentRange) => position >= commentRange.pos && position <= commentRange.end);
  if (!range) {
    return void 0;
  }
  const text = sourceFile.text.slice(range.pos, position);
  const match = tripleSlashDirectiveFragmentRegex.exec(text);
  if (!match) {
    return void 0;
  }
  const [, prefix, kind, toComplete] = match;
  const scriptPath = getDirectoryPath(sourceFile.path);
  const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(
    toComplete,
    scriptPath,
    getExtensionOptions(compilerOptions, 0 /* Filename */, sourceFile),
    host,
    /*moduleSpecifierIsRelative*/
    true,
    sourceFile.path
  ) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail();
  return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values()));
}
function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) {
  const seen = /* @__PURE__ */ new Map();
  const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray;
  for (const root of typeRoots) {
    getCompletionEntriesFromDirectories(root);
  }
  for (const packageJson of findPackageJsons(scriptPath, host)) {
    const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types");
    getCompletionEntriesFromDirectories(typesDir);
  }
  return result;
  function getCompletionEntriesFromDirectories(directory) {
    if (!tryDirectoryExists(host, directory))
      return;
    for (const typeDirectoryName of tryGetDirectories(host, directory)) {
      const packageName = unmangleScopedPackageName(typeDirectoryName);
      if (options.types && !contains(options.types, packageName))
        continue;
      if (fragmentDirectory === void 0) {
        if (!seen.has(packageName)) {
          result.add(nameAndKind(
            packageName,
            "external module name" /* externalModuleName */,
            /*extension*/
            void 0
          ));
          seen.set(packageName, true);
        }
      } else {
        const baseDirectory = combinePaths(directory, typeDirectoryName);
        const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host));
        if (remainingFragment !== void 0) {
          getCompletionEntriesForDirectoryFragment(
            remainingFragment,
            baseDirectory,
            extensionOptions,
            host,
            /*moduleSpecifierIsRelative*/
            false,
            /*exclude*/
            void 0,
            result
          );
        }
      }
    }
  }
}
function enumerateNodeModulesVisibleToScript(host, scriptPath) {
  if (!host.readFile || !host.fileExists)
    return emptyArray;
  const result = [];
  for (const packageJson of findPackageJsons(scriptPath, host)) {
    const contents = readJson(packageJson, host);
    for (const key of nodeModulesDependencyKeys) {
      const dependencies = contents[key];
      if (!dependencies)
        continue;
      for (const dep in dependencies) {
        if (hasProperty(dependencies, dep) && !startsWith(dep, "@types/")) {
          result.push(dep);
        }
      }
    }
  }
  return result;
}
function getDirectoryFragmentTextSpan(text, textStart) {
  const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf(altDirectorySeparator));
  const offset = index !== -1 ? index + 1 : 0;
  const length2 = text.length - offset;
  return length2 === 0 || isIdentifierText(text.substr(offset, length2), 99 /* ESNext */) ? void 0 : createTextSpan(textStart + offset, length2);
}
function isPathRelativeToScript(path) {
  if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) {
    const slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1;
    const slashCharCode = path.charCodeAt(slashIndex);
    return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */;
  }
  return false;
}
var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
function containsSlash(fragment) {
  return stringContains(fragment, directorySeparator);
}
function isRequireCallArgument(node) {
  return isCallExpression(node.parent) && firstOrUndefined(node.parent.arguments) === node && isIdentifier(node.parent.expression) && node.parent.expression.escapedText === "require";
}

// src/services/_namespaces/ts.FindAllReferences.ts
var ts_FindAllReferences_exports = {};
__export(ts_FindAllReferences_exports, {
  Core: () => Core,
  DefinitionKind: () => DefinitionKind,
  EntryKind: () => EntryKind,
  ExportKind: () => ExportKind2,
  FindReferencesUse: () => FindReferencesUse,
  ImportExport: () => ImportExport,
  createImportTracker: () => createImportTracker,
  findModuleReferences: () => findModuleReferences,
  findReferenceOrRenameEntries: () => findReferenceOrRenameEntries,
  findReferencedSymbols: () => findReferencedSymbols,
  getContextNode: () => getContextNode,
  getExportInfo: () => getExportInfo,
  getImplementationsAtPosition: () => getImplementationsAtPosition,
  getImportOrExportSymbol: () => getImportOrExportSymbol,
  getReferenceEntriesForNode: () => getReferenceEntriesForNode,
  getTextSpanOfEntry: () => getTextSpanOfEntry,
  isContextWithStartAndEndNode: () => isContextWithStartAndEndNode,
  isDeclarationOfSymbol: () => isDeclarationOfSymbol,
  nodeEntry: () => nodeEntry,
  toContextSpan: () => toContextSpan,
  toHighlightSpan: () => toHighlightSpan,
  toReferenceEntry: () => toReferenceEntry,
  toRenameLocation: () => toRenameLocation
});

// src/services/importTracker.ts
function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) {
  const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
  return (exportSymbol, exportInfo, isForRename) => {
    const { directImports, indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken);
    return { indirectUsers, ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) };
  };
}
var ExportKind2 = /* @__PURE__ */ ((ExportKind3) => {
  ExportKind3[ExportKind3["Named"] = 0] = "Named";
  ExportKind3[ExportKind3["Default"] = 1] = "Default";
  ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals";
  return ExportKind3;
})(ExportKind2 || {});
var ImportExport = /* @__PURE__ */ ((ImportExport2) => {
  ImportExport2[ImportExport2["Import"] = 0] = "Import";
  ImportExport2[ImportExport2["Export"] = 1] = "Export";
  return ImportExport2;
})(ImportExport || {});
function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { exportingModuleSymbol, exportKind }, checker, cancellationToken) {
  const markSeenDirectImport = nodeSeenTracker();
  const markSeenIndirectUser = nodeSeenTracker();
  const directImports = [];
  const isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
  const indirectUserDeclarations = isAvailableThroughGlobal ? void 0 : [];
  handleDirectImports(exportingModuleSymbol);
  return { directImports, indirectUsers: getIndirectUsers() };
  function getIndirectUsers() {
    if (isAvailableThroughGlobal) {
      return sourceFiles;
    }
    if (exportingModuleSymbol.declarations) {
      for (const decl of exportingModuleSymbol.declarations) {
        if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
          addIndirectUser(decl);
        }
      }
    }
    return indirectUserDeclarations.map(getSourceFileOfNode);
  }
  function handleDirectImports(exportingModuleSymbol2) {
    const theseDirectImports = getDirectImports(exportingModuleSymbol2);
    if (theseDirectImports) {
      for (const direct of theseDirectImports) {
        if (!markSeenDirectImport(direct)) {
          continue;
        }
        if (cancellationToken)
          cancellationToken.throwIfCancellationRequested();
        switch (direct.kind) {
          case 212 /* CallExpression */:
            if (isImportCall(direct)) {
              handleImportCall(direct);
              break;
            }
            if (!isAvailableThroughGlobal) {
              const parent2 = direct.parent;
              if (exportKind === 2 /* ExportEquals */ && parent2.kind === 259 /* VariableDeclaration */) {
                const { name } = parent2;
                if (name.kind === 80 /* Identifier */) {
                  directImports.push(name);
                  break;
                }
              }
            }
            break;
          case 80 /* Identifier */:
            break;
          case 270 /* ImportEqualsDeclaration */:
            handleNamespaceImport(
              direct,
              direct.name,
              hasSyntacticModifier(direct, 1 /* Export */),
              /*alreadyAddedDirect*/
              false
            );
            break;
          case 271 /* ImportDeclaration */:
            directImports.push(direct);
            const namedBindings = direct.importClause && direct.importClause.namedBindings;
            if (namedBindings && namedBindings.kind === 273 /* NamespaceImport */) {
              handleNamespaceImport(
                direct,
                namedBindings.name,
                /*isReExport*/
                false,
                /*alreadyAddedDirect*/
                true
              );
            } else if (!isAvailableThroughGlobal && isDefaultImport(direct)) {
              addIndirectUser(getSourceFileLikeForImportDeclaration(direct));
            }
            break;
          case 277 /* ExportDeclaration */:
            if (!direct.exportClause) {
              handleDirectImports(getContainingModuleSymbol(direct, checker));
            } else if (direct.exportClause.kind === 279 /* NamespaceExport */) {
              addIndirectUser(
                getSourceFileLikeForImportDeclaration(direct),
                /*addTransitiveDependencies*/
                true
              );
            } else {
              directImports.push(direct);
            }
            break;
          case 204 /* ImportType */:
            if (!isAvailableThroughGlobal && direct.isTypeOf && !direct.qualifier && isExported2(direct)) {
              addIndirectUser(
                direct.getSourceFile(),
                /*addTransitiveDependencies*/
                true
              );
            }
            directImports.push(direct);
            break;
          default:
            Debug.failBadSyntaxKind(direct, "Unexpected import kind.");
        }
      }
    }
  }
  function handleImportCall(importCall) {
    const top = findAncestor(importCall, isAmbientModuleDeclaration) || importCall.getSourceFile();
    addIndirectUser(
      top,
      /** addTransitiveDependencies */
      !!isExported2(
        importCall,
        /*stopAtAmbientModule*/
        true
      )
    );
  }
  function isExported2(node, stopAtAmbientModule = false) {
    return findAncestor(node, (node2) => {
      if (stopAtAmbientModule && isAmbientModuleDeclaration(node2))
        return "quit";
      return canHaveModifiers(node2) && some(node2.modifiers, isExportModifier);
    });
  }
  function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
    if (exportKind === 2 /* ExportEquals */) {
      if (!alreadyAddedDirect)
        directImports.push(importDeclaration);
    } else if (!isAvailableThroughGlobal) {
      const sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
      Debug.assert(sourceFileLike.kind === 311 /* SourceFile */ || sourceFileLike.kind === 266 /* ModuleDeclaration */);
      if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
        addIndirectUser(
          sourceFileLike,
          /*addTransitiveDependencies*/
          true
        );
      } else {
        addIndirectUser(sourceFileLike);
      }
    }
  }
  function addIndirectUser(sourceFileLike, addTransitiveDependencies = false) {
    Debug.assert(!isAvailableThroughGlobal);
    const isNew = markSeenIndirectUser(sourceFileLike);
    if (!isNew)
      return;
    indirectUserDeclarations.push(sourceFileLike);
    if (!addTransitiveDependencies)
      return;
    const moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
    if (!moduleSymbol)
      return;
    Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
    const directImports2 = getDirectImports(moduleSymbol);
    if (directImports2) {
      for (const directImport of directImports2) {
        if (!isImportTypeNode(directImport)) {
          addIndirectUser(
            getSourceFileLikeForImportDeclaration(directImport),
            /*addTransitiveDependencies*/
            true
          );
        }
      }
    }
  }
  function getDirectImports(moduleSymbol) {
    return allDirectImports.get(getSymbolId(moduleSymbol).toString());
  }
}
function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
  const importSearches = [];
  const singleReferences = [];
  function addSearch(location, symbol) {
    importSearches.push([location, symbol]);
  }
  if (directImports) {
    for (const decl of directImports) {
      handleImport(decl);
    }
  }
  return { importSearches, singleReferences };
  function handleImport(decl) {
    if (decl.kind === 270 /* ImportEqualsDeclaration */) {
      if (isExternalModuleImportEquals(decl)) {
        handleNamespaceImportLike(decl.name);
      }
      return;
    }
    if (decl.kind === 80 /* Identifier */) {
      handleNamespaceImportLike(decl);
      return;
    }
    if (decl.kind === 204 /* ImportType */) {
      if (decl.qualifier) {
        const firstIdentifier = getFirstIdentifier(decl.qualifier);
        if (firstIdentifier.escapedText === symbolName(exportSymbol)) {
          singleReferences.push(firstIdentifier);
        }
      } else if (exportKind === 2 /* ExportEquals */) {
        singleReferences.push(decl.argument.literal);
      }
      return;
    }
    if (decl.moduleSpecifier.kind !== 11 /* StringLiteral */) {
      return;
    }
    if (decl.kind === 277 /* ExportDeclaration */) {
      if (decl.exportClause && isNamedExports(decl.exportClause)) {
        searchForNamedImport(decl.exportClause);
      }
      return;
    }
    const { name, namedBindings } = decl.importClause || { name: void 0, namedBindings: void 0 };
    if (namedBindings) {
      switch (namedBindings.kind) {
        case 273 /* NamespaceImport */:
          handleNamespaceImportLike(namedBindings.name);
          break;
        case 274 /* NamedImports */:
          if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
            searchForNamedImport(namedBindings);
          }
          break;
        default:
          Debug.assertNever(namedBindings);
      }
    }
    if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === symbolEscapedNameNoDefault(exportSymbol))) {
      const defaultImportAlias = checker.getSymbolAtLocation(name);
      addSearch(name, defaultImportAlias);
    }
  }
  function handleNamespaceImportLike(importName) {
    if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) {
      addSearch(importName, checker.getSymbolAtLocation(importName));
    }
  }
  function searchForNamedImport(namedBindings) {
    if (!namedBindings) {
      return;
    }
    for (const element of namedBindings.elements) {
      const { name, propertyName } = element;
      if (!isNameMatch((propertyName || name).escapedText)) {
        continue;
      }
      if (propertyName) {
        singleReferences.push(propertyName);
        if (!isForRename || name.escapedText === exportSymbol.escapedName) {
          addSearch(name, checker.getSymbolAtLocation(name));
        }
      } else {
        const localSymbol = element.kind === 280 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) : checker.getSymbolAtLocation(name);
        addSearch(name, localSymbol);
      }
    }
  }
  function isNameMatch(name) {
    return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */;
  }
}
function findNamespaceReExports(sourceFileLike, name, checker) {
  const namespaceImportSymbol = checker.getSymbolAtLocation(name);
  return !!forEachPossibleImportOrExportStatement(sourceFileLike, (statement) => {
    if (!isExportDeclaration(statement))
      return;
    const { exportClause, moduleSpecifier } = statement;
    return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some((element) => checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol);
  });
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
  var _a;
  const refs = [];
  const checker = program.getTypeChecker();
  for (const referencingFile of sourceFiles) {
    const searchSourceFile = searchModuleSymbol.valueDeclaration;
    if ((searchSourceFile == null ? void 0 : searchSourceFile.kind) === 311 /* SourceFile */) {
      for (const ref of referencingFile.referencedFiles) {
        if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
          refs.push({ kind: "reference", referencingFile, ref });
        }
      }
      for (const ref of referencingFile.typeReferenceDirectives) {
        const referenced = (_a = program.getResolvedTypeReferenceDirectives().get(ref.fileName, ref.resolutionMode || referencingFile.impliedNodeFormat)) == null ? void 0 : _a.resolvedTypeReferenceDirective;
        if (referenced !== void 0 && referenced.resolvedFileName === searchSourceFile.fileName) {
          refs.push({ kind: "reference", referencingFile, ref });
        }
      }
    }
    forEachImport(referencingFile, (importDecl, moduleSpecifier) => {
      const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
      if (moduleSymbol === searchModuleSymbol) {
        refs.push(nodeIsSynthesized(importDecl) ? { kind: "implicit", literal: moduleSpecifier, referencingFile } : { kind: "import", literal: moduleSpecifier });
      }
    });
  }
  return refs;
}
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
  const map2 = /* @__PURE__ */ new Map();
  for (const sourceFile of sourceFiles) {
    if (cancellationToken)
      cancellationToken.throwIfCancellationRequested();
    forEachImport(sourceFile, (importDecl, moduleSpecifier) => {
      const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
      if (moduleSymbol) {
        const id = getSymbolId(moduleSymbol).toString();
        let imports = map2.get(id);
        if (!imports) {
          map2.set(id, imports = []);
        }
        imports.push(importDecl);
      }
    });
  }
  return map2;
}
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
  return forEach(sourceFileLike.kind === 311 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, (statement) => (
    // TODO: GH#18217
    action(statement) || isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action)
  ));
}
function forEachImport(sourceFile, action) {
  if (sourceFile.externalModuleIndicator || sourceFile.imports !== void 0) {
    for (const i of sourceFile.imports) {
      action(importFromModuleSpecifier(i), i);
    }
  } else {
    forEachPossibleImportOrExportStatement(sourceFile, (statement) => {
      switch (statement.kind) {
        case 277 /* ExportDeclaration */:
        case 271 /* ImportDeclaration */: {
          const decl = statement;
          if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) {
            action(decl, decl.moduleSpecifier);
          }
          break;
        }
        case 270 /* ImportEqualsDeclaration */: {
          const decl = statement;
          if (isExternalModuleImportEquals(decl)) {
            action(decl, decl.moduleReference.expression);
          }
          break;
        }
      }
    });
  }
}
function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
  return comingFromExport ? getExport() : getExport() || getImport();
  function getExport() {
    var _a;
    const { parent: parent2 } = node;
    const grandparent = parent2.parent;
    if (symbol.exportSymbol) {
      if (parent2.kind === 210 /* PropertyAccessExpression */) {
        return ((_a = symbol.declarations) == null ? void 0 : _a.some((d) => d === parent2)) && isBinaryExpression(grandparent) ? getSpecialPropertyExport(
          grandparent,
          /*useLhsSymbol*/
          false
        ) : void 0;
      } else {
        return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent2));
      }
    } else {
      const exportNode = getExportNode(parent2, node);
      if (exportNode && hasSyntacticModifier(exportNode, 1 /* Export */)) {
        if (isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) {
          if (comingFromExport) {
            return void 0;
          }
          const lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
          return { kind: 0 /* Import */, symbol: lhsSymbol };
        } else {
          return exportInfo(symbol, getExportKindForDeclaration(exportNode));
        }
      } else if (isNamespaceExport(parent2)) {
        return exportInfo(symbol, 0 /* Named */);
      } else if (isExportAssignment(parent2)) {
        return getExportAssignmentExport(parent2);
      } else if (isExportAssignment(grandparent)) {
        return getExportAssignmentExport(grandparent);
      } else if (isBinaryExpression(parent2)) {
        return getSpecialPropertyExport(
          parent2,
          /*useLhsSymbol*/
          true
        );
      } else if (isBinaryExpression(grandparent)) {
        return getSpecialPropertyExport(
          grandparent,
          /*useLhsSymbol*/
          true
        );
      } else if (isJSDocTypedefTag(parent2) || isJSDocCallbackTag(parent2)) {
        return exportInfo(symbol, 0 /* Named */);
      }
    }
    function getExportAssignmentExport(ex) {
      if (!ex.symbol.parent)
        return void 0;
      const exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */;
      return { kind: 1 /* Export */, symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind } };
    }
    function getSpecialPropertyExport(node2, useLhsSymbol) {
      let kind;
      switch (getAssignmentDeclarationKind(node2)) {
        case 1 /* ExportsProperty */:
          kind = 0 /* Named */;
          break;
        case 2 /* ModuleExports */:
          kind = 2 /* ExportEquals */;
          break;
        default:
          return void 0;
      }
      const sym = useLhsSymbol ? checker.getSymbolAtLocation(getNameOfAccessExpression(cast(node2.left, isAccessExpression))) : symbol;
      return sym && exportInfo(sym, kind);
    }
  }
  function getImport() {
    const isImport3 = isNodeImport(node);
    if (!isImport3)
      return void 0;
    let importedSymbol = checker.getImmediateAliasedSymbol(symbol);
    if (!importedSymbol)
      return void 0;
    importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
    if (importedSymbol.escapedName === "export=") {
      importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker);
      if (importedSymbol === void 0)
        return void 0;
    }
    const importedName = symbolEscapedNameNoDefault(importedSymbol);
    if (importedName === void 0 || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
      return { kind: 0 /* Import */, symbol: importedSymbol };
    }
  }
  function exportInfo(symbol2, kind) {
    const exportInfo2 = getExportInfo(symbol2, kind, checker);
    return exportInfo2 && { kind: 1 /* Export */, symbol: symbol2, exportInfo: exportInfo2 };
  }
  function getExportKindForDeclaration(node2) {
    return hasSyntacticModifier(node2, 1024 /* Default */) ? 1 /* Default */ : 0 /* Named */;
  }
}
function getExportEqualsLocalSymbol(importedSymbol, checker) {
  var _a, _b;
  if (importedSymbol.flags & 2097152 /* Alias */) {
    return checker.getImmediateAliasedSymbol(importedSymbol);
  }
  const decl = Debug.checkDefined(importedSymbol.valueDeclaration);
  if (isExportAssignment(decl)) {
    return (_a = tryCast(decl.expression, canHaveSymbol)) == null ? void 0 : _a.symbol;
  } else if (isBinaryExpression(decl)) {
    return (_b = tryCast(decl.right, canHaveSymbol)) == null ? void 0 : _b.symbol;
  } else if (isSourceFile(decl)) {
    return decl.symbol;
  }
  return void 0;
}
function getExportNode(parent2, node) {
  const declaration = isVariableDeclaration(parent2) ? parent2 : isBindingElement(parent2) ? walkUpBindingElementsAndPatterns(parent2) : void 0;
  if (declaration) {
    return parent2.name !== node ? void 0 : isCatchClause(declaration.parent) ? void 0 : isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : void 0;
  } else {
    return parent2;
  }
}
function isNodeImport(node) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 270 /* ImportEqualsDeclaration */:
      return parent2.name === node && isExternalModuleImportEquals(parent2);
    case 275 /* ImportSpecifier */:
      return !parent2.propertyName;
    case 272 /* ImportClause */:
    case 273 /* NamespaceImport */:
      Debug.assert(parent2.name === node);
      return true;
    case 207 /* BindingElement */:
      return isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(parent2.parent.parent);
    default:
      return false;
  }
}
function getExportInfo(exportSymbol, exportKind, checker) {
  const moduleSymbol = exportSymbol.parent;
  if (!moduleSymbol)
    return void 0;
  const exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol);
  return isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol, exportKind } : void 0;
}
function skipExportSpecifierSymbol(symbol, checker) {
  if (symbol.declarations) {
    for (const declaration of symbol.declarations) {
      if (isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
        return checker.getExportSpecifierLocalTargetSymbol(declaration) || symbol;
      } else if (isPropertyAccessExpression(declaration) && isModuleExportsAccessExpression(declaration.expression) && !isPrivateIdentifier(declaration.name)) {
        return checker.getSymbolAtLocation(declaration);
      } else if (isShorthandPropertyAssignment(declaration) && isBinaryExpression(declaration.parent.parent) && getAssignmentDeclarationKind(declaration.parent.parent) === 2 /* ModuleExports */) {
        return checker.getExportSpecifierLocalTargetSymbol(declaration.name);
      }
    }
  }
  return symbol;
}
function getContainingModuleSymbol(importer, checker) {
  return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
}
function getSourceFileLikeForImportDeclaration(node) {
  if (node.kind === 212 /* CallExpression */) {
    return node.getSourceFile();
  }
  const { parent: parent2 } = node;
  if (parent2.kind === 311 /* SourceFile */) {
    return parent2;
  }
  Debug.assert(parent2.kind === 267 /* ModuleBlock */);
  return cast(parent2.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
  return node.kind === 266 /* ModuleDeclaration */ && node.name.kind === 11 /* StringLiteral */;
}
function isExternalModuleImportEquals(eq) {
  return eq.moduleReference.kind === 282 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 11 /* StringLiteral */;
}

// src/services/findAllReferences.ts
var DefinitionKind = /* @__PURE__ */ ((DefinitionKind2) => {
  DefinitionKind2[DefinitionKind2["Symbol"] = 0] = "Symbol";
  DefinitionKind2[DefinitionKind2["Label"] = 1] = "Label";
  DefinitionKind2[DefinitionKind2["Keyword"] = 2] = "Keyword";
  DefinitionKind2[DefinitionKind2["This"] = 3] = "This";
  DefinitionKind2[DefinitionKind2["String"] = 4] = "String";
  DefinitionKind2[DefinitionKind2["TripleSlashReference"] = 5] = "TripleSlashReference";
  return DefinitionKind2;
})(DefinitionKind || {});
var EntryKind = /* @__PURE__ */ ((EntryKind2) => {
  EntryKind2[EntryKind2["Span"] = 0] = "Span";
  EntryKind2[EntryKind2["Node"] = 1] = "Node";
  EntryKind2[EntryKind2["StringLiteral"] = 2] = "StringLiteral";
  EntryKind2[EntryKind2["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty";
  EntryKind2[EntryKind2["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal";
  return EntryKind2;
})(EntryKind || {});
function nodeEntry(node, kind = 1 /* Node */) {
  return {
    kind,
    node: node.name || node,
    context: getContextNodeForNodeEntry(node)
  };
}
function isContextWithStartAndEndNode(node) {
  return node && node.kind === void 0;
}
function getContextNodeForNodeEntry(node) {
  if (isDeclaration(node)) {
    return getContextNode(node);
  }
  if (!node.parent)
    return void 0;
  if (!isDeclaration(node.parent) && !isExportAssignment(node.parent)) {
    if (isInJSFile(node)) {
      const binaryExpression = isBinaryExpression(node.parent) ? node.parent : isAccessExpression(node.parent) && isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ? node.parent.parent : void 0;
      if (binaryExpression && getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */) {
        return getContextNode(binaryExpression);
      }
    }
    if (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) {
      return node.parent.parent;
    } else if (isJsxSelfClosingElement(node.parent) || isLabeledStatement(node.parent) || isBreakOrContinueStatement(node.parent)) {
      return node.parent;
    } else if (isStringLiteralLike(node)) {
      const validImport = tryGetImportFromModuleSpecifier(node);
      if (validImport) {
        const declOrStatement = findAncestor(
          validImport,
          (node2) => isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2)
        );
        return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement;
      }
    }
    const propertyName = findAncestor(node, isComputedPropertyName);
    return propertyName ? getContextNode(propertyName.parent) : void 0;
  }
  if (node.parent.name === node || // node is name of declaration, use parent
  isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent
  (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || // Is default export
  node.kind === 90 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 1025 /* ExportDefault */)) {
    return getContextNode(node.parent);
  }
  return void 0;
}
function getContextNode(node) {
  if (!node)
    return void 0;
  switch (node.kind) {
    case 259 /* VariableDeclaration */:
      return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : isVariableStatement(node.parent.parent) ? node.parent.parent : isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent;
    case 207 /* BindingElement */:
      return getContextNode(node.parent.parent);
    case 275 /* ImportSpecifier */:
      return node.parent.parent.parent;
    case 280 /* ExportSpecifier */:
    case 273 /* NamespaceImport */:
      return node.parent.parent;
    case 272 /* ImportClause */:
    case 279 /* NamespaceExport */:
      return node.parent;
    case 225 /* BinaryExpression */:
      return isExpressionStatement(node.parent) ? node.parent : node;
    case 249 /* ForOfStatement */:
    case 248 /* ForInStatement */:
      return {
        start: node.initializer,
        end: node.expression
      };
    case 302 /* PropertyAssignment */:
    case 303 /* ShorthandPropertyAssignment */:
      return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(
        findAncestor(
          node.parent,
          (node2) => isBinaryExpression(node2) || isForInOrOfStatement(node2)
        )
      ) : node;
    default:
      return node;
  }
}
function toContextSpan(textSpan, sourceFile, context) {
  if (!context)
    return void 0;
  const contextSpan = isContextWithStartAndEndNode(context) ? getTextSpan(context.start, sourceFile, context.end) : getTextSpan(context, sourceFile);
  return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ? { contextSpan } : void 0;
}
var FindReferencesUse = /* @__PURE__ */ ((FindReferencesUse2) => {
  FindReferencesUse2[FindReferencesUse2["Other"] = 0] = "Other";
  FindReferencesUse2[FindReferencesUse2["References"] = 1] = "References";
  FindReferencesUse2[FindReferencesUse2["Rename"] = 2] = "Rename";
  return FindReferencesUse2;
})(FindReferencesUse || {});
function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
  const node = getTouchingPropertyName(sourceFile, position);
  const options = { use: 1 /* References */ };
  const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
  const checker = program.getTypeChecker();
  const adjustedNode = Core.getAdjustedNode(node, options);
  const symbol = isDefinitionForReference(adjustedNode) ? checker.getSymbolAtLocation(adjustedNode) : void 0;
  return !referencedSymbols || !referencedSymbols.length ? void 0 : mapDefined(referencedSymbols, ({ definition, references }) => (
    // Only include referenced symbols that have a valid definition.
    definition && {
      definition: checker.runWithCancellationToken(cancellationToken, (checker2) => definitionToReferencedSymbolDefinitionInfo(definition, checker2, node)),
      references: references.map((r) => toReferencedSymbolEntry(r, symbol))
    }
  ));
}
function isDefinitionForReference(node) {
  return node.kind === 90 /* DefaultKeyword */ || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node) || node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent);
}
function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) {
  const node = getTouchingPropertyName(sourceFile, position);
  let referenceEntries;
  const entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
  if (node.parent.kind === 210 /* PropertyAccessExpression */ || node.parent.kind === 207 /* BindingElement */ || node.parent.kind === 211 /* ElementAccessExpression */ || node.kind === 108 /* SuperKeyword */) {
    referenceEntries = entries && [...entries];
  } else if (entries) {
    const queue = createQueue(entries);
    const seenNodes = /* @__PURE__ */ new Map();
    while (!queue.isEmpty()) {
      const entry = queue.dequeue();
      if (!addToSeen(seenNodes, getNodeId(entry.node))) {
        continue;
      }
      referenceEntries = append(referenceEntries, entry);
      const entries2 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos);
      if (entries2) {
        queue.enqueue(...entries2);
      }
    }
  }
  const checker = program.getTypeChecker();
  return map(referenceEntries, (entry) => toImplementationLocation(entry, checker));
}
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
  if (node.kind === 311 /* SourceFile */) {
    return void 0;
  }
  const checker = program.getTypeChecker();
  if (node.parent.kind === 303 /* ShorthandPropertyAssignment */) {
    const result = [];
    Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, (node2) => result.push(nodeEntry(node2)));
    return result;
  } else if (node.kind === 108 /* SuperKeyword */ || isSuperProperty(node.parent)) {
    const symbol = checker.getSymbolAtLocation(node);
    return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
  } else {
    return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: 1 /* References */ });
  }
}
function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
  return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), (entry) => convertEntry(entry, node, program.getTypeChecker()));
}
function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) {
  return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
}
function flattenEntries(referenceSymbols) {
  return referenceSymbols && flatMap(referenceSymbols, (r) => r.references);
}
function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
  const info = (() => {
    switch (def.type) {
      case 0 /* Symbol */: {
        const { symbol } = def;
        const { displayParts: displayParts2, kind: kind2 } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode);
        const name2 = displayParts2.map((p) => p.text).join("");
        const declaration = symbol.declarations && firstOrUndefined(symbol.declarations);
        const node = declaration ? getNameOfDeclaration(declaration) || declaration : originalNode;
        return {
          ...getFileAndTextSpanFromNode(node),
          name: name2,
          kind: kind2,
          displayParts: displayParts2,
          context: getContextNode(declaration)
        };
      }
      case 1 /* Label */: {
        const { node } = def;
        return { ...getFileAndTextSpanFromNode(node), name: node.text, kind: "label" /* label */, displayParts: [displayPart(node.text, 17 /* text */)] };
      }
      case 2 /* Keyword */: {
        const { node } = def;
        const name2 = tokenToString(node.kind);
        return { ...getFileAndTextSpanFromNode(node), name: name2, kind: "keyword" /* keyword */, displayParts: [{ text: name2, kind: "keyword" /* keyword */ }] };
      }
      case 3 /* This */: {
        const { node } = def;
        const symbol = checker.getSymbolAtLocation(node);
        const displayParts2 = symbol && ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(
          checker,
          symbol,
          node.getSourceFile(),
          getContainerNode(node),
          node
        ).displayParts || [textPart("this")];
        return { ...getFileAndTextSpanFromNode(node), name: "this", kind: "var" /* variableElement */, displayParts: displayParts2 };
      }
      case 4 /* String */: {
        const { node } = def;
        return {
          ...getFileAndTextSpanFromNode(node),
          name: node.text,
          kind: "var" /* variableElement */,
          displayParts: [displayPart(getTextOfNode(node), 8 /* stringLiteral */)]
        };
      }
      case 5 /* TripleSlashReference */: {
        return {
          textSpan: createTextSpanFromRange(def.reference),
          sourceFile: def.file,
          name: def.reference.fileName,
          kind: "string" /* string */,
          displayParts: [displayPart(`"${def.reference.fileName}"`, 8 /* stringLiteral */)]
        };
      }
      default:
        return Debug.assertNever(def);
    }
  })();
  const { sourceFile, textSpan, name, kind, displayParts, context } = info;
  return {
    containerKind: "" /* unknown */,
    containerName: "",
    fileName: sourceFile.fileName,
    kind,
    name,
    textSpan,
    displayParts,
    ...toContextSpan(textSpan, sourceFile, context)
  };
}
function getFileAndTextSpanFromNode(node) {
  const sourceFile = node.getSourceFile();
  return {
    sourceFile,
    textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile)
  };
}
function getDefinitionKindAndDisplayParts(symbol, checker, node) {
  const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
  const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node;
  const { displayParts, symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning);
  return { displayParts, kind: symbolKind };
}
function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) {
  return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) };
}
function toReferencedSymbolEntry(entry, symbol) {
  const referenceEntry = toReferenceEntry(entry);
  if (!symbol)
    return referenceEntry;
  return {
    ...referenceEntry,
    isDefinition: entry.kind !== 0 /* Span */ && isDeclarationOfSymbol(entry.node, symbol)
  };
}
function toReferenceEntry(entry) {
  const documentSpan = entryToDocumentSpan(entry);
  if (entry.kind === 0 /* Span */) {
    return { ...documentSpan, isWriteAccess: false };
  }
  const { kind, node } = entry;
  return {
    ...documentSpan,
    isWriteAccess: isWriteAccessForReference(node),
    isInString: kind === 2 /* StringLiteral */ ? true : void 0
  };
}
function entryToDocumentSpan(entry) {
  if (entry.kind === 0 /* Span */) {
    return { textSpan: entry.textSpan, fileName: entry.fileName };
  } else {
    const sourceFile = entry.node.getSourceFile();
    const textSpan = getTextSpan(entry.node, sourceFile);
    return {
      textSpan,
      fileName: sourceFile.fileName,
      ...toContextSpan(textSpan, sourceFile, entry.context)
    };
  }
}
function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) {
  if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) {
    const { node, kind } = entry;
    const parent2 = node.parent;
    const name = originalNode.text;
    const isShorthandAssignment = isShorthandPropertyAssignment(parent2);
    if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(parent2) && parent2.name === node && parent2.dotDotDotToken === void 0) {
      const prefixColon = { prefixText: name + ": " };
      const suffixColon = { suffixText: ": " + name };
      if (kind === 3 /* SearchedLocalFoundProperty */) {
        return prefixColon;
      }
      if (kind === 4 /* SearchedPropertyFoundLocal */) {
        return suffixColon;
      }
      if (isShorthandAssignment) {
        const grandParent = parent2.parent;
        if (isObjectLiteralExpression(grandParent) && isBinaryExpression(grandParent.parent) && isModuleExportsAccessExpression(grandParent.parent.left)) {
          return prefixColon;
        }
        return suffixColon;
      } else {
        return prefixColon;
      }
    } else if (isImportSpecifier(parent2) && !parent2.propertyName) {
      const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
      return contains(originalSymbol.declarations, parent2) ? { prefixText: name + " as " } : emptyOptions;
    } else if (isExportSpecifier(parent2) && !parent2.propertyName) {
      return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { prefixText: name + " as " } : { suffixText: " as " + name };
    }
  }
  if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) {
    const quote2 = getQuoteFromPreference(quotePreference);
    return { prefixText: quote2, suffixText: quote2 };
  }
  return emptyOptions;
}
function toImplementationLocation(entry, checker) {
  const documentSpan = entryToDocumentSpan(entry);
  if (entry.kind !== 0 /* Span */) {
    const { node } = entry;
    return {
      ...documentSpan,
      ...implementationKindDisplayParts(node, checker)
    };
  } else {
    return { ...documentSpan, kind: "" /* unknown */, displayParts: [] };
  }
}
function implementationKindDisplayParts(node, checker) {
  const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node);
  if (symbol) {
    return getDefinitionKindAndDisplayParts(symbol, checker, node);
  } else if (node.kind === 209 /* ObjectLiteralExpression */) {
    return {
      kind: "interface" /* interfaceElement */,
      displayParts: [punctuationPart(21 /* OpenParenToken */), textPart("object literal"), punctuationPart(22 /* CloseParenToken */)]
    };
  } else if (node.kind === 230 /* ClassExpression */) {
    return {
      kind: "local class" /* localClassElement */,
      displayParts: [punctuationPart(21 /* OpenParenToken */), textPart("anonymous local class"), punctuationPart(22 /* CloseParenToken */)]
    };
  } else {
    return { kind: getNodeKind(node), displayParts: [] };
  }
}
function toHighlightSpan(entry) {
  const documentSpan = entryToDocumentSpan(entry);
  if (entry.kind === 0 /* Span */) {
    return {
      fileName: documentSpan.fileName,
      span: {
        textSpan: documentSpan.textSpan,
        kind: "reference" /* reference */
      }
    };
  }
  const writeAccess = isWriteAccessForReference(entry.node);
  const span = {
    textSpan: documentSpan.textSpan,
    kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */,
    isInString: entry.kind === 2 /* StringLiteral */ ? true : void 0,
    ...documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan }
  };
  return { fileName: documentSpan.fileName, span };
}
function getTextSpan(node, sourceFile, endNode2) {
  let start2 = node.getStart(sourceFile);
  let end = (endNode2 || node).getEnd();
  if (isStringLiteralLike(node) && end - start2 > 2) {
    Debug.assert(endNode2 === void 0);
    start2 += 1;
    end -= 1;
  }
  return createTextSpanFromBounds(start2, end);
}
function getTextSpanOfEntry(entry) {
  return entry.kind === 0 /* Span */ ? entry.textSpan : getTextSpan(entry.node, entry.node.getSourceFile());
}
function isWriteAccessForReference(node) {
  const decl = getDeclarationFromName(node);
  return !!decl && declarationIsWriteAccess(decl) || node.kind === 90 /* DefaultKeyword */ || isWriteAccess(node);
}
function isDeclarationOfSymbol(node, target) {
  var _a;
  if (!target)
    return false;
  const source = getDeclarationFromName(node) || (node.kind === 90 /* DefaultKeyword */ ? node.parent : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent : node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent) ? node.parent.parent : void 0);
  const commonjsSource = source && isBinaryExpression(source) ? source.left : void 0;
  return !!(source && ((_a = target.declarations) == null ? void 0 : _a.some((d) => d === source || d === commonjsSource)));
}
function declarationIsWriteAccess(decl) {
  if (!!(decl.flags & 16777216 /* Ambient */))
    return true;
  switch (decl.kind) {
    case 225 /* BinaryExpression */:
    case 207 /* BindingElement */:
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
    case 90 /* DefaultKeyword */:
    case 265 /* EnumDeclaration */:
    case 305 /* EnumMember */:
    case 280 /* ExportSpecifier */:
    case 272 /* ImportClause */:
    case 270 /* ImportEqualsDeclaration */:
    case 275 /* ImportSpecifier */:
    case 263 /* InterfaceDeclaration */:
    case 344 /* JSDocCallbackTag */:
    case 352 /* JSDocTypedefTag */:
    case 290 /* JsxAttribute */:
    case 266 /* ModuleDeclaration */:
    case 269 /* NamespaceExportDeclaration */:
    case 273 /* NamespaceImport */:
    case 279 /* NamespaceExport */:
    case 168 /* Parameter */:
    case 303 /* ShorthandPropertyAssignment */:
    case 264 /* TypeAliasDeclaration */:
    case 167 /* TypeParameter */:
      return true;
    case 302 /* PropertyAssignment */:
      return !isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 175 /* Constructor */:
    case 173 /* MethodDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
      return !!decl.body;
    case 259 /* VariableDeclaration */:
    case 171 /* PropertyDeclaration */:
      return !!decl.initializer || isCatchClause(decl.parent);
    case 172 /* MethodSignature */:
    case 170 /* PropertySignature */:
    case 354 /* JSDocPropertyTag */:
    case 347 /* JSDocParameterTag */:
      return false;
    default:
      return Debug.failBadSyntaxKind(decl);
  }
}
var Core;
((Core2) => {
  function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) {
    var _a, _b, _c;
    node = getAdjustedNode2(node, options);
    if (isSourceFile(node)) {
      const resolvedRef = ts_GoToDefinition_exports.getReferenceAtPosition(node, position, program);
      if (!(resolvedRef == null ? void 0 : resolvedRef.file)) {
        return void 0;
      }
      const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol);
      if (moduleSymbol) {
        return getReferencedSymbolsForModule(
          program,
          moduleSymbol,
          /*excludeImportTypeOfExportEquals*/
          false,
          sourceFiles,
          sourceFilesSet
        );
      }
      const fileIncludeReasons = program.getFileIncludeReasons();
      if (!fileIncludeReasons) {
        return void 0;
      }
      return [{
        definition: { type: 5 /* TripleSlashReference */, reference: resolvedRef.reference, file: node },
        references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray
      }];
    }
    if (!options.implementations) {
      const special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
      if (special) {
        return special;
      }
    }
    const checker = program.getTypeChecker();
    const symbol = checker.getSymbolAtLocation(isConstructorDeclaration(node) && node.parent.name || node);
    if (!symbol) {
      if (!options.implementations && isStringLiteralLike(node)) {
        if (isModuleSpecifierLike(node)) {
          const fileIncludeReasons = program.getFileIncludeReasons();
          const referencedFileName = (_c = (_b = (_a = node.getSourceFile().resolvedModules) == null ? void 0 : _a.get(node.text, getModeForUsageLocation(node.getSourceFile(), node))) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.resolvedFileName;
          const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : void 0;
          if (referencedFile) {
            return [{ definition: { type: 4 /* String */, node }, references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray }];
          }
        }
        return getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken);
      }
      return void 0;
    }
    if (symbol.escapedName === "export=" /* ExportEquals */) {
      return getReferencedSymbolsForModule(
        program,
        symbol.parent,
        /*excludeImportTypeOfExportEquals*/
        false,
        sourceFiles,
        sourceFilesSet
      );
    }
    const moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
    if (moduleReferences && !(symbol.flags & 33554432 /* Transient */)) {
      return moduleReferences;
    }
    const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker);
    const moduleReferencesOfExportTarget = aliasedSymbol && getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
    const references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
    return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
  }
  Core2.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
  function getAdjustedNode2(node, options) {
    if (options.use === 1 /* References */) {
      node = getAdjustedReferenceLocation(node);
    } else if (options.use === 2 /* Rename */) {
      node = getAdjustedRenameLocation(node);
    }
    return node;
  }
  Core2.getAdjustedNode = getAdjustedNode2;
  function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) {
    var _a, _b;
    const moduleSymbol = (_a = program.getSourceFile(fileName)) == null ? void 0 : _a.symbol;
    if (moduleSymbol) {
      return ((_b = getReferencedSymbolsForModule(
        program,
        moduleSymbol,
        /*excludeImportTypeOfExportEquals*/
        false,
        sourceFiles,
        sourceFilesSet
      )[0]) == null ? void 0 : _b.references) || emptyArray;
    }
    const fileIncludeReasons = program.getFileIncludeReasons();
    const referencedFile = program.getSourceFile(fileName);
    return referencedFile && fileIncludeReasons && getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray;
  }
  Core2.getReferencesForFileName = getReferencesForFileName;
  function getReferencesForNonModule(referencedFile, refFileMap, program) {
    let entries;
    const references = refFileMap.get(referencedFile.path) || emptyArray;
    for (const ref of references) {
      if (isReferencedFile(ref)) {
        const referencingFile = program.getSourceFileByPath(ref.file);
        const location = getReferencedFileLocation(program.getSourceFileByPath, ref);
        if (isReferenceFileLocation(location)) {
          entries = append(entries, {
            kind: 0 /* Span */,
            fileName: referencingFile.fileName,
            textSpan: createTextSpanFromRange(location)
          });
        }
      }
    }
    return entries;
  }
  function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) {
    if (node.parent && isNamespaceExportDeclaration(node.parent)) {
      const aliasedSymbol = checker.getAliasedSymbol(symbol);
      const targetSymbol = checker.getMergedSymbol(aliasedSymbol);
      if (aliasedSymbol !== targetSymbol) {
        return targetSymbol;
      }
    }
    return void 0;
  }
  function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
    const moduleSourceFile = symbol.flags & 1536 /* Module */ && symbol.declarations && find(symbol.declarations, isSourceFile);
    if (!moduleSourceFile)
      return void 0;
    const exportEquals = symbol.exports.get("export=" /* ExportEquals */);
    const moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
    if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
      return moduleReferences;
    const checker = program.getTypeChecker();
    symbol = skipAlias(exportEquals, checker);
    return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(
      symbol,
      /*node*/
      void 0,
      sourceFiles,
      sourceFilesSet,
      checker,
      cancellationToken,
      options
    ));
  }
  function mergeReferences(program, ...referencesToMerge) {
    let result;
    for (const references of referencesToMerge) {
      if (!references || !references.length)
        continue;
      if (!result) {
        result = references;
        continue;
      }
      for (const entry of references) {
        if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
          result.push(entry);
          continue;
        }
        const symbol = entry.definition.symbol;
        const refIndex = findIndex(result, (ref) => !!ref.definition && ref.definition.type === 0 /* Symbol */ && ref.definition.symbol === symbol);
        if (refIndex === -1) {
          result.push(entry);
          continue;
        }
        const reference = result[refIndex];
        result[refIndex] = {
          definition: reference.definition,
          references: reference.references.concat(entry.references).sort((entry1, entry2) => {
            const entry1File = getSourceFileIndexOfEntry(program, entry1);
            const entry2File = getSourceFileIndexOfEntry(program, entry2);
            if (entry1File !== entry2File) {
              return compareValues(entry1File, entry2File);
            }
            const entry1Span = getTextSpanOfEntry(entry1);
            const entry2Span = getTextSpanOfEntry(entry2);
            return entry1Span.start !== entry2Span.start ? compareValues(entry1Span.start, entry2Span.start) : compareValues(entry1Span.length, entry2Span.length);
          })
        };
      }
    }
    return result;
  }
  function getSourceFileIndexOfEntry(program, entry) {
    const sourceFile = entry.kind === 0 /* Span */ ? program.getSourceFile(entry.fileName) : entry.node.getSourceFile();
    return program.getSourceFiles().indexOf(sourceFile);
  }
  function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
    Debug.assert(!!symbol.valueDeclaration);
    const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), (reference) => {
      if (reference.kind === "import") {
        const parent2 = reference.literal.parent;
        if (isLiteralTypeNode(parent2)) {
          const importType = cast(parent2.parent, isImportTypeNode);
          if (excludeImportTypeOfExportEquals && !importType.qualifier) {
            return void 0;
          }
        }
        return nodeEntry(reference.literal);
      } else if (reference.kind === "implicit") {
        const range = reference.literal.text !== externalHelpersModuleNameText && forEachChildRecursively(
          reference.referencingFile,
          (n) => !(n.transformFlags & 2 /* ContainsJsx */) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : void 0
        ) || reference.referencingFile.statements[0] || reference.referencingFile;
        return nodeEntry(range);
      } else {
        return {
          kind: 0 /* Span */,
          fileName: reference.referencingFile.fileName,
          textSpan: createTextSpanFromRange(reference.ref)
        };
      }
    });
    if (symbol.declarations) {
      for (const decl of symbol.declarations) {
        switch (decl.kind) {
          case 311 /* SourceFile */:
            break;
          case 266 /* ModuleDeclaration */:
            if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
              references.push(nodeEntry(decl.name));
            }
            break;
          default:
            Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
        }
      }
    }
    const exported = symbol.exports.get("export=" /* ExportEquals */);
    if (exported == null ? void 0 : exported.declarations) {
      for (const decl of exported.declarations) {
        const sourceFile = decl.getSourceFile();
        if (sourceFilesSet.has(sourceFile.fileName)) {
          const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) ? decl.left.expression : isExportAssignment(decl) ? Debug.checkDefined(findChildOfKind(decl, 95 /* ExportKeyword */, sourceFile)) : getNameOfDeclaration(decl) || decl;
          references.push(nodeEntry(node));
        }
      }
    }
    return references.length ? [{ definition: { type: 0 /* Symbol */, symbol }, references }] : emptyArray;
  }
  function isReadonlyTypeOperator(node) {
    return node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(node.parent) && node.parent.operator === 148 /* ReadonlyKeyword */;
  }
  function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
    if (isTypeKeyword(node.kind)) {
      if (node.kind === 116 /* VoidKeyword */ && isVoidExpression(node.parent)) {
        return void 0;
      }
      if (node.kind === 148 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) {
        return void 0;
      }
      return getAllReferencesForKeyword(
        sourceFiles,
        node.kind,
        cancellationToken,
        node.kind === 148 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : void 0
      );
    }
    if (isImportMeta(node.parent) && node.parent.name === node) {
      return getAllReferencesForImportMeta(sourceFiles, cancellationToken);
    }
    if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) {
      return [{ definition: { type: 2 /* Keyword */, node }, references: [nodeEntry(node)] }];
    }
    if (isJumpStatementTarget(node)) {
      const labelDefinition = getTargetLabel(node.parent, node.text);
      return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
    } else if (isLabelOfLabeledStatement(node)) {
      return getLabelReferencesInNode(node.parent, node);
    }
    if (isThis(node)) {
      return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
    }
    if (node.kind === 108 /* SuperKeyword */) {
      return getReferencesForSuperKeyword(node);
    }
    return void 0;
  }
  function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
    const symbol = node && skipPastExportOrImportSpecifierOrUnion(
      originalSymbol,
      node,
      checker,
      /*useLocalSymbolForExportSpecifier*/
      !isForRenameWithPrefixAndSuffixText(options)
    ) || originalSymbol;
    const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
    const result = [];
    const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
    const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? void 0 : find(symbol.declarations, isExportSpecifier);
    if (exportSpecifier) {
      getReferencesAtExportSpecifier(
        exportSpecifier.name,
        symbol,
        exportSpecifier,
        state.createSearch(
          node,
          originalSymbol,
          /*comingFrom*/
          void 0
        ),
        state,
        /*addReferencesHere*/
        true,
        /*alwaysGetReferences*/
        true
      );
    } else if (node && node.kind === 90 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) {
      addReference(node, symbol, state);
      searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state);
    } else {
      const search = state.createSearch(
        node,
        symbol,
        /*comingFrom*/
        void 0,
        { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }
      );
      getReferencesInContainerOrFiles(symbol, state, search);
    }
    return result;
  }
  function getReferencesInContainerOrFiles(symbol, state, search) {
    const scope = getSymbolScope(symbol);
    if (scope) {
      getReferencesInContainer(
        scope,
        scope.getSourceFile(),
        search,
        state,
        /*addReferencesHere*/
        !(isSourceFile(scope) && !contains(state.sourceFiles, scope))
      );
    } else {
      for (const sourceFile of state.sourceFiles) {
        state.cancellationToken.throwIfCancellationRequested();
        searchForName(sourceFile, search, state);
      }
    }
  }
  function getSpecialSearchKind(node) {
    switch (node.kind) {
      case 175 /* Constructor */:
      case 137 /* ConstructorKeyword */:
        return 1 /* Constructor */;
      case 80 /* Identifier */:
        if (isClassLike(node.parent)) {
          Debug.assert(node.parent.name === node);
          return 2 /* Class */;
        }
      default:
        return 0 /* None */;
    }
  }
  function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) {
    const { parent: parent2 } = node;
    if (isExportSpecifier(parent2) && useLocalSymbolForExportSpecifier) {
      return getLocalSymbolForExportSpecifier(node, symbol, parent2, checker);
    }
    return firstDefined(symbol.declarations, (decl) => {
      if (!decl.parent) {
        if (symbol.flags & 33554432 /* Transient */)
          return void 0;
        Debug.fail(`Unexpected symbol at ${Debug.formatSyntaxKind(node.kind)}: ${Debug.formatSymbol(symbol)}`);
      }
      return isTypeLiteralNode(decl.parent) && isUnionTypeNode(decl.parent.parent) ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) : void 0;
    });
  }
  let SpecialSearchKind;
  ((SpecialSearchKind2) => {
    SpecialSearchKind2[SpecialSearchKind2["None"] = 0] = "None";
    SpecialSearchKind2[SpecialSearchKind2["Constructor"] = 1] = "Constructor";
    SpecialSearchKind2[SpecialSearchKind2["Class"] = 2] = "Class";
  })(SpecialSearchKind || (SpecialSearchKind = {}));
  function getNonModuleSymbolOfMergedModuleSymbol(symbol) {
    if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */)))
      return void 0;
    const decl = symbol.declarations && find(symbol.declarations, (d) => !isSourceFile(d) && !isModuleDeclaration(d));
    return decl && decl.symbol;
  }
  class State {
    constructor(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
      this.sourceFiles = sourceFiles;
      this.sourceFilesSet = sourceFilesSet;
      this.specialSearchKind = specialSearchKind;
      this.checker = checker;
      this.cancellationToken = cancellationToken;
      this.searchMeaning = searchMeaning;
      this.options = options;
      this.result = result;
      /** Cache for `explicitlyinheritsFrom`. */
      this.inheritsFromCache = /* @__PURE__ */ new Map();
      /**
       * Type nodes can contain multiple references to the same type. For example:
       *      let x: Foo & (Foo & Bar) = ...
       * Because we are returning the implementation locations and not the identifier locations,
       * duplicate entries would be returned here as each of the type references is part of
       * the same implementation. For that reason, check before we add a new entry.
       */
      this.markSeenContainingTypeReference = nodeSeenTracker();
      /**
       * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
       * For example:
       *     // b.ts
       *     export { foo as bar } from "./a";
       *     import { bar } from "./b";
       *
       * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
       * But another reference to it may appear in the same source file.
       * See `tests/cases/fourslash/transitiveExportImports3.ts`.
       */
      this.markSeenReExportRHS = nodeSeenTracker();
      this.symbolIdToReferences = [];
      // Source file ID -> symbol ID -> Whether the symbol has been searched for in the source file.
      this.sourceFileToSeenSymbols = [];
    }
    includesSourceFile(sourceFile) {
      return this.sourceFilesSet.has(sourceFile.fileName);
    }
    /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
    getImportSearches(exportSymbol, exportInfo) {
      if (!this.importTracker)
        this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
      return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */);
    }
    /** @param allSearchSymbols set of additional symbols for use by `includes`. */
    createSearch(location, symbol, comingFrom, searchOptions = {}) {
      const {
        text = stripQuotes(symbolName(getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol)),
        allSearchSymbols = [symbol]
      } = searchOptions;
      const escapedText = escapeLeadingUnderscores(text);
      const parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : void 0;
      return { symbol, comingFrom, text, escapedText, parents, allSearchSymbols, includes: (sym) => contains(allSearchSymbols, sym) };
    }
    /**
     * Callback to add references for a particular searched symbol.
     * This initializes a reference group, so only call this if you will add at least one reference.
     */
    referenceAdder(searchSymbol) {
      const symbolId = getSymbolId(searchSymbol);
      let references = this.symbolIdToReferences[symbolId];
      if (!references) {
        references = this.symbolIdToReferences[symbolId] = [];
        this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references });
      }
      return (node, kind) => references.push(nodeEntry(node, kind));
    }
    /** Add a reference with no associated definition. */
    addStringOrCommentReference(fileName, textSpan) {
      this.result.push({
        definition: void 0,
        references: [{ kind: 0 /* Span */, fileName, textSpan }]
      });
    }
    /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
    markSearchedSymbols(sourceFile, symbols) {
      const sourceId = getNodeId(sourceFile);
      const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = /* @__PURE__ */ new Set());
      let anyNewSymbols = false;
      for (const sym of symbols) {
        anyNewSymbols = tryAddToSet(seenSymbols, getSymbolId(sym)) || anyNewSymbols;
      }
      return anyNewSymbols;
    }
  }
  function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
    const { importSearches, singleReferences, indirectUsers } = state.getImportSearches(exportSymbol, exportInfo);
    if (singleReferences.length) {
      const addRef = state.referenceAdder(exportSymbol);
      for (const singleRef of singleReferences) {
        if (shouldAddSingleReference(singleRef, state))
          addRef(singleRef);
      }
    }
    for (const [importLocation, importSymbol] of importSearches) {
      getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
    }
    if (indirectUsers.length) {
      let indirectSearch;
      switch (exportInfo.exportKind) {
        case 0 /* Named */:
          indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
          break;
        case 1 /* Default */:
          indirectSearch = state.options.use === 2 /* Rename */ ? void 0 : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
          break;
        case 2 /* ExportEquals */:
          break;
      }
      if (indirectSearch) {
        for (const indirectUser of indirectUsers) {
          searchForName(indirectUser, indirectSearch, state);
        }
      }
    }
  }
  function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
    const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map((f) => f.fileName)), checker, cancellationToken);
    const { importSearches, indirectUsers, singleReferences } = importTracker(
      exportSymbol,
      { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol },
      /*isForRename*/
      false
    );
    for (const [importLocation] of importSearches) {
      cb(importLocation);
    }
    for (const singleReference of singleReferences) {
      if (isIdentifier(singleReference) && isImportTypeNode(singleReference.parent)) {
        cb(singleReference);
      }
    }
    for (const indirectUser of indirectUsers) {
      for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)) {
        const symbol = checker.getSymbolAtLocation(node);
        const hasExportAssignmentDeclaration = some(symbol == null ? void 0 : symbol.declarations, (d) => tryCast(d, isExportAssignment) ? true : false);
        if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) {
          cb(node);
        }
      }
    }
  }
  Core2.eachExportReference = eachExportReference;
  function shouldAddSingleReference(singleRef, state) {
    if (!hasMatchingMeaning(singleRef, state))
      return false;
    if (state.options.use !== 2 /* Rename */)
      return true;
    if (!isIdentifier(singleRef))
      return false;
    return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
  }
  function searchForImportedSymbol(symbol, state) {
    if (!symbol.declarations)
      return;
    for (const declaration of symbol.declarations) {
      const exportingFile = declaration.getSourceFile();
      getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile));
    }
  }
  function searchForName(sourceFile, search, state) {
    if (getNameTable(sourceFile).get(search.escapedText) !== void 0) {
      getReferencesInSourceFile(sourceFile, search, state);
    }
  }
  function getPropertySymbolOfDestructuringAssignment(location, checker) {
    return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) ? checker.getPropertySymbolOfDestructuringAssignment(location) : void 0;
  }
  function getSymbolScope(symbol) {
    const { declarations, flags, parent: parent2, valueDeclaration } = symbol;
    if (valueDeclaration && (valueDeclaration.kind === 217 /* FunctionExpression */ || valueDeclaration.kind === 230 /* ClassExpression */)) {
      return valueDeclaration;
    }
    if (!declarations) {
      return void 0;
    }
    if (flags & (4 /* Property */ | 8192 /* Method */)) {
      const privateDeclaration = find(declarations, (d) => hasEffectiveModifier(d, 8 /* Private */) || isPrivateIdentifierClassElementDeclaration(d));
      if (privateDeclaration) {
        return getAncestor(privateDeclaration, 262 /* ClassDeclaration */);
      }
      return void 0;
    }
    if (declarations.some(isObjectBindingElementWithoutPropertyName)) {
      return void 0;
    }
    const exposedByParent = parent2 && !(symbol.flags & 262144 /* TypeParameter */);
    if (exposedByParent && !(isExternalModuleSymbol(parent2) && !parent2.globalExports)) {
      return void 0;
    }
    let scope;
    for (const declaration of declarations) {
      const container = getContainerNode(declaration);
      if (scope && scope !== container) {
        return void 0;
      }
      if (!container || container.kind === 311 /* SourceFile */ && !isExternalOrCommonJsModule(container)) {
        return void 0;
      }
      scope = container;
      if (isFunctionExpression(scope)) {
        let next;
        while (next = getNextJSDocCommentLocation(scope)) {
          scope = next;
        }
      }
    }
    return exposedByParent ? scope.getSourceFile() : scope;
  }
  function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer = sourceFile) {
    return eachSymbolReferenceInFile(definition, checker, sourceFile, () => true, searchContainer) || false;
  }
  Core2.isSymbolReferencedInFile = isSymbolReferencedInFile;
  function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer = sourceFile) {
    const symbol = isParameterPropertyDeclaration(definition.parent, definition.parent.parent) ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) : checker.getSymbolAtLocation(definition);
    if (!symbol)
      return void 0;
    for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)) {
      if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText)
        continue;
      const referenceSymbol = checker.getSymbolAtLocation(token);
      if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
        const res = cb(token);
        if (res)
          return res;
      }
    }
  }
  Core2.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
  function getTopMostDeclarationNamesInFile(declarationName, sourceFile) {
    const candidates = filter(getPossibleSymbolReferenceNodes(sourceFile, declarationName), (name) => !!getDeclarationFromName(name));
    return candidates.reduce((topMost, decl) => {
      const depth = getDepth(decl);
      if (!some(topMost.declarationNames) || depth === topMost.depth) {
        topMost.declarationNames.push(decl);
        topMost.depth = depth;
      } else if (depth < topMost.depth) {
        topMost.declarationNames = [decl];
        topMost.depth = depth;
      }
      return topMost;
    }, { depth: Infinity, declarationNames: [] }).declarationNames;
    function getDepth(declaration) {
      let depth = 0;
      while (declaration) {
        declaration = getContainerNode(declaration);
        depth++;
      }
      return depth;
    }
  }
  Core2.getTopMostDeclarationNamesInFile = getTopMostDeclarationNamesInFile;
  function someSignatureUsage(signature, sourceFiles, checker, cb) {
    if (!signature.name || !isIdentifier(signature.name))
      return false;
    const symbol = Debug.checkDefined(checker.getSymbolAtLocation(signature.name));
    for (const sourceFile of sourceFiles) {
      for (const name of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)) {
        if (!isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
          continue;
        const called = climbPastPropertyAccess(name);
        const call = isCallExpression(called.parent) && called.parent.expression === called ? called.parent : void 0;
        const referenceSymbol = checker.getSymbolAtLocation(name);
        if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some((s) => s === symbol)) {
          if (cb(name, call)) {
            return true;
          }
        }
      }
    }
    return false;
  }
  Core2.someSignatureUsage = someSignatureUsage;
  function getPossibleSymbolReferenceNodes(sourceFile, symbolName2, container = sourceFile) {
    return getPossibleSymbolReferencePositions(sourceFile, symbolName2, container).map((pos) => getTouchingPropertyName(sourceFile, pos));
  }
  function getPossibleSymbolReferencePositions(sourceFile, symbolName2, container = sourceFile) {
    const positions = [];
    if (!symbolName2 || !symbolName2.length) {
      return positions;
    }
    const text = sourceFile.text;
    const sourceLength = text.length;
    const symbolNameLength = symbolName2.length;
    let position = text.indexOf(symbolName2, container.pos);
    while (position >= 0) {
      if (position > container.end)
        break;
      const endPosition = position + symbolNameLength;
      if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */)) && (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */))) {
        positions.push(position);
      }
      position = text.indexOf(symbolName2, position + symbolNameLength + 1);
    }
    return positions;
  }
  function getLabelReferencesInNode(container, targetLabel) {
    const sourceFile = container.getSourceFile();
    const labelName = targetLabel.text;
    const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), (node) => (
      // Only pick labels that are either the target label, or have a target that is the target label
      node === targetLabel || isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel ? nodeEntry(node) : void 0
    ));
    return [{ definition: { type: 1 /* Label */, node: targetLabel }, references }];
  }
  function isValidReferencePosition(node, searchSymbolName) {
    switch (node.kind) {
      case 81 /* PrivateIdentifier */:
        if (isJSDocMemberName(node.parent)) {
          return true;
        }
      case 80 /* Identifier */:
        return node.text.length === searchSymbolName.length;
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */: {
        const str = node;
        return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) && str.text.length === searchSymbolName.length;
      }
      case 9 /* NumericLiteral */:
        return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length;
      case 90 /* DefaultKeyword */:
        return "default".length === searchSymbolName.length;
      default:
        return false;
    }
  }
  function getAllReferencesForImportMeta(sourceFiles, cancellationToken) {
    const references = flatMap(sourceFiles, (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile), (node) => {
        const parent2 = node.parent;
        if (isImportMeta(parent2)) {
          return nodeEntry(parent2);
        }
      });
    });
    return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references }] : void 0;
  }
  function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter2) {
    const references = flatMap(sourceFiles, (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind), sourceFile), (referenceLocation) => {
        if (referenceLocation.kind === keywordKind && (!filter2 || filter2(referenceLocation))) {
          return nodeEntry(referenceLocation);
        }
      });
    });
    return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references }] : void 0;
  }
  function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere = true) {
    state.cancellationToken.throwIfCancellationRequested();
    return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere);
  }
  function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) {
    if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) {
      return;
    }
    for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container)) {
      getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
    }
  }
  function hasMatchingMeaning(referenceLocation, state) {
    return !!(getMeaningFromLocation(referenceLocation) & state.searchMeaning);
  }
  function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
    const referenceLocation = getTouchingPropertyName(sourceFile, position);
    if (!isValidReferencePosition(referenceLocation, search.text)) {
      if (!state.options.implementations && (state.options.findInStrings && isInString(sourceFile, position) || state.options.findInComments && isInNonReferenceComment(sourceFile, position))) {
        state.addStringOrCommentReference(sourceFile.fileName, createTextSpan(position, search.text.length));
      }
      return;
    }
    if (!hasMatchingMeaning(referenceLocation, state))
      return;
    let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
    if (!referenceSymbol) {
      return;
    }
    const parent2 = referenceLocation.parent;
    if (isImportSpecifier(parent2) && parent2.propertyName === referenceLocation) {
      return;
    }
    if (isExportSpecifier(parent2)) {
      Debug.assert(referenceLocation.kind === 80 /* Identifier */);
      getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent2, search, state, addReferencesHere);
      return;
    }
    const relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
    if (!relatedSymbol) {
      getReferenceForShorthandProperty(referenceSymbol, search, state);
      return;
    }
    switch (state.specialSearchKind) {
      case 0 /* None */:
        if (addReferencesHere)
          addReference(referenceLocation, relatedSymbol, state);
        break;
      case 1 /* Constructor */:
        addConstructorReferences(referenceLocation, sourceFile, search, state);
        break;
      case 2 /* Class */:
        addClassStaticThisReferences(referenceLocation, search, state);
        break;
      default:
        Debug.assertNever(state.specialSearchKind);
    }
    if (isInJSFile(referenceLocation) && isBindingElement(referenceLocation.parent) && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) {
      referenceSymbol = referenceLocation.parent.symbol;
      if (!referenceSymbol)
        return;
    }
    getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
  }
  function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
    Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled");
    const { parent: parent2, propertyName, name } = exportSpecifier;
    const exportDeclaration = parent2.parent;
    const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
    if (!alwaysGetReferences && !search.includes(localSymbol)) {
      return;
    }
    if (!propertyName) {
      if (!(state.options.use === 2 /* Rename */ && name.escapedText === "default" /* Default */)) {
        addRef();
      }
    } else if (referenceLocation === propertyName) {
      if (!exportDeclaration.moduleSpecifier) {
        addRef();
      }
      if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) {
        addReference(name, Debug.checkDefined(exportSpecifier.symbol), state);
      }
    } else {
      if (state.markSeenReExportRHS(referenceLocation)) {
        addRef();
      }
    }
    if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
      const isDefaultExport = referenceLocation.escapedText === "default" || exportSpecifier.name.escapedText === "default";
      const exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
      const exportSymbol = Debug.checkDefined(exportSpecifier.symbol);
      const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker);
      if (exportInfo) {
        searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
      }
    }
    if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) {
      const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
      if (imported)
        searchForImportedSymbol(imported, state);
    }
    function addRef() {
      if (addReferencesHere)
        addReference(referenceLocation, localSymbol, state);
    }
  }
  function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
    return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol;
  }
  function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
    const { parent: parent2, propertyName, name } = exportSpecifier;
    Debug.assert(propertyName === referenceLocation || name === referenceLocation);
    if (propertyName) {
      return propertyName === referenceLocation;
    } else {
      return !parent2.parent.moduleSpecifier;
    }
  }
  function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
    const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
    if (!importOrExport)
      return;
    const { symbol } = importOrExport;
    if (importOrExport.kind === 0 /* Import */) {
      if (!isForRenameWithPrefixAndSuffixText(state.options)) {
        searchForImportedSymbol(symbol, state);
      }
    } else {
      searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
    }
  }
  function getReferenceForShorthandProperty({ flags, valueDeclaration }, search, state) {
    const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
    const name = valueDeclaration && getNameOfDeclaration(valueDeclaration);
    if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
      addReference(name, shorthandValueSymbol, state);
    }
  }
  function addReference(referenceLocation, relatedSymbol, state) {
    const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: void 0, symbol: relatedSymbol };
    if (state.options.use === 2 /* Rename */ && referenceLocation.kind === 90 /* DefaultKeyword */) {
      return;
    }
    const addRef = state.referenceAdder(symbol);
    if (state.options.implementations) {
      addImplementationReferences(referenceLocation, addRef, state);
    } else {
      addRef(referenceLocation, kind);
    }
  }
  function addConstructorReferences(referenceLocation, sourceFile, search, state) {
    if (isNewExpressionTarget(referenceLocation)) {
      addReference(referenceLocation, search.symbol, state);
    }
    const pusher = () => state.referenceAdder(search.symbol);
    if (isClassLike(referenceLocation.parent)) {
      Debug.assert(referenceLocation.kind === 90 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
      findOwnConstructorReferences(search.symbol, sourceFile, pusher());
    } else {
      const classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
      if (classExtending) {
        findSuperConstructorAccesses(classExtending, pusher());
        findInheritedConstructorReferences(classExtending, state);
      }
    }
  }
  function addClassStaticThisReferences(referenceLocation, search, state) {
    addReference(referenceLocation, search.symbol, state);
    const classLike = referenceLocation.parent;
    if (state.options.use === 2 /* Rename */ || !isClassLike(classLike))
      return;
    Debug.assert(classLike.name === referenceLocation);
    const addRef = state.referenceAdder(search.symbol);
    for (const member of classLike.members) {
      if (!(isMethodOrAccessor(member) && isStatic(member))) {
        continue;
      }
      if (member.body) {
        member.body.forEachChild(function cb(node) {
          if (node.kind === 110 /* ThisKeyword */) {
            addRef(node);
          } else if (!isFunctionLike(node) && !isClassLike(node)) {
            node.forEachChild(cb);
          }
        });
      }
    }
  }
  function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
    const constructorSymbol = getClassConstructorSymbol(classSymbol);
    if (constructorSymbol && constructorSymbol.declarations) {
      for (const decl of constructorSymbol.declarations) {
        const ctrKeyword = findChildOfKind(decl, 137 /* ConstructorKeyword */, sourceFile);
        Debug.assert(decl.kind === 175 /* Constructor */ && !!ctrKeyword);
        addNode(ctrKeyword);
      }
    }
    if (classSymbol.exports) {
      classSymbol.exports.forEach((member) => {
        const decl = member.valueDeclaration;
        if (decl && decl.kind === 173 /* MethodDeclaration */) {
          const body = decl.body;
          if (body) {
            forEachDescendantOfKind(body, 110 /* ThisKeyword */, (thisKeyword) => {
              if (isNewExpressionTarget(thisKeyword)) {
                addNode(thisKeyword);
              }
            });
          }
        }
      });
    }
  }
  function getClassConstructorSymbol(classSymbol) {
    return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
  }
  function findSuperConstructorAccesses(classDeclaration, addNode) {
    const constructor = getClassConstructorSymbol(classDeclaration.symbol);
    if (!(constructor && constructor.declarations)) {
      return;
    }
    for (const decl of constructor.declarations) {
      Debug.assert(decl.kind === 175 /* Constructor */);
      const body = decl.body;
      if (body) {
        forEachDescendantOfKind(body, 108 /* SuperKeyword */, (node) => {
          if (isCallExpressionTarget(node)) {
            addNode(node);
          }
        });
      }
    }
  }
  function hasOwnConstructor(classDeclaration) {
    return !!getClassConstructorSymbol(classDeclaration.symbol);
  }
  function findInheritedConstructorReferences(classDeclaration, state) {
    if (hasOwnConstructor(classDeclaration))
      return;
    const classSymbol = classDeclaration.symbol;
    const search = state.createSearch(
      /*location*/
      void 0,
      classSymbol,
      /*comingFrom*/
      void 0
    );
    getReferencesInContainerOrFiles(classSymbol, state, search);
  }
  function addImplementationReferences(refNode, addReference2, state) {
    if (isDeclarationName(refNode) && isImplementation(refNode.parent)) {
      addReference2(refNode);
      return;
    }
    if (refNode.kind !== 80 /* Identifier */) {
      return;
    }
    if (refNode.parent.kind === 303 /* ShorthandPropertyAssignment */) {
      getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference2);
    }
    const containingClass = getContainingClassIfInHeritageClause(refNode);
    if (containingClass) {
      addReference2(containingClass);
      return;
    }
    const typeNode = findAncestor(refNode, (a) => !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent));
    const typeHavingNode = typeNode.parent;
    if (hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) {
      if (hasInitializer(typeHavingNode)) {
        addIfImplementation(typeHavingNode.initializer);
      } else if (isFunctionLike(typeHavingNode) && typeHavingNode.body) {
        const body = typeHavingNode.body;
        if (body.kind === 240 /* Block */) {
          forEachReturnStatement(body, (returnStatement) => {
            if (returnStatement.expression)
              addIfImplementation(returnStatement.expression);
          });
        } else {
          addIfImplementation(body);
        }
      } else if (isAssertionExpression(typeHavingNode)) {
        addIfImplementation(typeHavingNode.expression);
      }
    }
    function addIfImplementation(e) {
      if (isImplementationExpression(e))
        addReference2(e);
    }
  }
  function getContainingClassIfInHeritageClause(node) {
    return isIdentifier(node) || isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) : isExpressionWithTypeArguments(node) ? tryCast(node.parent.parent, isClassLike) : void 0;
  }
  function isImplementationExpression(node) {
    switch (node.kind) {
      case 216 /* ParenthesizedExpression */:
        return isImplementationExpression(node.expression);
      case 218 /* ArrowFunction */:
      case 217 /* FunctionExpression */:
      case 209 /* ObjectLiteralExpression */:
      case 230 /* ClassExpression */:
      case 208 /* ArrayLiteralExpression */:
        return true;
      default:
        return false;
    }
  }
  function explicitlyInheritsFrom(symbol, parent2, cachedResults, checker) {
    if (symbol === parent2) {
      return true;
    }
    const key = getSymbolId(symbol) + "," + getSymbolId(parent2);
    const cached = cachedResults.get(key);
    if (cached !== void 0) {
      return cached;
    }
    cachedResults.set(key, false);
    const inherits = !!symbol.declarations && symbol.declarations.some((declaration) => getAllSuperTypeNodes(declaration).some((typeReference) => {
      const type = checker.getTypeAtLocation(typeReference);
      return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker);
    }));
    cachedResults.set(key, inherits);
    return inherits;
  }
  function getReferencesForSuperKeyword(superKeyword) {
    let searchSpaceNode = getSuperContainer(
      superKeyword,
      /*stopOnFunctions*/
      false
    );
    if (!searchSpaceNode) {
      return void 0;
    }
    let staticFlag = 32 /* Static */;
    switch (searchSpaceNode.kind) {
      case 171 /* PropertyDeclaration */:
      case 170 /* PropertySignature */:
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
      case 175 /* Constructor */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        staticFlag &= getSyntacticModifierFlags(searchSpaceNode);
        searchSpaceNode = searchSpaceNode.parent;
        break;
      default:
        return void 0;
    }
    const sourceFile = searchSpaceNode.getSourceFile();
    const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), (node) => {
      if (node.kind !== 108 /* SuperKeyword */) {
        return;
      }
      const container = getSuperContainer(
        node,
        /*stopOnFunctions*/
        false
      );
      return container && isStatic(container) === !!staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : void 0;
    });
    return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references }];
  }
  function isParameterName(node) {
    return node.kind === 80 /* Identifier */ && node.parent.kind === 168 /* Parameter */ && node.parent.name === node;
  }
  function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
    let searchSpaceNode = getThisContainer(
      thisOrSuperKeyword,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    let staticFlag = 32 /* Static */;
    switch (searchSpaceNode.kind) {
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
        if (isObjectLiteralMethod(searchSpaceNode)) {
          staticFlag &= getSyntacticModifierFlags(searchSpaceNode);
          searchSpaceNode = searchSpaceNode.parent;
          break;
        }
      case 171 /* PropertyDeclaration */:
      case 170 /* PropertySignature */:
      case 175 /* Constructor */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        staticFlag &= getSyntacticModifierFlags(searchSpaceNode);
        searchSpaceNode = searchSpaceNode.parent;
        break;
      case 311 /* SourceFile */:
        if (isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
          return void 0;
        }
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
        break;
      default:
        return void 0;
    }
    const references = flatMap(searchSpaceNode.kind === 311 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return getPossibleSymbolReferenceNodes(sourceFile, "this", isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter((node) => {
        if (!isThis(node)) {
          return false;
        }
        const container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        if (!canHaveSymbol(container))
          return false;
        switch (searchSpaceNode.kind) {
          case 217 /* FunctionExpression */:
          case 261 /* FunctionDeclaration */:
            return searchSpaceNode.symbol === container.symbol;
          case 173 /* MethodDeclaration */:
          case 172 /* MethodSignature */:
            return isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
          case 230 /* ClassExpression */:
          case 262 /* ClassDeclaration */:
          case 209 /* ObjectLiteralExpression */:
            return container.parent && canHaveSymbol(container.parent) && searchSpaceNode.symbol === container.parent.symbol && isStatic(container) === !!staticFlag;
          case 311 /* SourceFile */:
            return container.kind === 311 /* SourceFile */ && !isExternalModule(container) && !isParameterName(node);
        }
      });
    }).map((n) => nodeEntry(n));
    const thisParameter = firstDefined(references, (r) => isParameter(r.node.parent) ? r.node : void 0);
    return [{
      definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
      references
    }];
  }
  function getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken) {
    const type = getContextualTypeFromParentOrAncestorTypeNode(node, checker);
    const references = flatMap(sourceFiles, (sourceFile) => {
      cancellationToken.throwIfCancellationRequested();
      return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), (ref) => {
        if (isStringLiteralLike(ref) && ref.text === node.text) {
          if (type) {
            const refType = getContextualTypeFromParentOrAncestorTypeNode(ref, checker);
            if (type !== checker.getStringType() && type === refType) {
              return nodeEntry(ref, 2 /* StringLiteral */);
            }
          } else {
            return isNoSubstitutionTemplateLiteral(ref) && !rangeIsOnSingleLine(ref, sourceFile) ? void 0 : nodeEntry(ref, 2 /* StringLiteral */);
          }
        }
      });
    });
    return [{
      definition: { type: 4 /* String */, node },
      references
    }];
  }
  function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) {
    const result = [];
    forEachRelatedSymbol(
      symbol,
      location,
      checker,
      isForRename,
      !(isForRename && providePrefixAndSuffixText),
      (sym, root, base) => {
        if (base) {
          if (isStaticSymbol(symbol) !== isStaticSymbol(base)) {
            base = void 0;
          }
        }
        result.push(base || root || sym);
      },
      // when try to find implementation, implementations is true, and not allowed to find base class
      /*allowBaseTypes*/
      () => !implementations
    );
    return result;
  }
  function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) {
    const containingObjectLiteralElement = getContainingObjectLiteralElement(location);
    if (containingObjectLiteralElement) {
      const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent);
      if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) {
        return cbSymbol(
          shorthandValueSymbol,
          /*rootSymbol*/
          void 0,
          /*baseSymbol*/
          void 0,
          3 /* SearchedLocalFoundProperty */
        );
      }
      const contextualType = checker.getContextualType(containingObjectLiteralElement.parent);
      const res2 = contextualType && firstDefined(
        getPropertySymbolsFromContextualType(
          containingObjectLiteralElement,
          checker,
          contextualType,
          /*unionSymbolOk*/
          true
        ),
        (sym) => fromRoot(sym, 4 /* SearchedPropertyFoundLocal */)
      );
      if (res2)
        return res2;
      const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
      const res1 = propertySymbol && cbSymbol(
        propertySymbol,
        /*rootSymbol*/
        void 0,
        /*baseSymbol*/
        void 0,
        4 /* SearchedPropertyFoundLocal */
      );
      if (res1)
        return res1;
      const res22 = shorthandValueSymbol && cbSymbol(
        shorthandValueSymbol,
        /*rootSymbol*/
        void 0,
        /*baseSymbol*/
        void 0,
        3 /* SearchedLocalFoundProperty */
      );
      if (res22)
        return res22;
    }
    const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker);
    if (aliasedSymbol) {
      const res2 = cbSymbol(
        aliasedSymbol,
        /*rootSymbol*/
        void 0,
        /*baseSymbol*/
        void 0,
        1 /* Node */
      );
      if (res2)
        return res2;
    }
    const res = fromRoot(symbol);
    if (res)
      return res;
    if (symbol.valueDeclaration && isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) {
      const paramProps = checker.getSymbolsOfParameterPropertyDeclaration(cast(symbol.valueDeclaration, isParameter), symbol.name);
      Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */));
      return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]);
    }
    const exportSpecifier = getDeclarationOfKind(symbol, 280 /* ExportSpecifier */);
    if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) {
      const localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
      if (localSymbol) {
        const res2 = cbSymbol(
          localSymbol,
          /*rootSymbol*/
          void 0,
          /*baseSymbol*/
          void 0,
          1 /* Node */
        );
        if (res2)
          return res2;
      }
    }
    if (!isForRenamePopulateSearchSymbolSet) {
      let bindingElementPropertySymbol;
      if (onlyIncludeBindingElementAtReferenceLocation) {
        bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : void 0;
      } else {
        bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
      }
      return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
    }
    Debug.assert(isForRenamePopulateSearchSymbolSet);
    const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation;
    if (includeOriginalSymbolOfBindingElement) {
      const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
      return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
    }
    function fromRoot(sym, kind) {
      return firstDefined(checker.getRootSymbols(sym), (rootSymbol) => cbSymbol(
        sym,
        rootSymbol,
        /*baseSymbol*/
        void 0,
        kind
      ) || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, (base) => cbSymbol(sym, rootSymbol, base, kind)) : void 0));
    }
    function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol2, checker2) {
      const bindingElement = getDeclarationOfKind(symbol2, 207 /* BindingElement */);
      if (bindingElement && isObjectBindingElementWithoutPropertyName(bindingElement)) {
        return getPropertySymbolFromBindingElement(checker2, bindingElement);
      }
    }
  }
  function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
    const seen = /* @__PURE__ */ new Map();
    return recur(symbol);
    function recur(symbol2) {
      if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, getSymbolId(symbol2)))
        return;
      return firstDefined(symbol2.declarations, (declaration) => firstDefined(getAllSuperTypeNodes(declaration), (typeReference) => {
        const type = checker.getTypeAtLocation(typeReference);
        const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
        return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
      }));
    }
  }
  function isStaticSymbol(symbol) {
    if (!symbol.valueDeclaration)
      return false;
    const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration);
    return !!(modifierFlags & 32 /* Static */);
  }
  function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
    const { checker } = state;
    return forEachRelatedSymbol(
      referenceSymbol,
      referenceLocation,
      checker,
      /*isForRenamePopulateSearchSymbolSet*/
      false,
      /*onlyIncludeBindingElementAtReferenceLocation*/
      state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename,
      (sym, rootSymbol, baseSymbol, kind) => {
        if (baseSymbol) {
          if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) {
            baseSymbol = void 0;
          }
        }
        return search.includes(baseSymbol || rootSymbol || sym) ? { symbol: rootSymbol && !(getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind } : void 0;
      },
      /*allowBaseTypes*/
      (rootSymbol) => !(search.parents && !search.parents.some((parent2) => explicitlyInheritsFrom(rootSymbol.parent, parent2, state.inheritsFromCache, checker)))
    );
  }
  function getIntersectingMeaningFromDeclarations(node, symbol) {
    let meaning = getMeaningFromLocation(node);
    const { declarations } = symbol;
    if (declarations) {
      let lastIterationMeaning;
      do {
        lastIterationMeaning = meaning;
        for (const declaration of declarations) {
          const declarationMeaning = getMeaningFromDeclaration(declaration);
          if (declarationMeaning & meaning) {
            meaning |= declarationMeaning;
          }
        }
      } while (meaning !== lastIterationMeaning);
    }
    return meaning;
  }
  Core2.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
  function isImplementation(node) {
    return !!(node.flags & 16777216 /* Ambient */) ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) : isVariableLike(node) ? hasInitializer(node) : isFunctionLikeDeclaration(node) ? !!node.body : isClassLike(node) || isModuleOrEnumDeclaration(node);
  }
  function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference2) {
    const refSymbol = checker.getSymbolAtLocation(node);
    const shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
    if (shorthandSymbol) {
      for (const declaration of shorthandSymbol.getDeclarations()) {
        if (getMeaningFromDeclaration(declaration) & 1 /* Value */) {
          addReference2(declaration);
        }
      }
    }
  }
  Core2.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
  function forEachDescendantOfKind(node, kind, action) {
    forEachChild(node, (child) => {
      if (child.kind === kind) {
        action(child);
      }
      forEachDescendantOfKind(child, kind, action);
    });
  }
  function tryGetClassByExtendingIdentifier(node) {
    return tryGetClassExtendingExpressionWithTypeArguments(climbPastPropertyAccess(node).parent);
  }
  function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
    const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent : void 0;
    const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
    const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? void 0 : [lhsType]), (t) => t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : void 0);
    return res.length === 0 ? void 0 : res;
  }
  function isForRenameWithPrefixAndSuffixText(options) {
    return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename;
  }
})(Core || (Core = {}));

// src/services/_namespaces/ts.GoToDefinition.ts
var ts_GoToDefinition_exports = {};
__export(ts_GoToDefinition_exports, {
  createDefinitionInfo: () => createDefinitionInfo,
  findReferenceInPosition: () => findReferenceInPosition,
  getDefinitionAndBoundSpan: () => getDefinitionAndBoundSpan,
  getDefinitionAtPosition: () => getDefinitionAtPosition,
  getReferenceAtPosition: () => getReferenceAtPosition,
  getTypeDefinitionAtPosition: () => getTypeDefinitionAtPosition
});

// src/services/goToDefinition.ts
function getDefinitionAtPosition(program, sourceFile, position, searchOtherFilesOnly, stopAtAlias) {
  var _a, _b;
  const resolvedRef = getReferenceAtPosition(sourceFile, position, program);
  const fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || emptyArray;
  if (resolvedRef == null ? void 0 : resolvedRef.file) {
    return fileReferenceDefinition;
  }
  const node = getTouchingPropertyName(sourceFile, position);
  if (node === sourceFile) {
    return void 0;
  }
  const { parent: parent2 } = node;
  const typeChecker = program.getTypeChecker();
  if (node.kind === 163 /* OverrideKeyword */ || isIdentifier(node) && isJSDocOverrideTag(parent2) && parent2.tagName === node) {
    return getDefinitionFromOverriddenMember(typeChecker, node) || emptyArray;
  }
  if (isJumpStatementTarget(node)) {
    const label = getTargetLabel(node.parent, node.text);
    return label ? [createDefinitionInfoFromName(
      typeChecker,
      label,
      "label" /* label */,
      node.text,
      /*containerName*/
      void 0
    )] : void 0;
  }
  if (node.kind === 107 /* ReturnKeyword */) {
    const functionDeclaration = findAncestor(node.parent, (n) => isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n));
    return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0;
  }
  if (node.kind === 135 /* AwaitKeyword */) {
    const functionDeclaration = findAncestor(node, (n) => isFunctionLikeDeclaration(n));
    const isAsyncFunction2 = functionDeclaration && some(functionDeclaration.modifiers, (node2) => node2.kind === 134 /* AsyncKeyword */);
    return isAsyncFunction2 ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0;
  }
  if (node.kind === 127 /* YieldKeyword */) {
    const functionDeclaration = findAncestor(node, (n) => isFunctionLikeDeclaration(n));
    const isGeneratorFunction = functionDeclaration && functionDeclaration.asteriskToken;
    return isGeneratorFunction ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0;
  }
  if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) {
    const classDecl = node.parent.parent;
    const { symbol: symbol2, failedAliasResolution: failedAliasResolution2 } = getSymbol(classDecl, typeChecker, stopAtAlias);
    const staticBlocks = filter(classDecl.members, isClassStaticBlockDeclaration);
    const containerName = symbol2 ? typeChecker.symbolToString(symbol2, classDecl) : "";
    const sourceFile2 = node.getSourceFile();
    return map(staticBlocks, (staticBlock) => {
      let { pos } = moveRangePastModifiers(staticBlock);
      pos = skipTrivia(sourceFile2.text, pos);
      return createDefinitionInfoFromName(
        typeChecker,
        staticBlock,
        "constructor" /* constructorImplementationElement */,
        "static {}",
        containerName,
        /*unverified*/
        false,
        failedAliasResolution2,
        { start: pos, length: "static".length }
      );
    });
  }
  let { symbol, failedAliasResolution } = getSymbol(node, typeChecker, stopAtAlias);
  let fallbackNode = node;
  if (searchOtherFilesOnly && failedAliasResolution) {
    const importDeclaration = forEach([node, ...(symbol == null ? void 0 : symbol.declarations) || emptyArray], (n) => findAncestor(n, isAnyImportOrBareOrAccessedRequire));
    const moduleSpecifier = importDeclaration && tryGetModuleSpecifierFromDeclaration(importDeclaration);
    if (moduleSpecifier) {
      ({ symbol, failedAliasResolution } = getSymbol(moduleSpecifier, typeChecker, stopAtAlias));
      fallbackNode = moduleSpecifier;
    }
  }
  if (!symbol && isModuleSpecifierLike(fallbackNode)) {
    const ref = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(fallbackNode.text, getModeForUsageLocation(sourceFile, fallbackNode))) == null ? void 0 : _b.resolvedModule;
    if (ref) {
      return [{
        name: fallbackNode.text,
        fileName: ref.resolvedFileName,
        containerName: void 0,
        containerKind: void 0,
        kind: "script" /* scriptElement */,
        textSpan: createTextSpan(0, 0),
        failedAliasResolution,
        isAmbient: isDeclarationFileName(ref.resolvedFileName),
        unverified: fallbackNode !== node
      }];
    }
  }
  if (!symbol) {
    return concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker));
  }
  if (searchOtherFilesOnly && every(symbol.declarations, (d) => d.getSourceFile().fileName === sourceFile.fileName))
    return void 0;
  const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
  if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) {
    const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution);
    if (typeChecker.getRootSymbols(symbol).some((s) => symbolMatchesSignature(s, calledDeclaration))) {
      return [sigInfo];
    } else {
      const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, calledDeclaration) || emptyArray;
      return node.kind === 108 /* SuperKeyword */ ? [sigInfo, ...defs] : [...defs, sigInfo];
    }
  }
  if (node.parent.kind === 303 /* ShorthandPropertyAssignment */) {
    const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
    const definitions = (shorthandSymbol == null ? void 0 : shorthandSymbol.declarations) ? shorthandSymbol.declarations.map((decl) => createDefinitionInfo(
      decl,
      typeChecker,
      shorthandSymbol,
      node,
      /*unverified*/
      false,
      failedAliasResolution
    )) : emptyArray;
    return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node));
  }
  if (isPropertyName(node) && isBindingElement(parent2) && isObjectBindingPattern(parent2.parent) && node === (parent2.propertyName || parent2.name)) {
    const name = getNameFromPropertyName(node);
    const type = typeChecker.getTypeAtLocation(parent2.parent);
    return name === void 0 ? emptyArray : flatMap(type.isUnion() ? type.types : [type], (t) => {
      const prop = t.getProperty(name);
      return prop && getDefinitionFromSymbol(typeChecker, prop, node);
    });
  }
  const objectLiteralElementDefinition = getDefinitionFromObjectLiteralElement(typeChecker, node);
  return concatenate(fileReferenceDefinition, objectLiteralElementDefinition.length ? objectLiteralElementDefinition : getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution));
}
function symbolMatchesSignature(s, calledDeclaration) {
  var _a;
  return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || isAssignmentExpression(calledDeclaration.parent) || !isCallLikeExpression(calledDeclaration.parent) && s === ((_a = tryCast(calledDeclaration.parent, canHaveSymbol)) == null ? void 0 : _a.symbol);
}
function getDefinitionFromObjectLiteralElement(typeChecker, node) {
  const element = getContainingObjectLiteralElement(node);
  if (element) {
    const contextualType = element && typeChecker.getContextualType(element.parent);
    if (contextualType) {
      return flatMap(getPropertySymbolsFromContextualType(
        element,
        typeChecker,
        contextualType,
        /*unionSymbolOk*/
        false
      ), (propertySymbol) => getDefinitionFromSymbol(typeChecker, propertySymbol, node));
    }
  }
  return emptyArray;
}
function getDefinitionFromOverriddenMember(typeChecker, node) {
  const classElement = findAncestor(node, isClassElement);
  if (!(classElement && classElement.name))
    return;
  const baseDeclaration = findAncestor(classElement, isClassLike);
  if (!baseDeclaration)
    return;
  const baseTypeNode = getEffectiveBaseTypeNode(baseDeclaration);
  if (!baseTypeNode)
    return;
  const expression = skipParentheses(baseTypeNode.expression);
  const base = isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression);
  if (!base)
    return;
  const name = unescapeLeadingUnderscores(getTextOfPropertyName(classElement.name));
  const symbol = hasStaticModifier(classElement) ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name);
  if (!symbol)
    return;
  return getDefinitionFromSymbol(typeChecker, symbol, node);
}
function getReferenceAtPosition(sourceFile, position, program) {
  var _a, _b, _c, _d;
  const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
  if (referencePath) {
    const file = program.getSourceFileFromReference(sourceFile, referencePath);
    return file && { reference: referencePath, fileName: file.fileName, file, unverified: false };
  }
  const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
  if (typeReferenceDirective) {
    const reference = (_a = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName, typeReferenceDirective.resolutionMode || sourceFile.impliedNodeFormat)) == null ? void 0 : _a.resolvedTypeReferenceDirective;
    const file = reference && program.getSourceFile(reference.resolvedFileName);
    return file && { reference: typeReferenceDirective, fileName: file.fileName, file, unverified: false };
  }
  const libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
  if (libReferenceDirective) {
    const file = program.getLibFileFromReference(libReferenceDirective);
    return file && { reference: libReferenceDirective, fileName: file.fileName, file, unverified: false };
  }
  if ((_b = sourceFile.resolvedModules) == null ? void 0 : _b.size()) {
    const node = getTouchingToken(sourceFile, position);
    if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text, getModeForUsageLocation(sourceFile, node))) {
      const verifiedFileName = (_d = (_c = sourceFile.resolvedModules.get(node.text, getModeForUsageLocation(sourceFile, node))) == null ? void 0 : _c.resolvedModule) == null ? void 0 : _d.resolvedFileName;
      const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text);
      return {
        file: program.getSourceFile(fileName),
        fileName,
        reference: {
          pos: node.getStart(),
          end: node.getEnd(),
          fileName: node.text
        },
        unverified: !verifiedFileName
      };
    }
  }
  return void 0;
}
function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
  const node = getTouchingPropertyName(sourceFile, position);
  if (node === sourceFile) {
    return void 0;
  }
  if (isImportMeta(node.parent) && node.parent.name === node) {
    return definitionFromType(
      typeChecker.getTypeAtLocation(node.parent),
      typeChecker,
      node.parent,
      /*failedAliasResolution*/
      false
    );
  }
  const { symbol, failedAliasResolution } = getSymbol(
    node,
    typeChecker,
    /*stopAtAlias*/
    false
  );
  if (!symbol)
    return void 0;
  const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
  const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
  const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node, failedAliasResolution);
  const typeDefinitions = fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node, failedAliasResolution);
  return typeDefinitions.length ? typeDefinitions : !(symbol.flags & 111551 /* Value */) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node, failedAliasResolution) : void 0;
}
function definitionFromType(type, checker, node, failedAliasResolution) {
  return flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], (t) => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution));
}
function tryGetReturnTypeOfFunction(symbol, type, checker) {
  if (type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}`
  symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) {
    const sigs = type.getCallSignatures();
    if (sigs.length === 1)
      return checker.getReturnTypeOfSignature(first(sigs));
  }
  return void 0;
}
function getDefinitionAndBoundSpan(program, sourceFile, position) {
  const definitions = getDefinitionAtPosition(program, sourceFile, position);
  if (!definitions || definitions.length === 0) {
    return void 0;
  }
  const comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || findReferenceInPosition(sourceFile.libReferenceDirectives, position);
  if (comment) {
    return { definitions, textSpan: createTextSpanFromRange(comment) };
  }
  const node = getTouchingPropertyName(sourceFile, position);
  const textSpan = createTextSpan(node.getStart(), node.getWidth());
  return { definitions, textSpan };
}
function getDefinitionInfoForIndexSignatures(node, checker) {
  return mapDefined(checker.getIndexInfosAtLocation(node), (info) => info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration));
}
function getSymbol(node, checker, stopAtAlias) {
  const symbol = checker.getSymbolAtLocation(node);
  let failedAliasResolution = false;
  if ((symbol == null ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && !stopAtAlias && shouldSkipAlias(node, symbol.declarations[0])) {
    const aliased = checker.getAliasedSymbol(symbol);
    if (aliased.declarations) {
      return { symbol: aliased };
    } else {
      failedAliasResolution = true;
    }
  }
  return { symbol, failedAliasResolution };
}
function shouldSkipAlias(node, declaration) {
  if (node.kind !== 80 /* Identifier */) {
    return false;
  }
  if (node.parent === declaration) {
    return true;
  }
  if (declaration.kind === 273 /* NamespaceImport */) {
    return false;
  }
  return true;
}
function isExpandoDeclaration(node) {
  if (!isAssignmentDeclaration(node))
    return false;
  const containingAssignment = findAncestor(node, (p) => {
    if (isAssignmentExpression(p))
      return true;
    if (!isAssignmentDeclaration(p))
      return "quit";
    return false;
  });
  return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */;
}
function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, excludeDeclaration) {
  const filteredDeclarations = filter(symbol.declarations, (d) => d !== excludeDeclaration);
  const withoutExpandos = filter(filteredDeclarations, (d) => !isExpandoDeclaration(d));
  const results = some(withoutExpandos) ? withoutExpandos : filteredDeclarations;
  return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(results, (declaration) => createDefinitionInfo(
    declaration,
    typeChecker,
    symbol,
    node,
    /*unverified*/
    false,
    failedAliasResolution
  ));
  function getConstructSignatureDefinition() {
    if (symbol.flags & 32 /* Class */ && !(symbol.flags & (16 /* Function */ | 3 /* Variable */)) && (isNewExpressionTarget(node) || node.kind === 137 /* ConstructorKeyword */)) {
      const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration");
      return getSignatureDefinition(
        cls.members,
        /*selectConstructors*/
        true
      );
    }
  }
  function getCallSignatureDefinition() {
    return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition(
      filteredDeclarations,
      /*selectConstructors*/
      false
    ) : void 0;
  }
  function getSignatureDefinition(signatureDeclarations, selectConstructors) {
    if (!signatureDeclarations) {
      return void 0;
    }
    const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isFunctionLike);
    const declarationsWithBody = declarations.filter((d) => !!d.body);
    return declarations.length ? declarationsWithBody.length !== 0 ? declarationsWithBody.map((x) => createDefinitionInfo(x, typeChecker, symbol, node)) : [createDefinitionInfo(
      last(declarations),
      typeChecker,
      symbol,
      node,
      /*unverified*/
      false,
      failedAliasResolution
    )] : void 0;
  }
}
function createDefinitionInfo(declaration, checker, symbol, node, unverified, failedAliasResolution) {
  const symbolName2 = checker.symbolToString(symbol);
  const symbolKind = ts_SymbolDisplay_exports.getSymbolKind(checker, symbol, node);
  const containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : "";
  return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution);
}
function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName2, containerName, unverified, failedAliasResolution, textSpan) {
  const sourceFile = declaration.getSourceFile();
  if (!textSpan) {
    const name = getNameOfDeclaration(declaration) || declaration;
    textSpan = createTextSpanFromNode(name, sourceFile);
  }
  return {
    fileName: sourceFile.fileName,
    textSpan,
    kind: symbolKind,
    name: symbolName2,
    containerKind: void 0,
    // TODO: GH#18217
    containerName,
    ...ts_FindAllReferences_exports.toContextSpan(
      textSpan,
      sourceFile,
      ts_FindAllReferences_exports.getContextNode(declaration)
    ),
    isLocal: !isDefinitionVisible(checker, declaration),
    isAmbient: !!(declaration.flags & 16777216 /* Ambient */),
    unverified,
    failedAliasResolution
  };
}
function isDefinitionVisible(checker, declaration) {
  if (checker.isDeclarationVisible(declaration))
    return true;
  if (!declaration.parent)
    return false;
  if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration)
    return isDefinitionVisible(checker, declaration.parent);
  switch (declaration.kind) {
    case 171 /* PropertyDeclaration */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 173 /* MethodDeclaration */:
      if (hasEffectiveModifier(declaration, 8 /* Private */))
        return false;
    case 175 /* Constructor */:
    case 302 /* PropertyAssignment */:
    case 303 /* ShorthandPropertyAssignment */:
    case 209 /* ObjectLiteralExpression */:
    case 230 /* ClassExpression */:
    case 218 /* ArrowFunction */:
    case 217 /* FunctionExpression */:
      return isDefinitionVisible(checker, declaration.parent);
    default:
      return false;
  }
}
function createDefinitionFromSignatureDeclaration(typeChecker, decl, failedAliasResolution) {
  return createDefinitionInfo(
    decl,
    typeChecker,
    decl.symbol,
    decl,
    /*unverified*/
    false,
    failedAliasResolution
  );
}
function findReferenceInPosition(refs, pos) {
  return find(refs, (ref) => textRangeContainsPositionInclusive(ref, pos));
}
function getDefinitionInfoForFileReference(name, targetFileName, unverified) {
  return {
    fileName: targetFileName,
    textSpan: createTextSpanFromBounds(0, 0),
    kind: "script" /* scriptElement */,
    name,
    containerName: void 0,
    containerKind: void 0,
    // TODO: GH#18217
    unverified
  };
}
function getAncestorCallLikeExpression(node) {
  const target = findAncestor(node, (n) => !isRightSideOfPropertyAccess(n));
  const callLike = target == null ? void 0 : target.parent;
  return callLike && isCallLikeExpression(callLike) && getInvokedExpression(callLike) === target ? callLike : void 0;
}
function tryGetSignatureDeclaration(typeChecker, node) {
  const callLike = getAncestorCallLikeExpression(node);
  const signature = callLike && typeChecker.getResolvedSignature(callLike);
  return tryCast(signature && signature.declaration, (d) => isFunctionLike(d) && !isFunctionTypeNode(d));
}
function isConstructorLike(node) {
  switch (node.kind) {
    case 175 /* Constructor */:
    case 184 /* ConstructorType */:
    case 179 /* ConstructSignature */:
      return true;
    default:
      return false;
  }
}

// src/services/_namespaces/ts.InlayHints.ts
var ts_InlayHints_exports = {};
__export(ts_InlayHints_exports, {
  provideInlayHints: () => provideInlayHints
});

// src/services/inlayHints.ts
var maxHintsLength = 30;
var leadingParameterNameCommentRegexFactory = (name) => {
  return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`);
};
function shouldShowParameterNameHints(preferences) {
  return preferences.includeInlayParameterNameHints === "literals" || preferences.includeInlayParameterNameHints === "all";
}
function shouldShowLiteralParameterNameHintsOnly(preferences) {
  return preferences.includeInlayParameterNameHints === "literals";
}
function provideInlayHints(context) {
  const { file, program, span, cancellationToken, preferences } = context;
  const sourceFileText = file.text;
  const compilerOptions = program.getCompilerOptions();
  const checker = program.getTypeChecker();
  const result = [];
  visitor(file);
  return result;
  function visitor(node) {
    if (!node || node.getFullWidth() === 0) {
      return;
    }
    switch (node.kind) {
      case 266 /* ModuleDeclaration */:
      case 262 /* ClassDeclaration */:
      case 263 /* InterfaceDeclaration */:
      case 261 /* FunctionDeclaration */:
      case 230 /* ClassExpression */:
      case 217 /* FunctionExpression */:
      case 173 /* MethodDeclaration */:
      case 218 /* ArrowFunction */:
        cancellationToken.throwIfCancellationRequested();
    }
    if (!textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
      return;
    }
    if (isTypeNode(node) && !isExpressionWithTypeArguments(node)) {
      return;
    }
    if (preferences.includeInlayVariableTypeHints && isVariableDeclaration(node)) {
      visitVariableLikeDeclaration(node);
    } else if (preferences.includeInlayPropertyDeclarationTypeHints && isPropertyDeclaration(node)) {
      visitVariableLikeDeclaration(node);
    } else if (preferences.includeInlayEnumMemberValueHints && isEnumMember(node)) {
      visitEnumMember(node);
    } else if (shouldShowParameterNameHints(preferences) && (isCallExpression(node) || isNewExpression(node))) {
      visitCallOrNewExpression(node);
    } else {
      if (preferences.includeInlayFunctionParameterTypeHints && isFunctionLikeDeclaration(node) && hasContextSensitiveParameters(node)) {
        visitFunctionLikeForParameterType(node);
      }
      if (preferences.includeInlayFunctionLikeReturnTypeHints && isSignatureSupportingReturnAnnotation(node)) {
        visitFunctionDeclarationLikeForReturnType(node);
      }
    }
    return forEachChild(node, visitor);
  }
  function isSignatureSupportingReturnAnnotation(node) {
    return isArrowFunction(node) || isFunctionExpression(node) || isFunctionDeclaration(node) || isMethodDeclaration(node) || isGetAccessorDeclaration(node);
  }
  function addParameterHints(text, position, isFirstVariadicArgument) {
    result.push({
      text: `${isFirstVariadicArgument ? "..." : ""}${truncation(text, maxHintsLength)}:`,
      position,
      kind: "Parameter" /* Parameter */,
      whitespaceAfter: true
    });
  }
  function addTypeHints(text, position) {
    result.push({
      text: `: ${truncation(text, maxHintsLength)}`,
      position,
      kind: "Type" /* Type */,
      whitespaceBefore: true
    });
  }
  function addEnumMemberValueHints(text, position) {
    result.push({
      text: `= ${truncation(text, maxHintsLength)}`,
      position,
      kind: "Enum" /* Enum */,
      whitespaceBefore: true
    });
  }
  function visitEnumMember(member) {
    if (member.initializer) {
      return;
    }
    const enumValue = checker.getConstantValue(member);
    if (enumValue !== void 0) {
      addEnumMemberValueHints(enumValue.toString(), member.end);
    }
  }
  function isModuleReferenceType(type) {
    return type.symbol && type.symbol.flags & 1536 /* Module */;
  }
  function visitVariableLikeDeclaration(decl) {
    if (!decl.initializer || isBindingPattern(decl.name) || isVariableDeclaration(decl) && !isHintableDeclaration(decl)) {
      return;
    }
    const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(decl);
    if (effectiveTypeAnnotation) {
      return;
    }
    const declarationType = checker.getTypeAtLocation(decl);
    if (isModuleReferenceType(declarationType)) {
      return;
    }
    const typeDisplayString = printTypeInSingleLine(declarationType);
    if (typeDisplayString) {
      const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), typeDisplayString);
      if (isVariableNameMatchesType) {
        return;
      }
      addTypeHints(typeDisplayString, decl.name.end);
    }
  }
  function visitCallOrNewExpression(expr) {
    const args = expr.arguments;
    if (!args || !args.length) {
      return;
    }
    const candidates = [];
    const signature = checker.getResolvedSignatureForSignatureHelp(expr, candidates);
    if (!signature || !candidates.length) {
      return;
    }
    for (let i = 0; i < args.length; ++i) {
      const originalArg = args[i];
      const arg = skipParentheses(originalArg);
      if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) {
        continue;
      }
      const identifierNameInfo = checker.getParameterIdentifierNameAtPosition(signature, i);
      if (identifierNameInfo) {
        const [parameterName, isFirstVariadicArgument] = identifierNameInfo;
        const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName);
        if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) {
          continue;
        }
        const name = unescapeLeadingUnderscores(parameterName);
        if (leadingCommentsContainsParameterName(arg, name)) {
          continue;
        }
        addParameterHints(name, originalArg.getStart(), isFirstVariadicArgument);
      }
    }
  }
  function identifierOrAccessExpressionPostfixMatchesParameterName(expr, parameterName) {
    if (isIdentifier(expr)) {
      return expr.text === parameterName;
    }
    if (isPropertyAccessExpression(expr)) {
      return expr.name.text === parameterName;
    }
    return false;
  }
  function leadingCommentsContainsParameterName(node, name) {
    if (!isIdentifierText(name, compilerOptions.target, getLanguageVariant(file.scriptKind))) {
      return false;
    }
    const ranges = getLeadingCommentRanges(sourceFileText, node.pos);
    if (!(ranges == null ? void 0 : ranges.length)) {
      return false;
    }
    const regex = leadingParameterNameCommentRegexFactory(name);
    return some(ranges, (range) => regex.test(sourceFileText.substring(range.pos, range.end)));
  }
  function isHintableLiteral(node) {
    switch (node.kind) {
      case 223 /* PrefixUnaryExpression */: {
        const operand = node.operand;
        return isLiteralExpression(operand) || isIdentifier(operand) && isInfinityOrNaNString(operand.escapedText);
      }
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 227 /* TemplateExpression */:
        return true;
      case 80 /* Identifier */: {
        const name = node.escapedText;
        return isUndefined(name) || isInfinityOrNaNString(name);
      }
    }
    return isLiteralExpression(node);
  }
  function visitFunctionDeclarationLikeForReturnType(decl) {
    if (isArrowFunction(decl)) {
      if (!findChildOfKind(decl, 21 /* OpenParenToken */, file)) {
        return;
      }
    }
    const effectiveTypeAnnotation = getEffectiveReturnTypeNode(decl);
    if (effectiveTypeAnnotation || !decl.body) {
      return;
    }
    const signature = checker.getSignatureFromDeclaration(decl);
    if (!signature) {
      return;
    }
    const returnType = checker.getReturnTypeOfSignature(signature);
    if (isModuleReferenceType(returnType)) {
      return;
    }
    const typeDisplayString = printTypeInSingleLine(returnType);
    if (!typeDisplayString) {
      return;
    }
    addTypeHints(typeDisplayString, getTypeAnnotationPosition(decl));
  }
  function getTypeAnnotationPosition(decl) {
    const closeParenToken = findChildOfKind(decl, 22 /* CloseParenToken */, file);
    if (closeParenToken) {
      return closeParenToken.end;
    }
    return decl.parameters.end;
  }
  function visitFunctionLikeForParameterType(node) {
    const signature = checker.getSignatureFromDeclaration(node);
    if (!signature) {
      return;
    }
    for (let i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) {
      const param = node.parameters[i];
      if (!isHintableDeclaration(param)) {
        continue;
      }
      const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(param);
      if (effectiveTypeAnnotation) {
        continue;
      }
      const typeDisplayString = getParameterDeclarationTypeDisplayString(signature.parameters[i]);
      if (!typeDisplayString) {
        continue;
      }
      addTypeHints(typeDisplayString, param.questionToken ? param.questionToken.end : param.name.end);
    }
  }
  function getParameterDeclarationTypeDisplayString(symbol) {
    const valueDeclaration = symbol.valueDeclaration;
    if (!valueDeclaration || !isParameter(valueDeclaration)) {
      return void 0;
    }
    const signatureParamType = checker.getTypeOfSymbolAtLocation(symbol, valueDeclaration);
    if (isModuleReferenceType(signatureParamType)) {
      return void 0;
    }
    return printTypeInSingleLine(signatureParamType);
  }
  function truncation(text, maxLength2) {
    if (text.length > maxLength2) {
      return text.substr(0, maxLength2 - "...".length) + "...";
    }
    return text;
  }
  function printTypeInSingleLine(type) {
    const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
    const printer = createPrinterWithRemoveComments();
    return usingSingleLineStringWriter((writer) => {
      const typeNode = checker.typeToTypeNode(
        type,
        /*enclosingDeclaration*/
        void 0,
        flags
      );
      Debug.assertIsDefined(typeNode, "should always get typenode");
      printer.writeNode(
        4 /* Unspecified */,
        typeNode,
        /*sourceFile*/
        file,
        writer
      );
    });
  }
  function isUndefined(name) {
    return name === "undefined";
  }
  function isHintableDeclaration(node) {
    if ((isParameterDeclaration(node) || isVariableDeclaration(node) && isVarConst(node)) && node.initializer) {
      const initializer = skipParentheses(node.initializer);
      return !(isHintableLiteral(initializer) || isNewExpression(initializer) || isObjectLiteralExpression(initializer) || isAssertionExpression(initializer));
    }
    return true;
  }
}

// src/services/_namespaces/ts.JsDoc.ts
var ts_JsDoc_exports = {};
__export(ts_JsDoc_exports, {
  getDocCommentTemplateAtPosition: () => getDocCommentTemplateAtPosition,
  getJSDocParameterNameCompletionDetails: () => getJSDocParameterNameCompletionDetails,
  getJSDocParameterNameCompletions: () => getJSDocParameterNameCompletions,
  getJSDocTagCompletionDetails: () => getJSDocTagCompletionDetails,
  getJSDocTagCompletions: () => getJSDocTagCompletions,
  getJSDocTagNameCompletionDetails: () => getJSDocTagNameCompletionDetails,
  getJSDocTagNameCompletions: () => getJSDocTagNameCompletions,
  getJsDocCommentsFromDeclarations: () => getJsDocCommentsFromDeclarations,
  getJsDocTagsFromDeclarations: () => getJsDocTagsFromDeclarations
});

// src/services/jsDoc.ts
var jsDocTagNames = [
  "abstract",
  "access",
  "alias",
  "argument",
  "async",
  "augments",
  "author",
  "borrows",
  "callback",
  "class",
  "classdesc",
  "constant",
  "constructor",
  "constructs",
  "copyright",
  "default",
  "deprecated",
  "description",
  "emits",
  "enum",
  "event",
  "example",
  "exports",
  "extends",
  "external",
  "field",
  "file",
  "fileoverview",
  "fires",
  "function",
  "generator",
  "global",
  "hideconstructor",
  "host",
  "ignore",
  "implements",
  "inheritdoc",
  "inner",
  "instance",
  "interface",
  "kind",
  "lends",
  "license",
  "link",
  "linkcode",
  "linkplain",
  "listens",
  "member",
  "memberof",
  "method",
  "mixes",
  "module",
  "name",
  "namespace",
  "overload",
  "override",
  "package",
  "param",
  "private",
  "prop",
  "property",
  "protected",
  "public",
  "readonly",
  "requires",
  "returns",
  "satisfies",
  "see",
  "since",
  "static",
  "summary",
  "template",
  "this",
  "throws",
  "todo",
  "tutorial",
  "type",
  "typedef",
  "var",
  "variation",
  "version",
  "virtual",
  "yields"
];
var jsDocTagNameCompletionEntries;
var jsDocTagCompletionEntries;
function getJsDocCommentsFromDeclarations(declarations, checker) {
  const parts = [];
  forEachUnique(declarations, (declaration) => {
    for (const jsdoc of getCommentHavingNodes(declaration)) {
      const inheritDoc = isJSDoc(jsdoc) && jsdoc.tags && find(jsdoc.tags, (t) => t.kind === 333 /* JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc"));
      if (jsdoc.comment === void 0 && !inheritDoc || isJSDoc(jsdoc) && declaration.kind !== 352 /* JSDocTypedefTag */ && declaration.kind !== 344 /* JSDocCallbackTag */ && jsdoc.tags && jsdoc.tags.some((t) => t.kind === 352 /* JSDocTypedefTag */ || t.kind === 344 /* JSDocCallbackTag */) && !jsdoc.tags.some((t) => t.kind === 347 /* JSDocParameterTag */ || t.kind === 348 /* JSDocReturnTag */)) {
        continue;
      }
      let newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : [];
      if (inheritDoc && inheritDoc.comment) {
        newparts = newparts.concat(getDisplayPartsFromComment(inheritDoc.comment, checker));
      }
      if (!contains(parts, newparts, isIdenticalListOfDisplayParts)) {
        parts.push(newparts);
      }
    }
  });
  return flatten(intersperse(parts, [lineBreakPart()]));
}
function isIdenticalListOfDisplayParts(parts1, parts2) {
  return arraysEqual(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text);
}
function getCommentHavingNodes(declaration) {
  switch (declaration.kind) {
    case 347 /* JSDocParameterTag */:
    case 354 /* JSDocPropertyTag */:
      return [declaration];
    case 344 /* JSDocCallbackTag */:
    case 352 /* JSDocTypedefTag */:
      return [declaration, declaration.parent];
    default:
      return getJSDocCommentsAndTags(declaration);
  }
}
function getJsDocTagsFromDeclarations(declarations, checker) {
  const infos = [];
  forEachUnique(declarations, (declaration) => {
    const tags = getJSDocTags(declaration);
    if (tags.some((t) => t.kind === 352 /* JSDocTypedefTag */ || t.kind === 344 /* JSDocCallbackTag */) && !tags.some((t) => t.kind === 347 /* JSDocParameterTag */ || t.kind === 348 /* JSDocReturnTag */)) {
      return;
    }
    for (const tag of tags) {
      infos.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) });
    }
  });
  return infos;
}
function getDisplayPartsFromComment(comment, checker) {
  if (typeof comment === "string") {
    return [textPart(comment)];
  }
  return flatMap(
    comment,
    (node) => node.kind === 327 /* JSDocText */ ? [textPart(node.text)] : buildLinkParts(node, checker)
  );
}
function getCommentDisplayParts(tag, checker) {
  const { comment, kind } = tag;
  const namePart = getTagNameDisplayPart(kind);
  switch (kind) {
    case 355 /* JSDocThrowsTag */:
      const typeExpression = tag.typeExpression;
      return typeExpression ? withNode(typeExpression) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker);
    case 335 /* JSDocImplementsTag */:
      return withNode(tag.class);
    case 334 /* JSDocAugmentsTag */:
      return withNode(tag.class);
    case 351 /* JSDocTemplateTag */:
      const templateTag = tag;
      const displayParts = [];
      if (templateTag.constraint) {
        displayParts.push(textPart(templateTag.constraint.getText()));
      }
      if (length(templateTag.typeParameters)) {
        if (length(displayParts)) {
          displayParts.push(spacePart());
        }
        const lastTypeParameter = templateTag.typeParameters[templateTag.typeParameters.length - 1];
        forEach(templateTag.typeParameters, (tp) => {
          displayParts.push(namePart(tp.getText()));
          if (lastTypeParameter !== tp) {
            displayParts.push(...[punctuationPart(28 /* CommaToken */), spacePart()]);
          }
        });
      }
      if (comment) {
        displayParts.push(...[spacePart(), ...getDisplayPartsFromComment(comment, checker)]);
      }
      return displayParts;
    case 350 /* JSDocTypeTag */:
    case 356 /* JSDocSatisfiesTag */:
      return withNode(tag.typeExpression);
    case 352 /* JSDocTypedefTag */:
    case 344 /* JSDocCallbackTag */:
    case 354 /* JSDocPropertyTag */:
    case 347 /* JSDocParameterTag */:
    case 353 /* JSDocSeeTag */:
      const { name } = tag;
      return name ? withNode(name) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker);
    default:
      return comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker);
  }
  function withNode(node) {
    return addComment(node.getText());
  }
  function addComment(s) {
    if (comment) {
      if (s.match(/^https?$/)) {
        return [textPart(s), ...getDisplayPartsFromComment(comment, checker)];
      } else {
        return [namePart(s), spacePart(), ...getDisplayPartsFromComment(comment, checker)];
      }
    } else {
      return [textPart(s)];
    }
  }
}
function getTagNameDisplayPart(kind) {
  switch (kind) {
    case 347 /* JSDocParameterTag */:
      return parameterNamePart;
    case 354 /* JSDocPropertyTag */:
      return propertyNamePart;
    case 351 /* JSDocTemplateTag */:
      return typeParameterNamePart;
    case 352 /* JSDocTypedefTag */:
    case 344 /* JSDocCallbackTag */:
      return typeAliasNamePart;
    default:
      return textPart;
  }
}
function getJSDocTagNameCompletions() {
  return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, (tagName) => {
    return {
      name: tagName,
      kind: "keyword" /* keyword */,
      kindModifiers: "",
      sortText: ts_Completions_exports.SortText.LocationPriority
    };
  }));
}
var getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
function getJSDocTagCompletions() {
  return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, (tagName) => {
    return {
      name: `@${tagName}`,
      kind: "keyword" /* keyword */,
      kindModifiers: "",
      sortText: ts_Completions_exports.SortText.LocationPriority
    };
  }));
}
function getJSDocTagCompletionDetails(name) {
  return {
    name,
    kind: "" /* unknown */,
    // TODO: should have its own kind?
    kindModifiers: "",
    displayParts: [textPart(name)],
    documentation: emptyArray,
    tags: void 0,
    codeActions: void 0
  };
}
function getJSDocParameterNameCompletions(tag) {
  if (!isIdentifier(tag.name)) {
    return emptyArray;
  }
  const nameThusFar = tag.name.text;
  const jsdoc = tag.parent;
  const fn = jsdoc.parent;
  if (!isFunctionLike(fn))
    return [];
  return mapDefined(fn.parameters, (param) => {
    if (!isIdentifier(param.name))
      return void 0;
    const name = param.name.text;
    if (jsdoc.tags.some((t) => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) {
      return void 0;
    }
    return { name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: ts_Completions_exports.SortText.LocationPriority };
  });
}
function getJSDocParameterNameCompletionDetails(name) {
  return {
    name,
    kind: "parameter" /* parameterElement */,
    kindModifiers: "",
    displayParts: [textPart(name)],
    documentation: emptyArray,
    tags: void 0,
    codeActions: void 0
  };
}
function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) {
  const tokenAtPos = getTokenAtPosition(sourceFile, position);
  const existingDocComment = findAncestor(tokenAtPos, isJSDoc);
  if (existingDocComment && (existingDocComment.comment !== void 0 || length(existingDocComment.tags))) {
    return void 0;
  }
  const tokenStart = tokenAtPos.getStart(sourceFile);
  if (!existingDocComment && tokenStart < position) {
    return void 0;
  }
  const commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options);
  if (!commentOwnerInfo) {
    return void 0;
  }
  const { commentOwner, parameters, hasReturn: hasReturn2 } = commentOwnerInfo;
  const commentOwnerJsDoc = hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : void 0;
  const lastJsDoc = lastOrUndefined(commentOwnerJsDoc);
  if (commentOwner.getStart(sourceFile) < position || lastJsDoc && existingDocComment && lastJsDoc !== existingDocComment) {
    return void 0;
  }
  const indentationStr = getIndentationStringAtPosition(sourceFile, position);
  const isJavaScriptFile = hasJSFileExtension(sourceFile.fileName);
  const tags = (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") + (hasReturn2 ? returnsDocComment(indentationStr, newLine) : "");
  const openComment = "/**";
  const closeComment = " */";
  const hasTag = (commentOwnerJsDoc || []).some((jsDoc) => !!jsDoc.tags);
  if (tags && !hasTag) {
    const preamble = openComment + newLine + indentationStr + " * ";
    const endLine = tokenStart === position ? newLine + indentationStr : "";
    const result = preamble + newLine + tags + indentationStr + closeComment + endLine;
    return { newText: result, caretOffset: preamble.length };
  }
  return { newText: openComment + closeComment, caretOffset: 3 };
}
function getIndentationStringAtPosition(sourceFile, position) {
  const { text } = sourceFile;
  const lineStart = getLineStartPositionForPosition(position, sourceFile);
  let pos = lineStart;
  for (; pos <= position && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++)
    ;
  return text.slice(lineStart, pos);
}
function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
  return parameters.map(({ name, dotDotDotToken }, i) => {
    const paramName = name.kind === 80 /* Identifier */ ? name.text : "param" + i;
    const type = isJavaScriptFile ? dotDotDotToken ? "{...any} " : "{any} " : "";
    return `${indentationStr} * @param ${type}${paramName}${newLine}`;
  }).join("");
}
function returnsDocComment(indentationStr, newLine) {
  return `${indentationStr} * @returns${newLine}`;
}
function getCommentOwnerInfo(tokenAtPos, options) {
  return forEachAncestor(tokenAtPos, (n) => getCommentOwnerInfoWorker(n, options));
}
function getCommentOwnerInfoWorker(commentOwner, options) {
  switch (commentOwner.kind) {
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 173 /* MethodDeclaration */:
    case 175 /* Constructor */:
    case 172 /* MethodSignature */:
    case 218 /* ArrowFunction */:
      const host = commentOwner;
      return { commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) };
    case 302 /* PropertyAssignment */:
      return getCommentOwnerInfoWorker(commentOwner.initializer, options);
    case 262 /* ClassDeclaration */:
    case 263 /* InterfaceDeclaration */:
    case 265 /* EnumDeclaration */:
    case 305 /* EnumMember */:
    case 264 /* TypeAliasDeclaration */:
      return { commentOwner };
    case 170 /* PropertySignature */: {
      const host2 = commentOwner;
      return host2.type && isFunctionTypeNode(host2.type) ? { commentOwner, parameters: host2.type.parameters, hasReturn: hasReturn(host2.type, options) } : { commentOwner };
    }
    case 242 /* VariableStatement */: {
      const varStatement = commentOwner;
      const varDeclarations = varStatement.declarationList.declarations;
      const host2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : void 0;
      return host2 ? { commentOwner, parameters: host2.parameters, hasReturn: hasReturn(host2, options) } : { commentOwner };
    }
    case 311 /* SourceFile */:
      return "quit";
    case 266 /* ModuleDeclaration */:
      return commentOwner.parent.kind === 266 /* ModuleDeclaration */ ? void 0 : { commentOwner };
    case 243 /* ExpressionStatement */:
      return getCommentOwnerInfoWorker(commentOwner.expression, options);
    case 225 /* BinaryExpression */: {
      const be = commentOwner;
      if (getAssignmentDeclarationKind(be) === 0 /* None */) {
        return "quit";
      }
      return isFunctionLike(be.right) ? { commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner };
    }
    case 171 /* PropertyDeclaration */:
      const init = commentOwner.initializer;
      if (init && (isFunctionExpression(init) || isArrowFunction(init))) {
        return { commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) };
      }
  }
}
function hasReturn(node, options) {
  return !!(options == null ? void 0 : options.generateReturnInDocTemplate) && (isFunctionTypeNode(node) || isArrowFunction(node) && isExpression(node.body) || isFunctionLikeDeclaration(node) && node.body && isBlock(node.body) && !!forEachReturnStatement(node.body, (n) => n));
}
function getRightHandSideOfAssignment(rightHandSide) {
  while (rightHandSide.kind === 216 /* ParenthesizedExpression */) {
    rightHandSide = rightHandSide.expression;
  }
  switch (rightHandSide.kind) {
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
      return rightHandSide;
    case 230 /* ClassExpression */:
      return find(rightHandSide.members, isConstructorDeclaration);
  }
}

// src/services/_namespaces/ts.OrganizeImports.ts
var ts_OrganizeImports_exports = {};
__export(ts_OrganizeImports_exports, {
  coalesceExports: () => coalesceExports,
  coalesceImports: () => coalesceImports,
  compareImportOrExportSpecifiers: () => compareImportOrExportSpecifiers,
  compareImportsOrRequireStatements: () => compareImportsOrRequireStatements,
  compareModuleSpecifiers: () => compareModuleSpecifiers2,
  detectImportDeclarationSorting: () => detectImportDeclarationSorting,
  detectImportSpecifierSorting: () => detectImportSpecifierSorting,
  detectSorting: () => detectSorting,
  getImportDeclarationInsertionIndex: () => getImportDeclarationInsertionIndex,
  getImportSpecifierInsertionIndex: () => getImportSpecifierInsertionIndex,
  getOrganizeImportsComparer: () => getOrganizeImportsComparer,
  organizeImports: () => organizeImports
});

// src/services/organizeImports.ts
function organizeImports(sourceFile, formatContext, host, program, preferences, mode) {
  const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext({ host, formatContext, preferences });
  const shouldSort = mode === "SortAndCombine" /* SortAndCombine */ || mode === "All" /* All */;
  const shouldCombine = shouldSort;
  const shouldRemove = mode === "RemoveUnused" /* RemoveUnused */ || mode === "All" /* All */;
  const topLevelImportGroupDecls = groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration));
  const comparer = getOrganizeImportsComparerWithDetection(preferences, shouldSort ? () => detectSortingWorker(topLevelImportGroupDecls, preferences) === 2 /* CaseInsensitive */ : void 0);
  const processImportsOfSameModuleSpecifier = (importGroup) => {
    if (shouldRemove)
      importGroup = removeUnusedImports(importGroup, sourceFile, program);
    if (shouldCombine)
      importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile);
    if (shouldSort)
      importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, comparer));
    return importGroup;
  };
  topLevelImportGroupDecls.forEach((importGroupDecl) => organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier));
  if (mode !== "RemoveUnused" /* RemoveUnused */) {
    getTopLevelExportGroups(sourceFile).forEach((exportGroupDecl) => organizeImportsWorker(exportGroupDecl, (group2) => coalesceExportsWorker(group2, comparer)));
  }
  for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
    if (!ambientModule.body)
      continue;
    const ambientModuleImportGroupDecls = groupByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(isImportDeclaration));
    ambientModuleImportGroupDecls.forEach((importGroupDecl) => organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier));
    if (mode !== "RemoveUnused" /* RemoveUnused */) {
      const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration);
      organizeImportsWorker(ambientModuleExportDecls, (group2) => coalesceExportsWorker(group2, comparer));
    }
  }
  return changeTracker.getChanges();
  function organizeImportsWorker(oldImportDecls, coalesce) {
    if (length(oldImportDecls) === 0) {
      return;
    }
    suppressLeadingTrivia(oldImportDecls[0]);
    const oldImportGroups = shouldCombine ? group(oldImportDecls, (importDecl) => getExternalModuleName2(importDecl.moduleSpecifier)) : [oldImportDecls];
    const sortedImportGroups = shouldSort ? stableSort(oldImportGroups, (group1, group2) => compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer)) : oldImportGroups;
    const newImportDecls = flatMap(sortedImportGroups, (importGroup) => getExternalModuleName2(importGroup[0].moduleSpecifier) || importGroup[0].moduleSpecifier === void 0 ? coalesce(importGroup) : importGroup);
    if (newImportDecls.length === 0) {
      changeTracker.deleteNodes(
        sourceFile,
        oldImportDecls,
        {
          leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
          trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
        },
        /*hasTrailingComment*/
        true
      );
    } else {
      const replaceOptions = {
        leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude,
        // Leave header comment in place
        trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include,
        suffix: getNewLineOrDefaultFromHost(host, formatContext.options)
      };
      changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions);
      const hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions);
      changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), {
        trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include
      }, hasTrailingComment);
    }
  }
}
function groupByNewlineContiguous(sourceFile, decls) {
  const scanner2 = createScanner(
    sourceFile.languageVersion,
    /*skipTrivia*/
    false,
    sourceFile.languageVariant
  );
  const group2 = [];
  let groupIndex = 0;
  for (const decl of decls) {
    if (group2[groupIndex] && isNewGroup(sourceFile, decl, scanner2)) {
      groupIndex++;
    }
    if (!group2[groupIndex]) {
      group2[groupIndex] = [];
    }
    group2[groupIndex].push(decl);
  }
  return group2;
}
function isNewGroup(sourceFile, decl, scanner2) {
  const startPos = decl.getFullStart();
  const endPos = decl.getStart();
  scanner2.setText(sourceFile.text, startPos, endPos - startPos);
  let numberOfNewLines = 0;
  while (scanner2.getTokenStart() < endPos) {
    const tokenKind = scanner2.scan();
    if (tokenKind === 4 /* NewLineTrivia */) {
      numberOfNewLines++;
      if (numberOfNewLines >= 2) {
        return true;
      }
    }
  }
  return false;
}
function removeUnusedImports(oldImports, sourceFile, program) {
  const typeChecker = program.getTypeChecker();
  const compilerOptions = program.getCompilerOptions();
  const jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
  const jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile);
  const jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
  const usedImports = [];
  for (const importDecl of oldImports) {
    const { importClause, moduleSpecifier } = importDecl;
    if (!importClause) {
      usedImports.push(importDecl);
      continue;
    }
    let { name, namedBindings } = importClause;
    if (name && !isDeclarationUsed(name)) {
      name = void 0;
    }
    if (namedBindings) {
      if (isNamespaceImport(namedBindings)) {
        if (!isDeclarationUsed(namedBindings.name)) {
          namedBindings = void 0;
        }
      } else {
        const newElements = namedBindings.elements.filter((e) => isDeclarationUsed(e.name));
        if (newElements.length < namedBindings.elements.length) {
          namedBindings = newElements.length ? factory.updateNamedImports(namedBindings, newElements) : void 0;
        }
      }
    }
    if (name || namedBindings) {
      usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
    } else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
      if (sourceFile.isDeclarationFile) {
        usedImports.push(factory.createImportDeclaration(
          importDecl.modifiers,
          /*importClause*/
          void 0,
          moduleSpecifier,
          /*assertClause*/
          void 0
        ));
      } else {
        usedImports.push(importDecl);
      }
    }
  }
  return usedImports;
  function isDeclarationUsed(identifier) {
    return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) && jsxModeNeedsExplicitImport(compilerOptions.jsx) || ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
  }
}
function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) {
  const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
  return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, (moduleName) => isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText);
}
function getExternalModuleName2(specifier) {
  return specifier !== void 0 && isStringLiteralLike(specifier) ? specifier.text : void 0;
}
function coalesceImports(importGroup, ignoreCase, sourceFile) {
  const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
  return coalesceImportsWorker(importGroup, comparer, sourceFile);
}
function coalesceImportsWorker(importGroup, comparer, sourceFile) {
  if (importGroup.length === 0) {
    return importGroup;
  }
  const { importWithoutClause, typeOnlyImports, regularImports } = getCategorizedImports(importGroup);
  const coalescedImports = [];
  if (importWithoutClause) {
    coalescedImports.push(importWithoutClause);
  }
  for (const group2 of [regularImports, typeOnlyImports]) {
    const isTypeOnly = group2 === typeOnlyImports;
    const { defaultImports, namespaceImports, namedImports } = group2;
    if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
      const defaultImport = defaultImports[0];
      coalescedImports.push(
        updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)
      );
      continue;
    }
    const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2) => comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text));
    for (const namespaceImport of sortedNamespaceImports) {
      coalescedImports.push(
        updateImportDeclarationAndClause(
          namespaceImport,
          /*name*/
          void 0,
          namespaceImport.importClause.namedBindings
        )
      );
    }
    const firstDefaultImport = firstOrUndefined(defaultImports);
    const firstNamedImport = firstOrUndefined(namedImports);
    const importDecl = firstDefaultImport ?? firstNamedImport;
    if (!importDecl) {
      continue;
    }
    let newDefaultImport;
    const newImportSpecifiers = [];
    if (defaultImports.length === 1) {
      newDefaultImport = defaultImports[0].importClause.name;
    } else {
      for (const defaultImport of defaultImports) {
        newImportSpecifiers.push(
          factory.createImportSpecifier(
            /*isTypeOnly*/
            false,
            factory.createIdentifier("default"),
            defaultImport.importClause.name
          )
        );
      }
    }
    newImportSpecifiers.push(...getNewImportSpecifiers(namedImports));
    const sortedImportSpecifiers = factory.createNodeArray(
      sortSpecifiers(newImportSpecifiers, comparer),
      firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma
    );
    const newNamedImports = sortedImportSpecifiers.length === 0 ? newDefaultImport ? void 0 : factory.createNamedImports(emptyArray) : firstNamedImport ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) : factory.createNamedImports(sortedImportSpecifiers);
    if (sourceFile && newNamedImports && (firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings) && !rangeIsOnSingleLine(firstNamedImport.importClause.namedBindings, sourceFile)) {
      setEmitFlags(newNamedImports, 2 /* MultiLine */);
    }
    if (isTypeOnly && newDefaultImport && newNamedImports) {
      coalescedImports.push(
        updateImportDeclarationAndClause(
          importDecl,
          newDefaultImport,
          /*namedBindings*/
          void 0
        )
      );
      coalescedImports.push(
        updateImportDeclarationAndClause(
          firstNamedImport ?? importDecl,
          /*name*/
          void 0,
          newNamedImports
        )
      );
    } else {
      coalescedImports.push(
        updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)
      );
    }
  }
  return coalescedImports;
}
function getCategorizedImports(importGroup) {
  let importWithoutClause;
  const typeOnlyImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
  const regularImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
  for (const importDeclaration of importGroup) {
    if (importDeclaration.importClause === void 0) {
      importWithoutClause = importWithoutClause || importDeclaration;
      continue;
    }
    const group2 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports;
    const { name, namedBindings } = importDeclaration.importClause;
    if (name) {
      group2.defaultImports.push(importDeclaration);
    }
    if (namedBindings) {
      if (isNamespaceImport(namedBindings)) {
        group2.namespaceImports.push(importDeclaration);
      } else {
        group2.namedImports.push(importDeclaration);
      }
    }
  }
  return {
    importWithoutClause,
    typeOnlyImports,
    regularImports
  };
}
function coalesceExports(exportGroup, ignoreCase) {
  const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
  return coalesceExportsWorker(exportGroup, comparer);
}
function coalesceExportsWorker(exportGroup, comparer) {
  if (exportGroup.length === 0) {
    return exportGroup;
  }
  const { exportWithoutClause, namedExports, typeOnlyExports } = getCategorizedExports(exportGroup);
  const coalescedExports = [];
  if (exportWithoutClause) {
    coalescedExports.push(exportWithoutClause);
  }
  for (const exportGroup2 of [namedExports, typeOnlyExports]) {
    if (exportGroup2.length === 0) {
      continue;
    }
    const newExportSpecifiers = [];
    newExportSpecifiers.push(...flatMap(exportGroup2, (i) => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray));
    const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer);
    const exportDecl = exportGroup2[0];
    coalescedExports.push(
      factory.updateExportDeclaration(
        exportDecl,
        exportDecl.modifiers,
        exportDecl.isTypeOnly,
        exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)),
        exportDecl.moduleSpecifier,
        exportDecl.assertClause
      )
    );
  }
  return coalescedExports;
  function getCategorizedExports(exportGroup2) {
    let exportWithoutClause2;
    const namedExports2 = [];
    const typeOnlyExports2 = [];
    for (const exportDeclaration of exportGroup2) {
      if (exportDeclaration.exportClause === void 0) {
        exportWithoutClause2 = exportWithoutClause2 || exportDeclaration;
      } else if (exportDeclaration.isTypeOnly) {
        typeOnlyExports2.push(exportDeclaration);
      } else {
        namedExports2.push(exportDeclaration);
      }
    }
    return {
      exportWithoutClause: exportWithoutClause2,
      namedExports: namedExports2,
      typeOnlyExports: typeOnlyExports2
    };
  }
}
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
  return factory.updateImportDeclaration(
    importDeclaration,
    importDeclaration.modifiers,
    factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings),
    // TODO: GH#18217
    importDeclaration.moduleSpecifier,
    importDeclaration.assertClause
  );
}
function sortSpecifiers(specifiers, comparer) {
  return stableSort(specifiers, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer));
}
function compareImportOrExportSpecifiers(s1, s2, comparer) {
  return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text);
}
function compareModuleSpecifiers2(m1, m2, ignoreCase) {
  const comparer = getOrganizeImportsOrdinalStringComparer(!!ignoreCase);
  return compareModuleSpecifiersWorker(m1, m2, comparer);
}
function compareModuleSpecifiersWorker(m1, m2, comparer) {
  const name1 = m1 === void 0 ? void 0 : getExternalModuleName2(m1);
  const name2 = m2 === void 0 ? void 0 : getExternalModuleName2(m2);
  return compareBooleans(name1 === void 0, name2 === void 0) || compareBooleans(isExternalModuleNameRelative(name1), isExternalModuleNameRelative(name2)) || comparer(name1, name2);
}
function getModuleSpecifierExpression(declaration) {
  var _a;
  switch (declaration.kind) {
    case 270 /* ImportEqualsDeclaration */:
      return (_a = tryCast(declaration.moduleReference, isExternalModuleReference)) == null ? void 0 : _a.expression;
    case 271 /* ImportDeclaration */:
      return declaration.moduleSpecifier;
    case 242 /* VariableStatement */:
      return declaration.declarationList.declarations[0].initializer.arguments[0];
  }
}
function detectSorting(sourceFile, preferences) {
  return detectSortingWorker(
    groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)),
    preferences
  );
}
function detectSortingWorker(importGroups, preferences) {
  const collateCaseSensitive = getOrganizeImportsComparer(
    preferences,
    /*ignoreCase*/
    false
  );
  const collateCaseInsensitive = getOrganizeImportsComparer(
    preferences,
    /*ignoreCase*/
    true
  );
  let sortState = 3 /* Both */;
  let seenUnsortedGroup = false;
  for (const importGroup of importGroups) {
    if (importGroup.length > 1) {
      const moduleSpecifierSort = detectSortCaseSensitivity(
        importGroup,
        (i) => {
          var _a;
          return ((_a = tryCast(i.moduleSpecifier, isStringLiteral)) == null ? void 0 : _a.text) ?? "";
        },
        collateCaseSensitive,
        collateCaseInsensitive
      );
      if (moduleSpecifierSort) {
        sortState &= moduleSpecifierSort;
        seenUnsortedGroup = true;
      }
      if (!sortState) {
        return sortState;
      }
    }
    const declarationWithNamedImports = find(
      importGroup,
      (i) => {
        var _a, _b;
        return ((_b = tryCast((_a = i.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements.length) > 1;
      }
    );
    if (declarationWithNamedImports) {
      const namedImportSort = detectImportSpecifierSorting(declarationWithNamedImports.importClause.namedBindings.elements, preferences);
      if (namedImportSort) {
        sortState &= namedImportSort;
        seenUnsortedGroup = true;
      }
      if (!sortState) {
        return sortState;
      }
    }
    if (sortState !== 3 /* Both */) {
      return sortState;
    }
  }
  return seenUnsortedGroup ? 0 /* None */ : sortState;
}
function detectImportDeclarationSorting(imports, preferences) {
  const collateCaseSensitive = getOrganizeImportsComparer(
    preferences,
    /*ignoreCase*/
    false
  );
  const collateCaseInsensitive = getOrganizeImportsComparer(
    preferences,
    /*ignoreCase*/
    true
  );
  return detectSortCaseSensitivity(
    imports,
    (s) => getExternalModuleName2(getModuleSpecifierExpression(s)) || "",
    collateCaseSensitive,
    collateCaseInsensitive
  );
}
var ImportSpecifierSortingCache = class {
  has([specifiers, preferences]) {
    if (this._lastPreferences !== preferences || !this._cache)
      return false;
    return this._cache.has(specifiers);
  }
  get([specifiers, preferences]) {
    if (this._lastPreferences !== preferences || !this._cache)
      return void 0;
    return this._cache.get(specifiers);
  }
  set([specifiers, preferences], value) {
    if (this._lastPreferences !== preferences) {
      this._lastPreferences = preferences;
      this._cache = void 0;
    }
    this._cache ?? (this._cache = /* @__PURE__ */ new WeakMap());
    this._cache.set(specifiers, value);
  }
};
var detectImportSpecifierSorting = memoizeCached((specifiers, preferences) => {
  if (!arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) {
    return 0 /* None */;
  }
  const collateCaseSensitive = getOrganizeImportsComparer(
    preferences,
    /*ignoreCase*/
    false
  );
  const collateCaseInsensitive = getOrganizeImportsComparer(
    preferences,
    /*ignoreCase*/
    true
  );
  return detectSortCaseSensitivity(specifiers, (specifier) => specifier.name.text, collateCaseSensitive, collateCaseInsensitive);
}, new ImportSpecifierSortingCache());
function getImportDeclarationInsertionIndex(sortedImports, newImport, comparer) {
  const index = binarySearch(sortedImports, newImport, identity, (a, b) => compareImportsOrRequireStatements(a, b, comparer));
  return index < 0 ? ~index : index;
}
function getImportSpecifierInsertionIndex(sortedImports, newImport, comparer) {
  const index = binarySearch(sortedImports, newImport, identity, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer));
  return index < 0 ? ~index : index;
}
function compareImportsOrRequireStatements(s1, s2, comparer) {
  return compareModuleSpecifiersWorker(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2), comparer) || compareImportKind(s1, s2);
}
function compareImportKind(s1, s2) {
  return compareValues(getImportKindOrder(s1), getImportKindOrder(s2));
}
function getImportKindOrder(s1) {
  var _a;
  switch (s1.kind) {
    case 271 /* ImportDeclaration */:
      if (!s1.importClause)
        return 0;
      if (s1.importClause.isTypeOnly)
        return 1;
      if (((_a = s1.importClause.namedBindings) == null ? void 0 : _a.kind) === 273 /* NamespaceImport */)
        return 2;
      if (s1.importClause.name)
        return 3;
      return 4;
    case 270 /* ImportEqualsDeclaration */:
      return 5;
    case 242 /* VariableStatement */:
      return 6;
  }
}
function getNewImportSpecifiers(namedImports) {
  return flatMap(
    namedImports,
    (namedImport) => map(
      tryGetNamedBindingElements(namedImport),
      (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier(
        importSpecifier,
        importSpecifier.isTypeOnly,
        /*propertyName*/
        void 0,
        importSpecifier.name
      ) : importSpecifier
    )
  );
}
function tryGetNamedBindingElements(namedImport) {
  var _a;
  return ((_a = namedImport.importClause) == null ? void 0 : _a.namedBindings) && isNamedImports(namedImport.importClause.namedBindings) ? namedImport.importClause.namedBindings.elements : void 0;
}
function getOrganizeImportsOrdinalStringComparer(ignoreCase) {
  return ignoreCase ? compareStringsCaseInsensitiveEslintCompatible : compareStringsCaseSensitive;
}
function getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) {
  const resolvedLocale = getOrganizeImportsLocale(preferences);
  const caseFirst = preferences.organizeImportsCaseFirst ?? false;
  const numeric = preferences.organizeImportsNumericCollation ?? false;
  const accents = preferences.organizeImportsAccentCollation ?? true;
  const sensitivity = ignoreCase ? accents ? "accent" : "base" : accents ? "variant" : "case";
  const collator = new Intl.Collator(resolvedLocale, {
    usage: "sort",
    caseFirst: caseFirst || "false",
    sensitivity,
    numeric
  });
  return collator.compare;
}
function getOrganizeImportsLocale(preferences) {
  let locale = preferences.organizeImportsLocale;
  if (locale === "auto")
    locale = getUILocale();
  if (locale === void 0)
    locale = "en";
  const supportedLocales = Intl.Collator.supportedLocalesOf(locale);
  const resolvedLocale = supportedLocales.length ? supportedLocales[0] : "en";
  return resolvedLocale;
}
function getOrganizeImportsComparer(preferences, ignoreCase) {
  const collation = preferences.organizeImportsCollation ?? "ordinal";
  return collation === "unicode" ? getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) : getOrganizeImportsOrdinalStringComparer(ignoreCase);
}
function getOrganizeImportsComparerWithDetection(preferences, detectIgnoreCase) {
  const ignoreCase = typeof preferences.organizeImportsIgnoreCase === "boolean" ? preferences.organizeImportsIgnoreCase : (detectIgnoreCase == null ? void 0 : detectIgnoreCase()) ?? false;
  return getOrganizeImportsComparer(preferences, ignoreCase);
}
function getTopLevelExportGroups(sourceFile) {
  const topLevelExportGroups = [];
  const statements = sourceFile.statements;
  const len = length(statements);
  let i = 0;
  let groupIndex = 0;
  while (i < len) {
    if (isExportDeclaration(statements[i])) {
      if (topLevelExportGroups[groupIndex] === void 0) {
        topLevelExportGroups[groupIndex] = [];
      }
      const exportDecl = statements[i];
      if (exportDecl.moduleSpecifier) {
        topLevelExportGroups[groupIndex].push(exportDecl);
        i++;
      } else {
        while (i < len && isExportDeclaration(statements[i])) {
          topLevelExportGroups[groupIndex].push(statements[i++]);
        }
        groupIndex++;
      }
    } else {
      i++;
    }
  }
  return flatMap(topLevelExportGroups, (exportGroupDecls) => groupByNewlineContiguous(sourceFile, exportGroupDecls));
}

// src/services/_namespaces/ts.OutliningElementsCollector.ts
var ts_OutliningElementsCollector_exports = {};
__export(ts_OutliningElementsCollector_exports, {
  collectElements: () => collectElements
});

// src/services/outliningElementsCollector.ts
function collectElements(sourceFile, cancellationToken) {
  const res = [];
  addNodeOutliningSpans(sourceFile, cancellationToken, res);
  addRegionOutliningSpans(sourceFile, res);
  return res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start);
}
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
  let depthRemaining = 40;
  let current = 0;
  const statements = [...sourceFile.statements, sourceFile.endOfFileToken];
  const n = statements.length;
  while (current < n) {
    while (current < n && !isAnyImportSyntax(statements[current])) {
      visitNode3(statements[current]);
      current++;
    }
    if (current === n)
      break;
    const firstImport = current;
    while (current < n && isAnyImportSyntax(statements[current])) {
      visitNode3(statements[current]);
      current++;
    }
    const lastImport = current - 1;
    if (lastImport !== firstImport) {
      out.push(createOutliningSpanFromBounds(findChildOfKind(statements[firstImport], 102 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
    }
  }
  function visitNode3(n2) {
    var _a;
    if (depthRemaining === 0)
      return;
    cancellationToken.throwIfCancellationRequested();
    if (isDeclaration(n2) || isVariableStatement(n2) || isReturnStatement(n2) || isCallOrNewExpression(n2) || n2.kind === 1 /* EndOfFileToken */) {
      addOutliningForLeadingCommentsForNode(n2, sourceFile, cancellationToken, out);
    }
    if (isFunctionLike(n2) && isBinaryExpression(n2.parent) && isPropertyAccessExpression(n2.parent.left)) {
      addOutliningForLeadingCommentsForNode(n2.parent.left, sourceFile, cancellationToken, out);
    }
    if (isBlock(n2) || isModuleBlock(n2)) {
      addOutliningForLeadingCommentsForPos(n2.statements.end, sourceFile, cancellationToken, out);
    }
    if (isClassLike(n2) || isInterfaceDeclaration(n2)) {
      addOutliningForLeadingCommentsForPos(n2.members.end, sourceFile, cancellationToken, out);
    }
    const span = getOutliningSpanForNode(n2, sourceFile);
    if (span)
      out.push(span);
    depthRemaining--;
    if (isCallExpression(n2)) {
      depthRemaining++;
      visitNode3(n2.expression);
      depthRemaining--;
      n2.arguments.forEach(visitNode3);
      (_a = n2.typeArguments) == null ? void 0 : _a.forEach(visitNode3);
    } else if (isIfStatement(n2) && n2.elseStatement && isIfStatement(n2.elseStatement)) {
      visitNode3(n2.expression);
      visitNode3(n2.thenStatement);
      depthRemaining++;
      visitNode3(n2.elseStatement);
      depthRemaining--;
    } else {
      n2.forEachChild(visitNode3);
    }
    depthRemaining++;
  }
}
function addRegionOutliningSpans(sourceFile, out) {
  const regions = [];
  const lineStarts = sourceFile.getLineStarts();
  for (const currentLineStart of lineStarts) {
    const lineEnd = sourceFile.getLineEndOfPosition(currentLineStart);
    const lineText = sourceFile.text.substring(currentLineStart, lineEnd);
    const result = isRegionDelimiter(lineText);
    if (!result || isInComment(sourceFile, currentLineStart)) {
      continue;
    }
    if (!result[1]) {
      const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
      regions.push(createOutliningSpan(
        span,
        "region" /* Region */,
        span,
        /*autoCollapse*/
        false,
        result[2] || "#region"
      ));
    } else {
      const region = regions.pop();
      if (region) {
        region.textSpan.length = lineEnd - region.textSpan.start;
        region.hintSpan.length = lineEnd - region.textSpan.start;
        out.push(region);
      }
    }
  }
}
var regionDelimiterRegExp = /^#(end)?region(?:\s+(.*))?(?:\r)?$/;
function isRegionDelimiter(lineText) {
  lineText = trimStringStart(lineText);
  if (!startsWith(lineText, "//")) {
    return null;
  }
  lineText = trimString(lineText.slice(2));
  return regionDelimiterRegExp.exec(lineText);
}
function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) {
  const comments = getLeadingCommentRanges(sourceFile.text, pos);
  if (!comments)
    return;
  let firstSingleLineCommentStart = -1;
  let lastSingleLineCommentEnd = -1;
  let singleLineCommentCount = 0;
  const sourceText = sourceFile.getFullText();
  for (const { kind, pos: pos2, end } of comments) {
    cancellationToken.throwIfCancellationRequested();
    switch (kind) {
      case 2 /* SingleLineCommentTrivia */:
        const commentText = sourceText.slice(pos2, end);
        if (isRegionDelimiter(commentText)) {
          combineAndAddMultipleSingleLineComments();
          singleLineCommentCount = 0;
          break;
        }
        if (singleLineCommentCount === 0) {
          firstSingleLineCommentStart = pos2;
        }
        lastSingleLineCommentEnd = end;
        singleLineCommentCount++;
        break;
      case 3 /* MultiLineCommentTrivia */:
        combineAndAddMultipleSingleLineComments();
        out.push(createOutliningSpanFromBounds(pos2, end, "comment" /* Comment */));
        singleLineCommentCount = 0;
        break;
      default:
        Debug.assertNever(kind);
    }
  }
  combineAndAddMultipleSingleLineComments();
  function combineAndAddMultipleSingleLineComments() {
    if (singleLineCommentCount > 1) {
      out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
    }
  }
}
function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
  if (isJsxText(n))
    return;
  addOutliningForLeadingCommentsForPos(n.pos, sourceFile, cancellationToken, out);
}
function createOutliningSpanFromBounds(pos, end, kind) {
  return createOutliningSpan(createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
  switch (n.kind) {
    case 240 /* Block */:
      if (isFunctionLike(n.parent)) {
        return functionSpan(n.parent, n, sourceFile);
      }
      switch (n.parent.kind) {
        case 245 /* DoStatement */:
        case 248 /* ForInStatement */:
        case 249 /* ForOfStatement */:
        case 247 /* ForStatement */:
        case 244 /* IfStatement */:
        case 246 /* WhileStatement */:
        case 253 /* WithStatement */:
        case 298 /* CatchClause */:
          return spanForNode(n.parent);
        case 257 /* TryStatement */:
          const tryStatement = n.parent;
          if (tryStatement.tryBlock === n) {
            return spanForNode(n.parent);
          } else if (tryStatement.finallyBlock === n) {
            const node = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile);
            if (node)
              return spanForNode(node);
          }
        default:
          return createOutliningSpan(createTextSpanFromNode(n, sourceFile), "code" /* Code */);
      }
    case 267 /* ModuleBlock */:
      return spanForNode(n.parent);
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
    case 263 /* InterfaceDeclaration */:
    case 265 /* EnumDeclaration */:
    case 268 /* CaseBlock */:
    case 186 /* TypeLiteral */:
    case 205 /* ObjectBindingPattern */:
      return spanForNode(n);
    case 188 /* TupleType */:
      return spanForNode(
        n,
        /*autoCollapse*/
        false,
        /*useFullStart*/
        !isTupleTypeNode(n.parent),
        23 /* OpenBracketToken */
      );
    case 295 /* CaseClause */:
    case 296 /* DefaultClause */:
      return spanForNodeArray(n.statements);
    case 209 /* ObjectLiteralExpression */:
      return spanForObjectOrArrayLiteral(n);
    case 208 /* ArrayLiteralExpression */:
      return spanForObjectOrArrayLiteral(n, 23 /* OpenBracketToken */);
    case 283 /* JsxElement */:
      return spanForJSXElement(n);
    case 287 /* JsxFragment */:
      return spanForJSXFragment(n);
    case 284 /* JsxSelfClosingElement */:
    case 285 /* JsxOpeningElement */:
      return spanForJSXAttributes(n.attributes);
    case 227 /* TemplateExpression */:
    case 15 /* NoSubstitutionTemplateLiteral */:
      return spanForTemplateLiteral(n);
    case 206 /* ArrayBindingPattern */:
      return spanForNode(
        n,
        /*autoCollapse*/
        false,
        /*useFullStart*/
        !isBindingElement(n.parent),
        23 /* OpenBracketToken */
      );
    case 218 /* ArrowFunction */:
      return spanForArrowFunction(n);
    case 212 /* CallExpression */:
      return spanForCallExpression(n);
    case 216 /* ParenthesizedExpression */:
      return spanForParenthesizedExpression(n);
    case 274 /* NamedImports */:
    case 278 /* NamedExports */:
    case 299 /* AssertClause */:
      return spanForNamedImportsOrExportsOrAssertClause(n);
  }
  function spanForNamedImportsOrExportsOrAssertClause(node) {
    if (!node.elements.length) {
      return void 0;
    }
    const openToken = findChildOfKind(node, 19 /* OpenBraceToken */, sourceFile);
    const closeToken = findChildOfKind(node, 20 /* CloseBraceToken */, sourceFile);
    if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) {
      return void 0;
    }
    return spanBetweenTokens(
      openToken,
      closeToken,
      node,
      sourceFile,
      /*autoCollapse*/
      false,
      /*useFullStart*/
      false
    );
  }
  function spanForCallExpression(node) {
    if (!node.arguments.length) {
      return void 0;
    }
    const openToken = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile);
    const closeToken = findChildOfKind(node, 22 /* CloseParenToken */, sourceFile);
    if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) {
      return void 0;
    }
    return spanBetweenTokens(
      openToken,
      closeToken,
      node,
      sourceFile,
      /*autoCollapse*/
      false,
      /*useFullStart*/
      true
    );
  }
  function spanForArrowFunction(node) {
    if (isBlock(node.body) || isParenthesizedExpression(node.body) || positionsAreOnSameLine(node.body.getFullStart(), node.body.getEnd(), sourceFile)) {
      return void 0;
    }
    const textSpan = createTextSpanFromBounds(node.body.getFullStart(), node.body.getEnd());
    return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(node));
  }
  function spanForJSXElement(node) {
    const textSpan = createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd());
    const tagName = node.openingElement.tagName.getText(sourceFile);
    const bannerText = "<" + tagName + ">...</" + tagName + ">";
    return createOutliningSpan(
      textSpan,
      "code" /* Code */,
      textSpan,
      /*autoCollapse*/
      false,
      bannerText
    );
  }
  function spanForJSXFragment(node) {
    const textSpan = createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd());
    const bannerText = "<>...</>";
    return createOutliningSpan(
      textSpan,
      "code" /* Code */,
      textSpan,
      /*autoCollapse*/
      false,
      bannerText
    );
  }
  function spanForJSXAttributes(node) {
    if (node.properties.length === 0) {
      return void 0;
    }
    return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
  }
  function spanForTemplateLiteral(node) {
    if (node.kind === 15 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) {
      return void 0;
    }
    return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
  }
  function spanForObjectOrArrayLiteral(node, open = 19 /* OpenBraceToken */) {
    return spanForNode(
      node,
      /*autoCollapse*/
      false,
      /*useFullStart*/
      !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent),
      open
    );
  }
  function spanForNode(hintSpanNode, autoCollapse = false, useFullStart = true, open = 19 /* OpenBraceToken */, close = open === 19 /* OpenBraceToken */ ? 20 /* CloseBraceToken */ : 24 /* CloseBracketToken */) {
    const openToken = findChildOfKind(n, open, sourceFile);
    const closeToken = findChildOfKind(n, close, sourceFile);
    return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart);
  }
  function spanForNodeArray(nodeArray) {
    return nodeArray.length ? createOutliningSpan(createTextSpanFromRange(nodeArray), "code" /* Code */) : void 0;
  }
  function spanForParenthesizedExpression(node) {
    if (positionsAreOnSameLine(node.getStart(), node.getEnd(), sourceFile))
      return void 0;
    const textSpan = createTextSpanFromBounds(node.getStart(), node.getEnd());
    return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(node));
  }
}
function functionSpan(node, body, sourceFile) {
  const openToken = tryGetFunctionOpenToken(node, body, sourceFile);
  const closeToken = findChildOfKind(body, 20 /* CloseBraceToken */, sourceFile);
  return openToken && closeToken && spanBetweenTokens(
    openToken,
    closeToken,
    node,
    sourceFile,
    /*autoCollapse*/
    node.kind !== 218 /* ArrowFunction */
  );
}
function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse = false, useFullStart = true) {
  const textSpan = createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
  return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
function createOutliningSpan(textSpan, kind, hintSpan = textSpan, autoCollapse = false, bannerText = "...") {
  return { textSpan, kind, hintSpan, bannerText, autoCollapse };
}
function tryGetFunctionOpenToken(node, body, sourceFile) {
  if (isNodeArrayMultiLine(node.parameters, sourceFile)) {
    const openParenToken = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile);
    if (openParenToken) {
      return openParenToken;
    }
  }
  return findChildOfKind(body, 19 /* OpenBraceToken */, sourceFile);
}

// src/services/_namespaces/ts.Rename.ts
var ts_Rename_exports = {};
__export(ts_Rename_exports, {
  getRenameInfo: () => getRenameInfo,
  nodeIsEligibleForRename: () => nodeIsEligibleForRename
});

// src/services/rename.ts
function getRenameInfo(program, sourceFile, position, preferences) {
  const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position));
  if (nodeIsEligibleForRename(node)) {
    const renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences);
    if (renameInfo) {
      return renameInfo;
    }
  }
  return getRenameInfoError(Diagnostics.You_cannot_rename_this_element);
}
function getRenameInfoForNode(node, typeChecker, sourceFile, program, preferences) {
  const symbol = typeChecker.getSymbolAtLocation(node);
  if (!symbol) {
    if (isStringLiteralLike(node)) {
      const type = getContextualTypeFromParentOrAncestorTypeNode(node, typeChecker);
      if (type && (type.flags & 128 /* StringLiteral */ || type.flags & 1048576 /* Union */ && every(type.types, (type2) => !!(type2.flags & 128 /* StringLiteral */)))) {
        return getRenameInfoSuccess(node.text, node.text, "string" /* string */, "", node, sourceFile);
      }
    } else if (isLabelName(node)) {
      const name = getTextOfNode(node);
      return getRenameInfoSuccess(name, name, "label" /* label */, "" /* none */, node, sourceFile);
    }
    return void 0;
  }
  const { declarations } = symbol;
  if (!declarations || declarations.length === 0)
    return;
  if (declarations.some((declaration) => isDefinedInLibraryFile(program, declaration))) {
    return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
  }
  if (isIdentifier(node) && node.escapedText === "default" && symbol.parent && symbol.parent.flags & 1536 /* Module */) {
    return void 0;
  }
  if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) {
    return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : void 0;
  }
  const wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences);
  if (wouldRenameNodeModules) {
    return getRenameInfoError(wouldRenameNodeModules);
  }
  const kind = ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, node);
  const specifierName = isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === 166 /* ComputedPropertyName */ ? stripQuotes(getTextOfIdentifierOrLiteral(node)) : void 0;
  const displayName = specifierName || typeChecker.symbolToString(symbol);
  const fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
  return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), node, sourceFile);
}
function isDefinedInLibraryFile(program, declaration) {
  const sourceFile = declaration.getSourceFile();
  return program.isSourceFileDefaultLibrary(sourceFile) && fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */);
}
function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) {
  if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* Alias */) {
    const importSpecifier = symbol.declarations && find(symbol.declarations, (decl) => isImportSpecifier(decl));
    if (importSpecifier && !importSpecifier.propertyName) {
      symbol = checker.getAliasedSymbol(symbol);
    }
  }
  const { declarations } = symbol;
  if (!declarations) {
    return void 0;
  }
  const originalPackage = getPackagePathComponents(originalFile.path);
  if (originalPackage === void 0) {
    if (some(declarations, (declaration) => isInsideNodeModules(declaration.getSourceFile().path))) {
      return Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder;
    } else {
      return void 0;
    }
  }
  for (const declaration of declarations) {
    const declPackage = getPackagePathComponents(declaration.getSourceFile().path);
    if (declPackage) {
      const length2 = Math.min(originalPackage.length, declPackage.length);
      for (let i = 0; i <= length2; i++) {
        if (compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== 0 /* EqualTo */) {
          return Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder;
        }
      }
    }
  }
  return void 0;
}
function getPackagePathComponents(filePath) {
  const components = getPathComponents(filePath);
  const nodeModulesIdx = components.lastIndexOf("node_modules");
  if (nodeModulesIdx === -1) {
    return void 0;
  }
  return components.slice(0, nodeModulesIdx + 2);
}
function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
  if (!isExternalModuleNameRelative(node.text)) {
    return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import);
  }
  const moduleSourceFile = moduleSymbol.declarations && find(moduleSymbol.declarations, isSourceFile);
  if (!moduleSourceFile)
    return void 0;
  const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? void 0 : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index");
  const name = withoutIndex === void 0 ? moduleSourceFile.fileName : withoutIndex;
  const kind = withoutIndex === void 0 ? "module" /* moduleElement */ : "directory" /* directory */;
  const indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
  const triggerSpan = createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
  return {
    canRename: true,
    fileToRename: name,
    kind,
    displayName: name,
    fullDisplayName: name,
    kindModifiers: "" /* none */,
    triggerSpan
  };
}
function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
  return {
    canRename: true,
    fileToRename: void 0,
    kind,
    displayName,
    fullDisplayName,
    kindModifiers,
    triggerSpan: createTriggerSpanForNode(node, sourceFile)
  };
}
function getRenameInfoError(diagnostic) {
  return { canRename: false, localizedErrorMessage: getLocaleSpecificMessage(diagnostic) };
}
function createTriggerSpanForNode(node, sourceFile) {
  let start2 = node.getStart(sourceFile);
  let width = node.getWidth(sourceFile);
  if (isStringLiteralLike(node)) {
    start2 += 1;
    width -= 2;
  }
  return createTextSpan(start2, width);
}
function nodeIsEligibleForRename(node) {
  switch (node.kind) {
    case 80 /* Identifier */:
    case 81 /* PrivateIdentifier */:
    case 11 /* StringLiteral */:
    case 15 /* NoSubstitutionTemplateLiteral */:
    case 110 /* ThisKeyword */:
      return true;
    case 9 /* NumericLiteral */:
      return isLiteralNameOfPropertyDeclarationOrIndexAccess(node);
    default:
      return false;
  }
}

// src/services/_namespaces/ts.SignatureHelp.ts
var ts_SignatureHelp_exports = {};
__export(ts_SignatureHelp_exports, {
  getArgumentInfoForCompletions: () => getArgumentInfoForCompletions,
  getSignatureHelpItems: () => getSignatureHelpItems
});

// src/services/signatureHelp.ts
function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
  const typeChecker = program.getTypeChecker();
  const startingToken = findTokenOnLeftOfPosition(sourceFile, position);
  if (!startingToken) {
    return void 0;
  }
  const onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped";
  if (onlyUseSyntacticOwners && (isInString(sourceFile, position, startingToken) || isInComment(sourceFile, position))) {
    return void 0;
  }
  const isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked";
  const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked);
  if (!argumentInfo)
    return void 0;
  cancellationToken.throwIfCancellationRequested();
  const candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
  cancellationToken.throwIfCancellationRequested();
  if (!candidateInfo) {
    return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : void 0;
  }
  return typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => candidateInfo.kind === 0 /* Candidate */ ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker2) : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker2));
}
function getCandidateOrTypeInfo({ invocation, argumentCount }, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
  switch (invocation.kind) {
    case 0 /* Call */: {
      if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) {
        return void 0;
      }
      const candidates = [];
      const resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount);
      return candidates.length === 0 ? void 0 : { kind: 0 /* Candidate */, candidates, resolvedSignature };
    }
    case 1 /* TypeArgs */: {
      const { called } = invocation;
      if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, isIdentifier(called) ? called.parent : called)) {
        return void 0;
      }
      const candidates = getPossibleGenericSignatures(called, argumentCount, checker);
      if (candidates.length !== 0)
        return { kind: 0 /* Candidate */, candidates, resolvedSignature: first(candidates) };
      const symbol = checker.getSymbolAtLocation(called);
      return symbol && { kind: 1 /* Type */, symbol };
    }
    case 2 /* Contextual */:
      return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
    default:
      return Debug.assertNever(invocation);
  }
}
function isSyntacticOwner(startingToken, node, sourceFile) {
  if (!isCallOrNewExpression(node))
    return false;
  const invocationChildren = node.getChildren(sourceFile);
  switch (startingToken.kind) {
    case 21 /* OpenParenToken */:
      return contains(invocationChildren, startingToken);
    case 28 /* CommaToken */: {
      const containingList = findContainingList(startingToken);
      return !!containingList && contains(invocationChildren, containingList);
    }
    case 30 /* LessThanToken */:
      return containsPrecedingToken(startingToken, sourceFile, node.expression);
    default:
      return false;
  }
}
function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) {
  if (argumentInfo.invocation.kind === 2 /* Contextual */)
    return void 0;
  const expression = getExpressionFromInvocation(argumentInfo.invocation);
  const name = isPropertyAccessExpression(expression) ? expression.name.text : void 0;
  const typeChecker = program.getTypeChecker();
  return name === void 0 ? void 0 : firstDefined(program.getSourceFiles(), (sourceFile) => firstDefined(sourceFile.getNamedDeclarations().get(name), (declaration) => {
    const type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration);
    const callSignatures = type && type.getCallSignatures();
    if (callSignatures && callSignatures.length) {
      return typeChecker.runWithCancellationToken(
        cancellationToken,
        (typeChecker2) => createSignatureHelpItems(
          callSignatures,
          callSignatures[0],
          argumentInfo,
          sourceFile,
          typeChecker2,
          /*useFullPrefix*/
          true
        )
      );
    }
  }));
}
function containsPrecedingToken(startingToken, sourceFile, container) {
  const pos = startingToken.getFullStart();
  let currentParent = startingToken.parent;
  while (currentParent) {
    const precedingToken = findPrecedingToken(
      pos,
      sourceFile,
      currentParent,
      /*excludeJsdoc*/
      true
    );
    if (precedingToken) {
      return rangeContainsRange(container, precedingToken);
    }
    currentParent = currentParent.parent;
  }
  return Debug.fail("Could not find preceding token");
}
function getArgumentInfoForCompletions(node, position, sourceFile) {
  const info = getImmediatelyContainingArgumentInfo(node, position, sourceFile);
  return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? void 0 : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex };
}
function getArgumentOrParameterListInfo(node, position, sourceFile) {
  const info = getArgumentOrParameterListAndIndex(node, sourceFile);
  if (!info)
    return void 0;
  const { list, argumentIndex } = info;
  const argumentCount = getArgumentCount(
    list,
    /*ignoreTrailingComma*/
    isInString(sourceFile, position, node)
  );
  if (argumentIndex !== 0) {
    Debug.assertLessThan(argumentIndex, argumentCount);
  }
  const argumentsSpan = getApplicableSpanForArguments(list, sourceFile);
  return { list, argumentIndex, argumentCount, argumentsSpan };
}
function getArgumentOrParameterListAndIndex(node, sourceFile) {
  if (node.kind === 30 /* LessThanToken */ || node.kind === 21 /* OpenParenToken */) {
    return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 };
  } else {
    const list = findContainingList(node);
    return list && { list, argumentIndex: getArgumentIndex(list, node) };
  }
}
function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
  const { parent: parent2 } = node;
  if (isCallOrNewExpression(parent2)) {
    const invocation = parent2;
    const info = getArgumentOrParameterListInfo(node, position, sourceFile);
    if (!info)
      return void 0;
    const { list, argumentIndex, argumentCount, argumentsSpan } = info;
    const isTypeParameterList = !!parent2.typeArguments && parent2.typeArguments.pos === list.pos;
    return { isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan, argumentIndex, argumentCount };
  } else if (isNoSubstitutionTemplateLiteral(node) && isTaggedTemplateExpression(parent2)) {
    if (isInsideTemplateLiteral(node, position, sourceFile)) {
      return getArgumentListInfoForTemplate(
        parent2,
        /*argumentIndex*/
        0,
        sourceFile
      );
    }
    return void 0;
  } else if (isTemplateHead(node) && parent2.parent.kind === 214 /* TaggedTemplateExpression */) {
    const templateExpression = parent2;
    const tagExpression = templateExpression.parent;
    Debug.assert(templateExpression.kind === 227 /* TemplateExpression */);
    const argumentIndex = isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
    return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
  } else if (isTemplateSpan(parent2) && isTaggedTemplateExpression(parent2.parent.parent)) {
    const templateSpan = parent2;
    const tagExpression = parent2.parent.parent;
    if (isTemplateTail(node) && !isInsideTemplateLiteral(node, position, sourceFile)) {
      return void 0;
    }
    const spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan);
    const argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile);
    return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
  } else if (isJsxOpeningLikeElement(parent2)) {
    const attributeSpanStart = parent2.attributes.pos;
    const attributeSpanEnd = skipTrivia(
      sourceFile.text,
      parent2.attributes.end,
      /*stopAfterLineBreak*/
      false
    );
    return {
      isTypeParameterList: false,
      invocation: { kind: 0 /* Call */, node: parent2 },
      argumentsSpan: createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
      argumentIndex: 0,
      argumentCount: 1
    };
  } else {
    const typeArgInfo = getPossibleTypeArgumentsInfo(node, sourceFile);
    if (typeArgInfo) {
      const { called, nTypeArguments } = typeArgInfo;
      const invocation = { kind: 1 /* TypeArgs */, called };
      const argumentsSpan = createTextSpanFromBounds(called.getStart(sourceFile), node.end);
      return { isTypeParameterList: true, invocation, argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 };
    }
    return void 0;
  }
}
function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) {
  return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile);
}
function getHighestBinary(b) {
  return isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b;
}
function countBinaryExpressionParameters(b) {
  return isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2;
}
function tryGetParameterInfo(startingToken, position, sourceFile, checker) {
  const node = getAdjustedNode(startingToken);
  if (node === void 0)
    return void 0;
  const info = getContextualSignatureLocationInfo(node, sourceFile, position, checker);
  if (info === void 0)
    return void 0;
  const { contextualType, argumentIndex, argumentCount, argumentsSpan } = info;
  const nonNullableContextualType = contextualType.getNonNullableType();
  const symbol = nonNullableContextualType.symbol;
  if (symbol === void 0)
    return void 0;
  const signature = lastOrUndefined(nonNullableContextualType.getCallSignatures());
  if (signature === void 0)
    return void 0;
  const invocation = { kind: 2 /* Contextual */, signature, node: startingToken, symbol: chooseBetterSymbol(symbol) };
  return { isTypeParameterList: false, invocation, argumentsSpan, argumentIndex, argumentCount };
}
function getAdjustedNode(node) {
  switch (node.kind) {
    case 21 /* OpenParenToken */:
    case 28 /* CommaToken */:
      return node;
    default:
      return findAncestor(node.parent, (n) => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit");
  }
}
function getContextualSignatureLocationInfo(node, sourceFile, position, checker) {
  const { parent: parent2 } = node;
  switch (parent2.kind) {
    case 216 /* ParenthesizedExpression */:
    case 173 /* MethodDeclaration */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
      const info = getArgumentOrParameterListInfo(node, position, sourceFile);
      if (!info)
        return void 0;
      const { argumentIndex, argumentCount, argumentsSpan } = info;
      const contextualType = isMethodDeclaration(parent2) ? checker.getContextualTypeForObjectLiteralElement(parent2) : checker.getContextualType(parent2);
      return contextualType && { contextualType, argumentIndex, argumentCount, argumentsSpan };
    case 225 /* BinaryExpression */: {
      const highestBinary = getHighestBinary(parent2);
      const contextualType2 = checker.getContextualType(highestBinary);
      const argumentIndex2 = node.kind === 21 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent2) - 1;
      const argumentCount2 = countBinaryExpressionParameters(highestBinary);
      return contextualType2 && { contextualType: contextualType2, argumentIndex: argumentIndex2, argumentCount: argumentCount2, argumentsSpan: createTextSpanFromNode(parent2) };
    }
    default:
      return void 0;
  }
}
function chooseBetterSymbol(s) {
  return s.name === "__type" /* Type */ ? firstDefined(s.declarations, (d) => {
    var _a;
    return isFunctionTypeNode(d) ? (_a = tryCast(d.parent, canHaveSymbol)) == null ? void 0 : _a.symbol : void 0;
  }) || s : s;
}
function getArgumentIndex(argumentsList, node) {
  let argumentIndex = 0;
  for (const child of argumentsList.getChildren()) {
    if (child === node) {
      break;
    }
    if (child.kind !== 28 /* CommaToken */) {
      argumentIndex++;
    }
  }
  return argumentIndex;
}
function getArgumentCount(argumentsList, ignoreTrailingComma) {
  const listChildren = argumentsList.getChildren();
  let argumentCount = countWhere(listChildren, (arg) => arg.kind !== 28 /* CommaToken */);
  if (!ignoreTrailingComma && listChildren.length > 0 && last(listChildren).kind === 28 /* CommaToken */) {
    argumentCount++;
  }
  return argumentCount;
}
function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) {
  Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node.");
  if (isTemplateLiteralToken(node)) {
    if (isInsideTemplateLiteral(node, position, sourceFile)) {
      return 0;
    }
    return spanIndex + 2;
  }
  return spanIndex + 1;
}
function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) {
  const argumentCount = isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
  if (argumentIndex !== 0) {
    Debug.assertLessThan(argumentIndex, argumentCount);
  }
  return {
    isTypeParameterList: false,
    invocation: { kind: 0 /* Call */, node: tagExpression },
    argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile),
    argumentIndex,
    argumentCount
  };
}
function getApplicableSpanForArguments(argumentsList, sourceFile) {
  const applicableSpanStart = argumentsList.getFullStart();
  const applicableSpanEnd = skipTrivia(
    sourceFile.text,
    argumentsList.getEnd(),
    /*stopAfterLineBreak*/
    false
  );
  return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) {
  const template = taggedTemplate.template;
  const applicableSpanStart = template.getStart();
  let applicableSpanEnd = template.getEnd();
  if (template.kind === 227 /* TemplateExpression */) {
    const lastSpan = last(template.templateSpans);
    if (lastSpan.literal.getFullWidth() === 0) {
      applicableSpanEnd = skipTrivia(
        sourceFile.text,
        applicableSpanEnd,
        /*stopAfterLineBreak*/
        false
      );
    }
  }
  return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
  for (let n = node; !isSourceFile(n) && (isManuallyInvoked || !isBlock(n)); n = n.parent) {
    Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.formatSyntaxKind(n.kind)}, parent: ${Debug.formatSyntaxKind(n.parent.kind)}`);
    const argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
    if (argumentInfo) {
      return argumentInfo;
    }
  }
  return void 0;
}
function getChildListThatStartsWithOpenerToken(parent2, openerToken, sourceFile) {
  const children = parent2.getChildren(sourceFile);
  const indexOfOpenerToken = children.indexOf(openerToken);
  Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
  return children[indexOfOpenerToken + 1];
}
function getExpressionFromInvocation(invocation) {
  return invocation.kind === 0 /* Call */ ? getInvokedExpression(invocation.node) : invocation.called;
}
function getEnclosingDeclarationFromInvocation(invocation) {
  return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
}
var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParameterList, argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, typeChecker, useFullPrefix) {
  var _a;
  const enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
  const callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)) || useFullPrefix && ((_a = resolvedSignature.declaration) == null ? void 0 : _a.symbol);
  const callTargetDisplayParts = callTargetSymbol ? symbolToDisplayParts(
    typeChecker,
    callTargetSymbol,
    useFullPrefix ? sourceFile : void 0,
    /*meaning*/
    void 0
  ) : emptyArray;
  const items = map(candidates, (candidateSignature) => getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile));
  if (argumentIndex !== 0) {
    Debug.assertLessThan(argumentIndex, argumentCount);
  }
  let selectedItemIndex = 0;
  let itemsSeen = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (candidates[i] === resolvedSignature) {
      selectedItemIndex = itemsSeen;
      if (item.length > 1) {
        let count = 0;
        for (const i2 of item) {
          if (i2.isVariadic || i2.parameters.length >= argumentCount) {
            selectedItemIndex = itemsSeen + count;
            break;
          }
          count++;
        }
      }
    }
    itemsSeen += item.length;
  }
  Debug.assert(selectedItemIndex !== -1);
  const help = { items: flatMapToMutable(items, identity), applicableSpan, selectedItemIndex, argumentIndex, argumentCount };
  const selected = help.items[selectedItemIndex];
  if (selected.isVariadic) {
    const firstRest = findIndex(selected.parameters, (p) => !!p.isRest);
    if (-1 < firstRest && firstRest < selected.parameters.length - 1) {
      help.argumentIndex = selected.parameters.length;
    } else {
      help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1);
    }
  }
  return help;
}
function createTypeHelpItems(symbol, { argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, checker) {
  const typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
  if (!typeParameters)
    return void 0;
  const items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
  return { items, applicableSpan, selectedItemIndex: 0, argumentIndex, argumentCount };
}
function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
  const typeSymbolDisplay = symbolToDisplayParts(checker, symbol);
  const printer = createPrinterWithRemoveComments();
  const parameters = typeParameters.map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer));
  const documentation = symbol.getDocumentationComment(checker);
  const tags = symbol.getJsDocTags(checker);
  const prefixDisplayParts = [...typeSymbolDisplay, punctuationPart(30 /* LessThanToken */)];
  return { isVariadic: false, prefixDisplayParts, suffixDisplayParts: [punctuationPart(32 /* GreaterThanToken */)], separatorDisplayParts, parameters, documentation, tags };
}
var separatorDisplayParts = [punctuationPart(28 /* CommaToken */), spacePart()];
function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
  const infos = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile);
  return map(infos, ({ isVariadic, parameters, prefix, suffix }) => {
    const prefixDisplayParts = [...callTargetDisplayParts, ...prefix];
    const suffixDisplayParts = [...suffix, ...returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)];
    const documentation = candidateSignature.getDocumentationComment(checker);
    const tags = candidateSignature.getJsDocTags();
    return { isVariadic, prefixDisplayParts, suffixDisplayParts, separatorDisplayParts, parameters, documentation, tags };
  });
}
function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) {
  return mapToDisplayParts((writer) => {
    writer.writePunctuation(":");
    writer.writeSpace(" ");
    const predicate = checker.getTypePredicateOfSignature(candidateSignature);
    if (predicate) {
      checker.writeTypePredicate(
        predicate,
        enclosingDeclaration,
        /*flags*/
        void 0,
        writer
      );
    } else {
      checker.writeType(
        checker.getReturnTypeOfSignature(candidateSignature),
        enclosingDeclaration,
        /*flags*/
        void 0,
        writer
      );
    }
  });
}
function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
  const typeParameters = (candidateSignature.target || candidateSignature).typeParameters;
  const printer = createPrinterWithRemoveComments();
  const parameters = (typeParameters || emptyArray).map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer));
  const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
  return checker.getExpandedParameters(candidateSignature).map((paramList) => {
    const params = factory.createNodeArray([...thisParameter, ...map(paramList, (param) => checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags))]);
    const parameterParts = mapToDisplayParts((writer) => {
      printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
    });
    return { isVariadic: false, parameters, prefix: [punctuationPart(30 /* LessThanToken */)], suffix: [punctuationPart(32 /* GreaterThanToken */), ...parameterParts] };
  });
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
  const printer = createPrinterWithRemoveComments();
  const typeParameterParts = mapToDisplayParts((writer) => {
    if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
      const args = factory.createNodeArray(candidateSignature.typeParameters.map((p) => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags)));
      printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
    }
  });
  const lists = checker.getExpandedParameters(candidateSignature);
  const isVariadic = !checker.hasEffectiveRestParameter(candidateSignature) ? (_) => false : lists.length === 1 ? (_) => true : (pList) => {
    var _a;
    return !!(pList.length && ((_a = tryCast(pList[pList.length - 1], isTransientSymbol)) == null ? void 0 : _a.links.checkFlags) & 32768 /* RestParameter */);
  };
  return lists.map((parameterList) => ({
    isVariadic: isVariadic(parameterList),
    parameters: parameterList.map((p) => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)),
    prefix: [...typeParameterParts, punctuationPart(21 /* OpenParenToken */)],
    suffix: [punctuationPart(22 /* CloseParenToken */)]
  }));
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
  const displayParts = mapToDisplayParts((writer) => {
    const param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
    printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
  });
  const isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
  const isRest = isTransientSymbol(parameter) && !!(parameter.links.checkFlags & 32768 /* RestParameter */);
  return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts, isOptional, isRest };
}
function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
  const displayParts = mapToDisplayParts((writer) => {
    const param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
    printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
  });
  return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts, isOptional: false, isRest: false };
}

// src/services/_namespaces/ts.SmartSelectionRange.ts
var ts_SmartSelectionRange_exports = {};
__export(ts_SmartSelectionRange_exports, {
  getSmartSelectionRange: () => getSmartSelectionRange
});

// src/services/smartSelection.ts
function getSmartSelectionRange(pos, sourceFile) {
  var _a, _b;
  let selectionRange = {
    textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd())
  };
  let parentNode = sourceFile;
  outer:
    while (true) {
      const children = getSelectionChildren(parentNode);
      if (!children.length)
        break;
      for (let i = 0; i < children.length; i++) {
        const prevNode = children[i - 1];
        const node = children[i];
        const nextNode = children[i + 1];
        if (getTokenPosOfNode(
          node,
          sourceFile,
          /*includeJsDoc*/
          true
        ) > pos) {
          break outer;
        }
        const comment = singleOrUndefined(getTrailingCommentRanges(sourceFile.text, node.end));
        if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) {
          pushSelectionCommentRange(comment.pos, comment.end);
        }
        if (positionShouldSnapToNode(sourceFile, pos, node)) {
          if (isFunctionBody(node) && isFunctionLikeDeclaration(parentNode) && !positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile)) {
            pushSelectionRange(node.getStart(sourceFile), node.getEnd());
          }
          if (isBlock(node) || isTemplateSpan(node) || isTemplateHead(node) || isTemplateTail(node) || prevNode && isTemplateHead(prevNode) || isVariableDeclarationList(node) && isVariableStatement(parentNode) || isSyntaxList(node) && isVariableDeclarationList(parentNode) || isVariableDeclaration(node) && isSyntaxList(parentNode) && children.length === 1 || isJSDocTypeExpression(node) || isJSDocSignature(node) || isJSDocTypeLiteral(node)) {
            parentNode = node;
            break;
          }
          if (isTemplateSpan(parentNode) && nextNode && isTemplateMiddleOrTemplateTail(nextNode)) {
            const start3 = node.getFullStart() - "${".length;
            const end2 = nextNode.getStart() + "}".length;
            pushSelectionRange(start3, end2);
          }
          const isBetweenMultiLineBookends = isSyntaxList(node) && isListOpener(prevNode) && isListCloser(nextNode) && !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
          let start2 = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
          const end = isBetweenMultiLineBookends ? nextNode.getStart() : getEndPos(sourceFile, node);
          if (hasJSDocNodes(node) && ((_a = node.jsDoc) == null ? void 0 : _a.length)) {
            pushSelectionRange(first(node.jsDoc).getStart(), end);
          }
          if (isSyntaxList(node)) {
            const firstChild = node.getChildren()[0];
            if (firstChild && hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) == null ? void 0 : _b.length) && firstChild.getStart() !== node.pos) {
              start2 = Math.min(start2, first(firstChild.jsDoc).getStart());
            }
          }
          pushSelectionRange(start2, end);
          if (isStringLiteral(node) || isTemplateLiteral(node)) {
            pushSelectionRange(start2 + 1, end - 1);
          }
          parentNode = node;
          break;
        }
        if (i === children.length - 1) {
          break outer;
        }
      }
    }
  return selectionRange;
  function pushSelectionRange(start2, end) {
    if (start2 !== end) {
      const textSpan = createTextSpanFromBounds(start2, end);
      if (!selectionRange || // Skip ranges that are identical to the parent
      !textSpansEqual(textSpan, selectionRange.textSpan) && // Skip ranges that don't contain the original position
      textSpanIntersectsWithPosition(textSpan, pos)) {
        selectionRange = { textSpan, ...selectionRange && { parent: selectionRange } };
      }
    }
  }
  function pushSelectionCommentRange(start2, end) {
    pushSelectionRange(start2, end);
    let pos2 = start2;
    while (sourceFile.text.charCodeAt(pos2) === 47 /* slash */) {
      pos2++;
    }
    pushSelectionRange(pos2, end);
  }
}
function positionShouldSnapToNode(sourceFile, pos, node) {
  Debug.assert(node.pos <= pos);
  if (pos < node.end) {
    return true;
  }
  const nodeEnd = node.getEnd();
  if (nodeEnd === pos) {
    return getTouchingPropertyName(sourceFile, pos).pos < node.end;
  }
  return false;
}
var isImport2 = or(isImportDeclaration, isImportEqualsDeclaration);
function getSelectionChildren(node) {
  var _a;
  if (isSourceFile(node)) {
    return groupChildren(node.getChildAt(0).getChildren(), isImport2);
  }
  if (isMappedTypeNode(node)) {
    const [openBraceToken, ...children] = node.getChildren();
    const closeBraceToken = Debug.checkDefined(children.pop());
    Debug.assertEqual(openBraceToken.kind, 19 /* OpenBraceToken */);
    Debug.assertEqual(closeBraceToken.kind, 20 /* CloseBraceToken */);
    const groupedWithPlusMinusTokens = groupChildren(children, (child) => child === node.readonlyToken || child.kind === 148 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 58 /* QuestionToken */);
    const groupedWithBrackets = groupChildren(
      groupedWithPlusMinusTokens,
      ({ kind }) => kind === 23 /* OpenBracketToken */ || kind === 167 /* TypeParameter */ || kind === 24 /* CloseBracketToken */
    );
    return [
      openBraceToken,
      // Pivot on `:`
      createSyntaxList2(splitChildren(groupedWithBrackets, ({ kind }) => kind === 59 /* ColonToken */)),
      closeBraceToken
    ];
  }
  if (isPropertySignature(node)) {
    const children = groupChildren(node.getChildren(), (child) => child === node.name || contains(node.modifiers, child));
    const firstJSDocChild = ((_a = children[0]) == null ? void 0 : _a.kind) === 326 /* JSDoc */ ? children[0] : void 0;
    const withJSDocSeparated = firstJSDocChild ? children.slice(1) : children;
    const splittedChildren = splitChildren(withJSDocSeparated, ({ kind }) => kind === 59 /* ColonToken */);
    return firstJSDocChild ? [firstJSDocChild, createSyntaxList2(splittedChildren)] : splittedChildren;
  }
  if (isParameter(node)) {
    const groupedDotDotDotAndName = groupChildren(node.getChildren(), (child) => child === node.dotDotDotToken || child === node.name);
    const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, (child) => child === groupedDotDotDotAndName[0] || child === node.questionToken);
    return splitChildren(groupedWithQuestionToken, ({ kind }) => kind === 64 /* EqualsToken */);
  }
  if (isBindingElement(node)) {
    return splitChildren(node.getChildren(), ({ kind }) => kind === 64 /* EqualsToken */);
  }
  return node.getChildren();
}
function groupChildren(children, groupOn) {
  const result = [];
  let group2;
  for (const child of children) {
    if (groupOn(child)) {
      group2 = group2 || [];
      group2.push(child);
    } else {
      if (group2) {
        result.push(createSyntaxList2(group2));
        group2 = void 0;
      }
      result.push(child);
    }
  }
  if (group2) {
    result.push(createSyntaxList2(group2));
  }
  return result;
}
function splitChildren(children, pivotOn, separateTrailingSemicolon = true) {
  if (children.length < 2) {
    return children;
  }
  const splitTokenIndex = findIndex(children, pivotOn);
  if (splitTokenIndex === -1) {
    return children;
  }
  const leftChildren = children.slice(0, splitTokenIndex);
  const splitToken = children[splitTokenIndex];
  const lastToken = last(children);
  const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27 /* SemicolonToken */;
  const rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : void 0);
  const result = compact([
    leftChildren.length ? createSyntaxList2(leftChildren) : void 0,
    splitToken,
    rightChildren.length ? createSyntaxList2(rightChildren) : void 0
  ]);
  return separateLastToken ? result.concat(lastToken) : result;
}
function createSyntaxList2(children) {
  Debug.assertGreaterThanOrEqual(children.length, 1);
  return setTextRangePosEnd(parseNodeFactory.createSyntaxList(children), children[0].pos, last(children).end);
}
function isListOpener(token) {
  const kind = token && token.kind;
  return kind === 19 /* OpenBraceToken */ || kind === 23 /* OpenBracketToken */ || kind === 21 /* OpenParenToken */ || kind === 285 /* JsxOpeningElement */;
}
function isListCloser(token) {
  const kind = token && token.kind;
  return kind === 20 /* CloseBraceToken */ || kind === 24 /* CloseBracketToken */ || kind === 22 /* CloseParenToken */ || kind === 286 /* JsxClosingElement */;
}
function getEndPos(sourceFile, node) {
  switch (node.kind) {
    case 347 /* JSDocParameterTag */:
    case 344 /* JSDocCallbackTag */:
    case 354 /* JSDocPropertyTag */:
    case 352 /* JSDocTypedefTag */:
    case 349 /* JSDocThisTag */:
      return sourceFile.getLineEndOfPosition(node.getStart());
    default:
      return node.getEnd();
  }
}

// src/services/_namespaces/ts.SymbolDisplay.ts
var ts_SymbolDisplay_exports = {};
__export(ts_SymbolDisplay_exports, {
  getSymbolDisplayPartsDocumentationAndSymbolKind: () => getSymbolDisplayPartsDocumentationAndSymbolKind,
  getSymbolKind: () => getSymbolKind,
  getSymbolModifiers: () => getSymbolModifiers
});

// src/services/symbolDisplay.ts
var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
function getSymbolKind(typeChecker, symbol, location) {
  const result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
  if (result !== "" /* unknown */) {
    return result;
  }
  const flags = getCombinedLocalAndExportSymbolFlags(symbol);
  if (flags & 32 /* Class */) {
    return getDeclarationOfKind(symbol, 230 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */;
  }
  if (flags & 384 /* Enum */)
    return "enum" /* enumElement */;
  if (flags & 524288 /* TypeAlias */)
    return "type" /* typeElement */;
  if (flags & 64 /* Interface */)
    return "interface" /* interfaceElement */;
  if (flags & 262144 /* TypeParameter */)
    return "type parameter" /* typeParameterElement */;
  if (flags & 8 /* EnumMember */)
    return "enum member" /* enumMemberElement */;
  if (flags & 2097152 /* Alias */)
    return "alias" /* alias */;
  if (flags & 1536 /* Module */)
    return "module" /* moduleElement */;
  return result;
}
function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
  const roots = typeChecker.getRootSymbols(symbol);
  if (roots.length === 1 && first(roots).flags & 8192 /* Method */ && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) {
    return "method" /* memberFunctionElement */;
  }
  if (typeChecker.isUndefinedSymbol(symbol)) {
    return "var" /* variableElement */;
  }
  if (typeChecker.isArgumentsSymbol(symbol)) {
    return "local var" /* localVariableElement */;
  }
  if (location.kind === 110 /* ThisKeyword */ && isExpression(location) || isThisInTypeQuery(location)) {
    return "parameter" /* parameterElement */;
  }
  const flags = getCombinedLocalAndExportSymbolFlags(symbol);
  if (flags & 3 /* Variable */) {
    if (isFirstDeclarationOfSymbolParameter(symbol)) {
      return "parameter" /* parameterElement */;
    } else if (symbol.valueDeclaration && isVarConst(symbol.valueDeclaration)) {
      return "const" /* constElement */;
    } else if (forEach(symbol.declarations, isLet)) {
      return "let" /* letElement */;
    }
    return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */;
  }
  if (flags & 16 /* Function */)
    return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */;
  if (flags & 32768 /* GetAccessor */)
    return "getter" /* memberGetAccessorElement */;
  if (flags & 65536 /* SetAccessor */)
    return "setter" /* memberSetAccessorElement */;
  if (flags & 8192 /* Method */)
    return "method" /* memberFunctionElement */;
  if (flags & 16384 /* Constructor */)
    return "constructor" /* constructorImplementationElement */;
  if (flags & 131072 /* Signature */)
    return "index" /* indexSignatureElement */;
  if (flags & 4 /* Property */) {
    if (flags & 33554432 /* Transient */ && symbol.links.checkFlags & 6 /* Synthetic */) {
      const unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), (rootSymbol) => {
        const rootSymbolFlags = rootSymbol.getFlags();
        if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
          return "property" /* memberVariableElement */;
        }
      });
      if (!unionPropertyKind) {
        const typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
        if (typeOfUnionProperty.getCallSignatures().length) {
          return "method" /* memberFunctionElement */;
        }
        return "property" /* memberVariableElement */;
      }
      return unionPropertyKind;
    }
    return "property" /* memberVariableElement */;
  }
  return "" /* unknown */;
}
function getNormalizedSymbolModifiers(symbol) {
  if (symbol.declarations && symbol.declarations.length) {
    const [declaration, ...declarations] = symbol.declarations;
    const excludeFlags = length(declarations) && isDeprecatedDeclaration(declaration) && some(declarations, (d) => !isDeprecatedDeclaration(d)) ? 8192 /* Deprecated */ : 0 /* None */;
    const modifiers = getNodeModifiers(declaration, excludeFlags);
    if (modifiers) {
      return modifiers.split(",");
    }
  }
  return [];
}
function getSymbolModifiers(typeChecker, symbol) {
  if (!symbol) {
    return "" /* none */;
  }
  const modifiers = new Set(getNormalizedSymbolModifiers(symbol));
  if (symbol.flags & 2097152 /* Alias */) {
    const resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
    if (resolvedSymbol !== symbol) {
      forEach(getNormalizedSymbolModifiers(resolvedSymbol), (modifier) => {
        modifiers.add(modifier);
      });
    }
  }
  if (symbol.flags & 16777216 /* Optional */) {
    modifiers.add("optional" /* optionalModifier */);
  }
  return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */;
}
function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) {
  var _a;
  const displayParts = [];
  let documentation = [];
  let tags = [];
  const symbolFlags = getCombinedLocalAndExportSymbolFlags(symbol);
  let symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
  let hasAddedSymbolInfo = false;
  const isThisExpression = location.kind === 110 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location);
  let type;
  let documentationFromAlias;
  let tagsFromAlias;
  let hasMultipleSignatures = false;
  if (location.kind === 110 /* ThisKeyword */ && !isThisExpression) {
    return { displayParts: [keywordPart(110 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: void 0 };
  }
  if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
    if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) {
      const declaration = find(symbol.declarations, (declaration2) => declaration2.name === location);
      if (declaration) {
        switch (declaration.kind) {
          case 176 /* GetAccessor */:
            symbolKind = "getter" /* memberGetAccessorElement */;
            break;
          case 177 /* SetAccessor */:
            symbolKind = "setter" /* memberSetAccessorElement */;
            break;
          case 171 /* PropertyDeclaration */:
            symbolKind = "accessor" /* memberAccessorVariableElement */;
            break;
          default:
            Debug.assertNever(declaration);
        }
      } else {
        symbolKind = "property" /* memberVariableElement */;
      }
    }
    let signature;
    type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location);
    if (location.parent && location.parent.kind === 210 /* PropertyAccessExpression */) {
      const right = location.parent.name;
      if (right === location || right && right.getFullWidth() === 0) {
        location = location.parent;
      }
    }
    let callExpressionLike;
    if (isCallOrNewExpression(location)) {
      callExpressionLike = location;
    } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) {
      callExpressionLike = location.parent;
    } else if (location.parent && (isJsxOpeningLikeElement(location.parent) || isTaggedTemplateExpression(location.parent)) && isFunctionLike(symbol.valueDeclaration)) {
      callExpressionLike = location.parent;
    }
    if (callExpressionLike) {
      signature = typeChecker.getResolvedSignature(callExpressionLike);
      const useConstructSignatures = callExpressionLike.kind === 213 /* NewExpression */ || isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 108 /* SuperKeyword */;
      const allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
      if (signature && !contains(allSignatures, signature.target) && !contains(allSignatures, signature)) {
        signature = allSignatures.length ? allSignatures[0] : void 0;
      }
      if (signature) {
        if (useConstructSignatures && symbolFlags & 32 /* Class */) {
          symbolKind = "constructor" /* constructorImplementationElement */;
          addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
        } else if (symbolFlags & 2097152 /* Alias */) {
          symbolKind = "alias" /* alias */;
          pushSymbolKind(symbolKind);
          displayParts.push(spacePart());
          if (useConstructSignatures) {
            if (signature.flags & 4 /* Abstract */) {
              displayParts.push(keywordPart(128 /* AbstractKeyword */));
              displayParts.push(spacePart());
            }
            displayParts.push(keywordPart(105 /* NewKeyword */));
            displayParts.push(spacePart());
          }
          addFullSymbolName(symbol);
        } else {
          addPrefixForAnyFunctionOrVar(symbol, symbolKind);
        }
        switch (symbolKind) {
          case "JSX attribute" /* jsxAttribute */:
          case "property" /* memberVariableElement */:
          case "var" /* variableElement */:
          case "const" /* constElement */:
          case "let" /* letElement */:
          case "parameter" /* parameterElement */:
          case "local var" /* localVariableElement */:
            displayParts.push(punctuationPart(59 /* ColonToken */));
            displayParts.push(spacePart());
            if (!(getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) {
              addRange(displayParts, symbolToDisplayParts(
                typeChecker,
                type.symbol,
                enclosingDeclaration,
                /*meaning*/
                void 0,
                4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */
              ));
              displayParts.push(lineBreakPart());
            }
            if (useConstructSignatures) {
              if (signature.flags & 4 /* Abstract */) {
                displayParts.push(keywordPart(128 /* AbstractKeyword */));
                displayParts.push(spacePart());
              }
              displayParts.push(keywordPart(105 /* NewKeyword */));
              displayParts.push(spacePart());
            }
            addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */);
            break;
          default:
            addSignatureDisplayParts(signature, allSignatures);
        }
        hasAddedSymbolInfo = true;
        hasMultipleSignatures = allSignatures.length > 1;
      }
    } else if (isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */) || // name of function declaration
    location.kind === 137 /* ConstructorKeyword */ && location.parent.kind === 175 /* Constructor */) {
      const functionDeclaration = location.parent;
      const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, (declaration) => declaration === (location.kind === 137 /* ConstructorKeyword */ ? functionDeclaration.parent : functionDeclaration));
      if (locationIsSymbolDeclaration) {
        const allSignatures = functionDeclaration.kind === 175 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
        if (!typeChecker.isImplementationOfOverload(functionDeclaration)) {
          signature = typeChecker.getSignatureFromDeclaration(functionDeclaration);
        } else {
          signature = allSignatures[0];
        }
        if (functionDeclaration.kind === 175 /* Constructor */) {
          symbolKind = "constructor" /* constructorImplementationElement */;
          addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
        } else {
          addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 178 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind);
        }
        if (signature) {
          addSignatureDisplayParts(signature, allSignatures);
        }
        hasAddedSymbolInfo = true;
        hasMultipleSignatures = allSignatures.length > 1;
      }
    }
  }
  if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
    addAliasPrefixIfNecessary();
    if (getDeclarationOfKind(symbol, 230 /* ClassExpression */)) {
      pushSymbolKind("local class" /* localClassElement */);
    } else {
      displayParts.push(keywordPart(86 /* ClassKeyword */));
    }
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    writeTypeParametersOfSymbol(symbol, sourceFile);
  }
  if (symbolFlags & 64 /* Interface */ && semanticMeaning & 2 /* Type */) {
    prefixNextMeaning();
    displayParts.push(keywordPart(120 /* InterfaceKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    writeTypeParametersOfSymbol(symbol, sourceFile);
  }
  if (symbolFlags & 524288 /* TypeAlias */ && semanticMeaning & 2 /* Type */) {
    prefixNextMeaning();
    displayParts.push(keywordPart(156 /* TypeKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    writeTypeParametersOfSymbol(symbol, sourceFile);
    displayParts.push(spacePart());
    displayParts.push(operatorPart(64 /* EqualsToken */));
    displayParts.push(spacePart());
    addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */));
  }
  if (symbolFlags & 384 /* Enum */) {
    prefixNextMeaning();
    if (some(symbol.declarations, (d) => isEnumDeclaration(d) && isEnumConst(d))) {
      displayParts.push(keywordPart(87 /* ConstKeyword */));
      displayParts.push(spacePart());
    }
    displayParts.push(keywordPart(94 /* EnumKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
  }
  if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
    prefixNextMeaning();
    const declaration = getDeclarationOfKind(symbol, 266 /* ModuleDeclaration */);
    const isNamespace = declaration && declaration.name && declaration.name.kind === 80 /* Identifier */;
    displayParts.push(keywordPart(isNamespace ? 145 /* NamespaceKeyword */ : 144 /* ModuleKeyword */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
  }
  if (symbolFlags & 262144 /* TypeParameter */ && semanticMeaning & 2 /* Type */) {
    prefixNextMeaning();
    displayParts.push(punctuationPart(21 /* OpenParenToken */));
    displayParts.push(textPart("type parameter"));
    displayParts.push(punctuationPart(22 /* CloseParenToken */));
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    if (symbol.parent) {
      addInPrefix();
      addFullSymbolName(symbol.parent, enclosingDeclaration);
      writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
    } else {
      const decl = getDeclarationOfKind(symbol, 167 /* TypeParameter */);
      if (decl === void 0)
        return Debug.fail();
      const declaration = decl.parent;
      if (declaration) {
        if (isFunctionLike(declaration)) {
          addInPrefix();
          const signature = typeChecker.getSignatureFromDeclaration(declaration);
          if (declaration.kind === 179 /* ConstructSignature */) {
            displayParts.push(keywordPart(105 /* NewKeyword */));
            displayParts.push(spacePart());
          } else if (declaration.kind !== 178 /* CallSignature */ && declaration.name) {
            addFullSymbolName(declaration.symbol);
          }
          addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
        } else if (isTypeAliasDeclaration(declaration)) {
          addInPrefix();
          displayParts.push(keywordPart(156 /* TypeKeyword */));
          displayParts.push(spacePart());
          addFullSymbolName(declaration.symbol);
          writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
        }
      }
    }
  }
  if (symbolFlags & 8 /* EnumMember */) {
    symbolKind = "enum member" /* enumMemberElement */;
    addPrefixForAnyFunctionOrVar(symbol, "enum member");
    const declaration = (_a = symbol.declarations) == null ? void 0 : _a[0];
    if ((declaration == null ? void 0 : declaration.kind) === 305 /* EnumMember */) {
      const constantValue = typeChecker.getConstantValue(declaration);
      if (constantValue !== void 0) {
        displayParts.push(spacePart());
        displayParts.push(operatorPart(64 /* EqualsToken */));
        displayParts.push(spacePart());
        displayParts.push(displayPart(
          getTextOfConstantValue(constantValue),
          typeof constantValue === "number" ? 7 /* numericLiteral */ : 8 /* stringLiteral */
        ));
      }
    }
  }
  if (symbol.flags & 2097152 /* Alias */) {
    prefixNextMeaning();
    if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) {
      const resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
      if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) {
        const resolvedNode = resolvedSymbol.declarations[0];
        const declarationName = getNameOfDeclaration(resolvedNode);
        if (declarationName && !hasAddedSymbolInfo) {
          const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */);
          const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration;
          const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(
            typeChecker,
            resolvedSymbol,
            getSourceFileOfNode(resolvedNode),
            resolvedNode,
            declarationName,
            semanticMeaning,
            shouldUseAliasName ? symbol : resolvedSymbol
          );
          displayParts.push(...resolvedInfo.displayParts);
          displayParts.push(lineBreakPart());
          documentationFromAlias = resolvedInfo.documentation;
          tagsFromAlias = resolvedInfo.tags;
        } else {
          documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker);
          tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker);
        }
      }
    }
    if (symbol.declarations) {
      switch (symbol.declarations[0].kind) {
        case 269 /* NamespaceExportDeclaration */:
          displayParts.push(keywordPart(95 /* ExportKeyword */));
          displayParts.push(spacePart());
          displayParts.push(keywordPart(145 /* NamespaceKeyword */));
          break;
        case 276 /* ExportAssignment */:
          displayParts.push(keywordPart(95 /* ExportKeyword */));
          displayParts.push(spacePart());
          displayParts.push(keywordPart(symbol.declarations[0].isExportEquals ? 64 /* EqualsToken */ : 90 /* DefaultKeyword */));
          break;
        case 280 /* ExportSpecifier */:
          displayParts.push(keywordPart(95 /* ExportKeyword */));
          break;
        default:
          displayParts.push(keywordPart(102 /* ImportKeyword */));
      }
    }
    displayParts.push(spacePart());
    addFullSymbolName(symbol);
    forEach(symbol.declarations, (declaration) => {
      if (declaration.kind === 270 /* ImportEqualsDeclaration */) {
        const importEqualsDeclaration = declaration;
        if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
          displayParts.push(spacePart());
          displayParts.push(operatorPart(64 /* EqualsToken */));
          displayParts.push(spacePart());
          displayParts.push(keywordPart(149 /* RequireKeyword */));
          displayParts.push(punctuationPart(21 /* OpenParenToken */));
          displayParts.push(displayPart(getTextOfNode(getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), 8 /* stringLiteral */));
          displayParts.push(punctuationPart(22 /* CloseParenToken */));
        } else {
          const internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference);
          if (internalAliasSymbol) {
            displayParts.push(spacePart());
            displayParts.push(operatorPart(64 /* EqualsToken */));
            displayParts.push(spacePart());
            addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
          }
        }
        return true;
      }
    });
  }
  if (!hasAddedSymbolInfo) {
    if (symbolKind !== "" /* unknown */) {
      if (type) {
        if (isThisExpression) {
          prefixNextMeaning();
          displayParts.push(keywordPart(110 /* ThisKeyword */));
        } else {
          addPrefixForAnyFunctionOrVar(symbol, symbolKind);
        }
        if (symbolKind === "property" /* memberVariableElement */ || symbolKind === "accessor" /* memberAccessorVariableElement */ || symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || symbolKind === "index" /* indexSignatureElement */ || isThisExpression) {
          displayParts.push(punctuationPart(59 /* ColonToken */));
          displayParts.push(spacePart());
          if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */) {
            const typeParameterParts = mapToDisplayParts((writer) => {
              const param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags);
              getPrinter().writeNode(4 /* Unspecified */, param, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration)), writer);
            });
            addRange(displayParts, typeParameterParts);
          } else {
            addRange(displayParts, typeToDisplayParts(typeChecker, type, enclosingDeclaration));
          }
          if (isTransientSymbol(symbol) && symbol.links.target && isTransientSymbol(symbol.links.target) && symbol.links.target.links.tupleLabelDeclaration) {
            const labelDecl = symbol.links.target.links.tupleLabelDeclaration;
            Debug.assertNode(labelDecl.name, isIdentifier);
            displayParts.push(spacePart());
            displayParts.push(punctuationPart(21 /* OpenParenToken */));
            displayParts.push(textPart(idText(labelDecl.name)));
            displayParts.push(punctuationPart(22 /* CloseParenToken */));
          }
        } else if (symbolFlags & 16 /* Function */ || symbolFlags & 8192 /* Method */ || symbolFlags & 16384 /* Constructor */ || symbolFlags & 131072 /* Signature */ || symbolFlags & 98304 /* Accessor */ || symbolKind === "method" /* memberFunctionElement */) {
          const allSignatures = type.getNonNullableType().getCallSignatures();
          if (allSignatures.length) {
            addSignatureDisplayParts(allSignatures[0], allSignatures);
            hasMultipleSignatures = allSignatures.length > 1;
          }
        }
      }
    } else {
      symbolKind = getSymbolKind(typeChecker, symbol, location);
    }
  }
  if (documentation.length === 0 && !hasMultipleSignatures) {
    documentation = symbol.getContextualDocumentationComment(enclosingDeclaration, typeChecker);
  }
  if (documentation.length === 0 && symbolFlags & 4 /* Property */) {
    if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, (declaration) => declaration.kind === 311 /* SourceFile */)) {
      for (const declaration of symbol.declarations) {
        if (!declaration.parent || declaration.parent.kind !== 225 /* BinaryExpression */) {
          continue;
        }
        const rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
        if (!rhsSymbol) {
          continue;
        }
        documentation = rhsSymbol.getDocumentationComment(typeChecker);
        tags = rhsSymbol.getJsDocTags(typeChecker);
        if (documentation.length > 0) {
          break;
        }
      }
    }
  }
  if (documentation.length === 0 && isIdentifier(location) && symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration)) {
    const declaration = symbol.valueDeclaration;
    const parent2 = declaration.parent;
    if (isIdentifier(declaration.name) && isObjectBindingPattern(parent2)) {
      const name = getTextOfIdentifierOrLiteral(declaration.name);
      const objectType = typeChecker.getTypeAtLocation(parent2);
      documentation = firstDefined(objectType.isUnion() ? objectType.types : [objectType], (t) => {
        const prop = t.getProperty(name);
        return prop ? prop.getDocumentationComment(typeChecker) : void 0;
      }) || emptyArray;
    }
  }
  if (tags.length === 0 && !hasMultipleSignatures) {
    tags = symbol.getContextualJsDocTags(enclosingDeclaration, typeChecker);
  }
  if (documentation.length === 0 && documentationFromAlias) {
    documentation = documentationFromAlias;
  }
  if (tags.length === 0 && tagsFromAlias) {
    tags = tagsFromAlias;
  }
  return { displayParts, documentation, symbolKind, tags: tags.length === 0 ? void 0 : tags };
  function getPrinter() {
    return createPrinterWithRemoveComments();
  }
  function prefixNextMeaning() {
    if (displayParts.length) {
      displayParts.push(lineBreakPart());
    }
    addAliasPrefixIfNecessary();
  }
  function addAliasPrefixIfNecessary() {
    if (alias) {
      pushSymbolKind("alias" /* alias */);
      displayParts.push(spacePart());
    }
  }
  function addInPrefix() {
    displayParts.push(spacePart());
    displayParts.push(keywordPart(103 /* InKeyword */));
    displayParts.push(spacePart());
  }
  function addFullSymbolName(symbolToDisplay, enclosingDeclaration2) {
    let indexInfos;
    if (alias && symbolToDisplay === symbol) {
      symbolToDisplay = alias;
    }
    if (symbolKind === "index" /* indexSignatureElement */) {
      indexInfos = typeChecker.getIndexInfosOfIndexSymbol(symbolToDisplay);
    }
    let fullSymbolDisplayParts = [];
    if (symbolToDisplay.flags & 131072 /* Signature */ && indexInfos) {
      if (symbolToDisplay.parent) {
        fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay.parent);
      }
      fullSymbolDisplayParts.push(punctuationPart(23 /* OpenBracketToken */));
      indexInfos.forEach((info, i) => {
        fullSymbolDisplayParts.push(...typeToDisplayParts(typeChecker, info.keyType));
        if (i !== indexInfos.length - 1) {
          fullSymbolDisplayParts.push(spacePart());
          fullSymbolDisplayParts.push(punctuationPart(52 /* BarToken */));
          fullSymbolDisplayParts.push(spacePart());
        }
      });
      fullSymbolDisplayParts.push(punctuationPart(24 /* CloseBracketToken */));
    } else {
      fullSymbolDisplayParts = symbolToDisplayParts(
        typeChecker,
        symbolToDisplay,
        enclosingDeclaration2 || sourceFile,
        /*meaning*/
        void 0,
        1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */
      );
    }
    addRange(displayParts, fullSymbolDisplayParts);
    if (symbol.flags & 16777216 /* Optional */) {
      displayParts.push(punctuationPart(58 /* QuestionToken */));
    }
  }
  function addPrefixForAnyFunctionOrVar(symbol2, symbolKind2) {
    prefixNextMeaning();
    if (symbolKind2) {
      pushSymbolKind(symbolKind2);
      if (symbol2 && !some(symbol2.declarations, (d) => isArrowFunction(d) || (isFunctionExpression(d) || isClassExpression(d)) && !d.name)) {
        displayParts.push(spacePart());
        addFullSymbolName(symbol2);
      }
    }
  }
  function pushSymbolKind(symbolKind2) {
    switch (symbolKind2) {
      case "var" /* variableElement */:
      case "function" /* functionElement */:
      case "let" /* letElement */:
      case "const" /* constElement */:
      case "constructor" /* constructorImplementationElement */:
        displayParts.push(textOrKeywordPart(symbolKind2));
        return;
      default:
        displayParts.push(punctuationPart(21 /* OpenParenToken */));
        displayParts.push(textOrKeywordPart(symbolKind2));
        displayParts.push(punctuationPart(22 /* CloseParenToken */));
        return;
    }
  }
  function addSignatureDisplayParts(signature, allSignatures, flags = 0 /* None */) {
    addRange(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */));
    if (allSignatures.length > 1) {
      displayParts.push(spacePart());
      displayParts.push(punctuationPart(21 /* OpenParenToken */));
      displayParts.push(operatorPart(40 /* PlusToken */));
      displayParts.push(displayPart((allSignatures.length - 1).toString(), 7 /* numericLiteral */));
      displayParts.push(spacePart());
      displayParts.push(textPart(allSignatures.length === 2 ? "overload" : "overloads"));
      displayParts.push(punctuationPart(22 /* CloseParenToken */));
    }
    documentation = signature.getDocumentationComment(typeChecker);
    tags = signature.getJsDocTags();
    if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) {
      documentation = allSignatures[0].getDocumentationComment(typeChecker);
      tags = allSignatures[0].getJsDocTags().filter((tag) => tag.name !== "deprecated");
    }
  }
  function writeTypeParametersOfSymbol(symbol2, enclosingDeclaration2) {
    const typeParameterParts = mapToDisplayParts((writer) => {
      const params = typeChecker.symbolToTypeParameterDeclarations(symbol2, enclosingDeclaration2, symbolDisplayNodeBuilderFlags);
      getPrinter().writeList(53776 /* TypeParameters */, params, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration2)), writer);
    });
    addRange(displayParts, typeParameterParts);
  }
}
function isLocalVariableOrFunction(symbol) {
  if (symbol.parent) {
    return false;
  }
  return forEach(symbol.declarations, (declaration) => {
    if (declaration.kind === 217 /* FunctionExpression */) {
      return true;
    }
    if (declaration.kind !== 259 /* VariableDeclaration */ && declaration.kind !== 261 /* FunctionDeclaration */) {
      return false;
    }
    for (let parent2 = declaration.parent; !isFunctionBlock(parent2); parent2 = parent2.parent) {
      if (parent2.kind === 311 /* SourceFile */ || parent2.kind === 267 /* ModuleBlock */) {
        return false;
      }
    }
    return true;
  });
}

// src/services/_namespaces/ts.textChanges.ts
var ts_textChanges_exports = {};
__export(ts_textChanges_exports, {
  ChangeTracker: () => ChangeTracker,
  LeadingTriviaOption: () => LeadingTriviaOption,
  TrailingTriviaOption: () => TrailingTriviaOption,
  applyChanges: () => applyChanges,
  assignPositionsToNode: () => assignPositionsToNode,
  createWriter: () => createWriter,
  deleteNode: () => deleteNode,
  isThisTypeAnnotatable: () => isThisTypeAnnotatable,
  isValidLocationToAddComment: () => isValidLocationToAddComment
});

// src/services/textChanges.ts
function getPos2(n) {
  const result = n.__pos;
  Debug.assert(typeof result === "number");
  return result;
}
function setPos(n, pos) {
  Debug.assert(typeof pos === "number");
  n.__pos = pos;
}
function getEnd(n) {
  const result = n.__end;
  Debug.assert(typeof result === "number");
  return result;
}
function setEnd(n, end) {
  Debug.assert(typeof end === "number");
  n.__end = end;
}
var LeadingTriviaOption = /* @__PURE__ */ ((LeadingTriviaOption2) => {
  LeadingTriviaOption2[LeadingTriviaOption2["Exclude"] = 0] = "Exclude";
  LeadingTriviaOption2[LeadingTriviaOption2["IncludeAll"] = 1] = "IncludeAll";
  LeadingTriviaOption2[LeadingTriviaOption2["JSDoc"] = 2] = "JSDoc";
  LeadingTriviaOption2[LeadingTriviaOption2["StartLine"] = 3] = "StartLine";
  return LeadingTriviaOption2;
})(LeadingTriviaOption || {});
var TrailingTriviaOption = /* @__PURE__ */ ((TrailingTriviaOption2) => {
  TrailingTriviaOption2[TrailingTriviaOption2["Exclude"] = 0] = "Exclude";
  TrailingTriviaOption2[TrailingTriviaOption2["ExcludeWhitespace"] = 1] = "ExcludeWhitespace";
  TrailingTriviaOption2[TrailingTriviaOption2["Include"] = 2] = "Include";
  return TrailingTriviaOption2;
})(TrailingTriviaOption || {});
function skipWhitespacesAndLineBreaks(text, start2) {
  return skipTrivia(
    text,
    start2,
    /*stopAfterLineBreak*/
    false,
    /*stopAtComments*/
    true
  );
}
function hasCommentsBeforeLineBreak(text, start2) {
  let i = start2;
  while (i < text.length) {
    const ch = text.charCodeAt(i);
    if (isWhiteSpaceSingleLine(ch)) {
      i++;
      continue;
    }
    return ch === 47 /* slash */;
  }
  return false;
}
var useNonAdjustedPositions = {
  leadingTriviaOption: 0 /* Exclude */,
  trailingTriviaOption: 0 /* Exclude */
};
function getAdjustedRange(sourceFile, startNode2, endNode2, options) {
  return { pos: getAdjustedStartPosition(sourceFile, startNode2, options), end: getAdjustedEndPosition(sourceFile, endNode2, options) };
}
function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment = false) {
  var _a, _b;
  const { leadingTriviaOption } = options;
  if (leadingTriviaOption === 0 /* Exclude */) {
    return node.getStart(sourceFile);
  }
  if (leadingTriviaOption === 3 /* StartLine */) {
    const startPos = node.getStart(sourceFile);
    const pos = getLineStartPositionForPosition(startPos, sourceFile);
    return rangeContainsPosition(node, pos) ? pos : startPos;
  }
  if (leadingTriviaOption === 2 /* JSDoc */) {
    const JSDocComments = getJSDocCommentRanges(node, sourceFile.text);
    if (JSDocComments == null ? void 0 : JSDocComments.length) {
      return getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile);
    }
  }
  const fullStart = node.getFullStart();
  const start2 = node.getStart(sourceFile);
  if (fullStart === start2) {
    return start2;
  }
  const fullStartLine = getLineStartPositionForPosition(fullStart, sourceFile);
  const startLine = getLineStartPositionForPosition(start2, sourceFile);
  if (startLine === fullStartLine) {
    return leadingTriviaOption === 1 /* IncludeAll */ ? fullStart : start2;
  }
  if (hasTrailingComment) {
    const comment = ((_a = getLeadingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _a[0]) || ((_b = getTrailingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _b[0]);
    if (comment) {
      return skipTrivia(
        sourceFile.text,
        comment.end,
        /*stopAfterLineBreak*/
        true,
        /*stopAtComments*/
        true
      );
    }
  }
  const nextLineStart = fullStart > 0 ? 1 : 0;
  let adjustedStartPosition = getStartPositionOfLine(getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
  adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
  return getStartPositionOfLine(getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) {
  const { end } = node;
  const { trailingTriviaOption } = options;
  if (trailingTriviaOption === 2 /* Include */) {
    const comments = getTrailingCommentRanges(sourceFile.text, end);
    if (comments) {
      const nodeEndLine = getLineOfLocalPosition(sourceFile, node.end);
      for (const comment of comments) {
        if (comment.kind === 2 /* SingleLineCommentTrivia */ || getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) {
          break;
        }
        const commentEndLine = getLineOfLocalPosition(sourceFile, comment.end);
        if (commentEndLine > nodeEndLine) {
          return skipTrivia(
            sourceFile.text,
            comment.end,
            /*stopAfterLineBreak*/
            true,
            /*stopAtComments*/
            true
          );
        }
      }
    }
  }
  return void 0;
}
function getAdjustedEndPosition(sourceFile, node, options) {
  var _a;
  const { end } = node;
  const { trailingTriviaOption } = options;
  if (trailingTriviaOption === 0 /* Exclude */) {
    return end;
  }
  if (trailingTriviaOption === 1 /* ExcludeWhitespace */) {
    const comments = concatenate(getTrailingCommentRanges(sourceFile.text, end), getLeadingCommentRanges(sourceFile.text, end));
    const realEnd = (_a = comments == null ? void 0 : comments[comments.length - 1]) == null ? void 0 : _a.end;
    if (realEnd) {
      return realEnd;
    }
    return end;
  }
  const multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options);
  if (multilineEndPosition) {
    return multilineEndPosition;
  }
  const newEnd = skipTrivia(
    sourceFile.text,
    end,
    /*stopAfterLineBreak*/
    true
  );
  return newEnd !== end && (trailingTriviaOption === 2 /* Include */ || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end;
}
function isSeparator(node, candidate) {
  return !!candidate && !!node.parent && (candidate.kind === 28 /* CommaToken */ || candidate.kind === 27 /* SemicolonToken */ && node.parent.kind === 209 /* ObjectLiteralExpression */);
}
function isThisTypeAnnotatable(containingFunction) {
  return isFunctionExpression(containingFunction) || isFunctionDeclaration(containingFunction);
}
var ChangeTracker = class {
  /** Public for tests only. Other callers should use `ChangeTracker.with`. */
  constructor(newLineCharacter, formatContext) {
    this.newLineCharacter = newLineCharacter;
    this.formatContext = formatContext;
    this.changes = [];
    this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map();
    // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
    this.deletedNodes = [];
  }
  static fromContext(context) {
    return new ChangeTracker(getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
  }
  static with(context, cb) {
    const tracker = ChangeTracker.fromContext(context);
    cb(tracker);
    return tracker.getChanges();
  }
  pushRaw(sourceFile, change) {
    Debug.assertEqual(sourceFile.fileName, change.fileName);
    for (const c of change.textChanges) {
      this.changes.push({
        kind: 3 /* Text */,
        sourceFile,
        text: c.newText,
        range: createTextRangeFromSpan(c.span)
      });
    }
  }
  deleteRange(sourceFile, range) {
    this.changes.push({ kind: 0 /* Remove */, sourceFile, range });
  }
  delete(sourceFile, node) {
    this.deletedNodes.push({ sourceFile, node });
  }
  /** Stop! Consider using `delete` instead, which has logic for deleting nodes from delimited lists. */
  deleteNode(sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
    this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options));
  }
  deleteNodes(sourceFile, nodes, options = { leadingTriviaOption: 1 /* IncludeAll */ }, hasTrailingComment) {
    for (const node of nodes) {
      const pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment);
      const end = getAdjustedEndPosition(sourceFile, node, options);
      this.deleteRange(sourceFile, { pos, end });
      hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options);
    }
  }
  deleteModifier(sourceFile, modifier) {
    this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(
      sourceFile.text,
      modifier.end,
      /*stopAfterLineBreak*/
      true
    ) });
  }
  deleteNodeRange(sourceFile, startNode2, endNode2, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
    const startPosition = getAdjustedStartPosition(sourceFile, startNode2, options);
    const endPosition = getAdjustedEndPosition(sourceFile, endNode2, options);
    this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  }
  deleteNodeRangeExcludingEnd(sourceFile, startNode2, afterEndNode, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
    const startPosition = getAdjustedStartPosition(sourceFile, startNode2, options);
    const endPosition = afterEndNode === void 0 ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
    this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
  }
  replaceRange(sourceFile, range, newNode, options = {}) {
    this.changes.push({ kind: 1 /* ReplaceWithSingleNode */, sourceFile, range, options, node: newNode });
  }
  replaceNode(sourceFile, oldNode, newNode, options = useNonAdjustedPositions) {
    this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
  }
  replaceNodeRange(sourceFile, startNode2, endNode2, newNode, options = useNonAdjustedPositions) {
    this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode2, endNode2, options), newNode, options);
  }
  replaceRangeWithNodes(sourceFile, range, newNodes, options = {}) {
    this.changes.push({ kind: 2 /* ReplaceWithMultipleNodes */, sourceFile, range, options, nodes: newNodes });
  }
  replaceNodeWithNodes(sourceFile, oldNode, newNodes, options = useNonAdjustedPositions) {
    this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
  }
  replaceNodeWithText(sourceFile, oldNode, text) {
    this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
  }
  replaceNodeRangeWithNodes(sourceFile, startNode2, endNode2, newNodes, options = useNonAdjustedPositions) {
    this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode2, endNode2, options), newNodes, options);
  }
  nodeHasTrailingComment(sourceFile, oldNode, configurableEnd = useNonAdjustedPositions) {
    return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd);
  }
  nextCommaToken(sourceFile, node) {
    const next = findNextToken(node, node.parent, sourceFile);
    return next && next.kind === 28 /* CommaToken */ ? next : void 0;
  }
  replacePropertyAssignment(sourceFile, oldNode, newNode) {
    const suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : "," + this.newLineCharacter;
    this.replaceNode(sourceFile, oldNode, newNode, { suffix });
  }
  insertNodeAt(sourceFile, pos, newNode, options = {}) {
    this.replaceRange(sourceFile, createRange(pos), newNode, options);
  }
  insertNodesAt(sourceFile, pos, newNodes, options = {}) {
    this.replaceRangeWithNodes(sourceFile, createRange(pos), newNodes, options);
  }
  insertNodeAtTopOfFile(sourceFile, newNode, blankLineBetween) {
    this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween);
  }
  insertNodesAtTopOfFile(sourceFile, newNodes, blankLineBetween) {
    this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween);
  }
  insertAtTopOfFile(sourceFile, insert, blankLineBetween) {
    const pos = getInsertionPositionAtSourceFileTop(sourceFile);
    const options = {
      prefix: pos === 0 ? void 0 : this.newLineCharacter,
      suffix: (isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : "")
    };
    if (isArray(insert)) {
      this.insertNodesAt(sourceFile, pos, insert, options);
    } else {
      this.insertNodeAt(sourceFile, pos, insert, options);
    }
  }
  insertNodesAtEndOfFile(sourceFile, newNodes, blankLineBetween) {
    this.insertAtEndOfFile(sourceFile, newNodes, blankLineBetween);
  }
  insertAtEndOfFile(sourceFile, insert, blankLineBetween) {
    const pos = sourceFile.end + 1;
    const options = {
      prefix: this.newLineCharacter,
      suffix: this.newLineCharacter + (blankLineBetween ? this.newLineCharacter : "")
    };
    this.insertNodesAt(sourceFile, pos, insert, options);
  }
  insertStatementsInNewFile(fileName, statements, oldFile) {
    if (!this.newFileChanges) {
      this.newFileChanges = createMultiMap();
    }
    this.newFileChanges.add(fileName, { oldFile, statements });
  }
  insertFirstParameter(sourceFile, parameters, newParam) {
    const p0 = firstOrUndefined(parameters);
    if (p0) {
      this.insertNodeBefore(sourceFile, p0, newParam);
    } else {
      this.insertNodeAt(sourceFile, parameters.pos, newParam);
    }
  }
  insertNodeBefore(sourceFile, before, newNode, blankLineBetween = false, options = {}) {
    this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
  }
  insertModifierAt(sourceFile, pos, modifier, options = {}) {
    this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options);
  }
  insertModifierBefore(sourceFile, modifier, before) {
    return this.insertModifierAt(sourceFile, before.getStart(sourceFile), modifier, { suffix: " " });
  }
  insertCommentBeforeLine(sourceFile, lineNumber, position, commentText) {
    const lineStartPosition = getStartPositionOfLine(lineNumber, sourceFile);
    const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
    const insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
    const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
    const indent3 = sourceFile.text.slice(lineStartPosition, startPosition);
    const text = `${insertAtLineStart ? "" : this.newLineCharacter}//${commentText}${this.newLineCharacter}${indent3}`;
    this.insertText(sourceFile, token.getStart(sourceFile), text);
  }
  insertJsdocCommentBefore(sourceFile, node, tag) {
    const fnStart = node.getStart(sourceFile);
    if (node.jsDoc) {
      for (const jsdoc of node.jsDoc) {
        this.deleteRange(sourceFile, {
          pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile),
          end: getAdjustedEndPosition(
            sourceFile,
            jsdoc,
            /*options*/
            {}
          )
        });
      }
    }
    const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1);
    const indent3 = sourceFile.text.slice(startPosition, fnStart);
    this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent3 });
  }
  createJSDocText(sourceFile, node) {
    const comments = flatMap(node.jsDoc, (jsDoc2) => isString(jsDoc2.comment) ? factory.createJSDocText(jsDoc2.comment) : jsDoc2.comment);
    const jsDoc = singleOrUndefined(node.jsDoc);
    return jsDoc && positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && length(comments) === 0 ? void 0 : factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n")));
  }
  replaceJSDocComment(sourceFile, node, tags) {
    this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), factory.createJSDocComment(this.createJSDocText(sourceFile, node), factory.createNodeArray(tags)));
  }
  addJSDocTags(sourceFile, parent2, newTags) {
    const oldTags = flatMapToMutable(parent2.jsDoc, (j) => j.tags);
    const unmergedNewTags = newTags.filter((newTag) => !oldTags.some((tag, i) => {
      const merged = tryMergeJsdocTags(tag, newTag);
      if (merged)
        oldTags[i] = merged;
      return !!merged;
    }));
    this.replaceJSDocComment(sourceFile, parent2, [...oldTags, ...unmergedNewTags]);
  }
  filterJSDocTags(sourceFile, parent2, predicate) {
    this.replaceJSDocComment(sourceFile, parent2, filter(flatMapToMutable(parent2.jsDoc, (j) => j.tags), predicate));
  }
  replaceRangeWithText(sourceFile, range, text) {
    this.changes.push({ kind: 3 /* Text */, sourceFile, range, text });
  }
  insertText(sourceFile, pos, text) {
    this.replaceRangeWithText(sourceFile, createRange(pos), text);
  }
  /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
  tryInsertTypeAnnotation(sourceFile, node, type) {
    let endNode2;
    if (isFunctionLike(node)) {
      endNode2 = findChildOfKind(node, 22 /* CloseParenToken */, sourceFile);
      if (!endNode2) {
        if (!isArrowFunction(node))
          return false;
        endNode2 = first(node.parameters);
      }
    } else {
      endNode2 = (node.kind === 259 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) ?? node.name;
    }
    this.insertNodeAt(sourceFile, endNode2.end, type, { prefix: ": " });
    return true;
  }
  tryInsertThisTypeAnnotation(sourceFile, node, type) {
    const start2 = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1;
    const suffix = node.parameters.length ? ", " : "";
    this.insertNodeAt(sourceFile, start2, type, { prefix: "this: ", suffix });
  }
  insertTypeParameters(sourceFile, node, typeParameters) {
    const start2 = (findChildOfKind(node, 21 /* OpenParenToken */, sourceFile) || first(node.parameters)).getStart(sourceFile);
    this.insertNodesAt(sourceFile, start2, typeParameters, { prefix: "<", suffix: ">", joiner: ", " });
  }
  getOptionsForInsertNodeBefore(before, inserted, blankLineBetween) {
    if (isStatement(before) || isClassElement(before)) {
      return { suffix: blankLineBetween ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
    } else if (isVariableDeclaration(before)) {
      return { suffix: ", " };
    } else if (isParameter(before)) {
      return isParameter(inserted) ? { suffix: ", " } : {};
    } else if (isStringLiteral(before) && isImportDeclaration(before.parent) || isNamedImports(before)) {
      return { suffix: ", " };
    } else if (isImportSpecifier(before)) {
      return { suffix: "," + (blankLineBetween ? this.newLineCharacter : " ") };
    }
    return Debug.failBadSyntaxKind(before);
  }
  insertNodeAtConstructorStart(sourceFile, ctr, newStatement) {
    const firstStatement = firstOrUndefined(ctr.body.statements);
    if (!firstStatement || !ctr.body.multiLine) {
      this.replaceConstructorBody(sourceFile, ctr, [newStatement, ...ctr.body.statements]);
    } else {
      this.insertNodeBefore(sourceFile, firstStatement, newStatement);
    }
  }
  insertNodeAtConstructorStartAfterSuperCall(sourceFile, ctr, newStatement) {
    const superCallStatement = find(ctr.body.statements, (stmt) => isExpressionStatement(stmt) && isSuperCall(stmt.expression));
    if (!superCallStatement || !ctr.body.multiLine) {
      this.replaceConstructorBody(sourceFile, ctr, [...ctr.body.statements, newStatement]);
    } else {
      this.insertNodeAfter(sourceFile, superCallStatement, newStatement);
    }
  }
  insertNodeAtConstructorEnd(sourceFile, ctr, newStatement) {
    const lastStatement = lastOrUndefined(ctr.body.statements);
    if (!lastStatement || !ctr.body.multiLine) {
      this.replaceConstructorBody(sourceFile, ctr, [...ctr.body.statements, newStatement]);
    } else {
      this.insertNodeAfter(sourceFile, lastStatement, newStatement);
    }
  }
  replaceConstructorBody(sourceFile, ctr, statements) {
    this.replaceNode(sourceFile, ctr.body, factory.createBlock(
      statements,
      /*multiLine*/
      true
    ));
  }
  insertNodeAtEndOfScope(sourceFile, scope, newNode) {
    const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
    this.insertNodeAt(sourceFile, pos, newNode, {
      prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
      suffix: this.newLineCharacter
    });
  }
  insertMemberAtStart(sourceFile, node, newElement) {
    this.insertNodeAtStartWorker(sourceFile, node, newElement);
  }
  insertNodeAtObjectStart(sourceFile, obj, newElement) {
    this.insertNodeAtStartWorker(sourceFile, obj, newElement);
  }
  insertNodeAtStartWorker(sourceFile, node, newElement) {
    const indentation = this.guessIndentationFromExistingMembers(sourceFile, node) ?? this.computeIndentationForNewMember(sourceFile, node);
    this.insertNodeAt(sourceFile, getMembersOrProperties(node).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, node, indentation));
  }
  /**
   * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on
   * new lines and must share the same indentation.
   */
  guessIndentationFromExistingMembers(sourceFile, node) {
    let indentation;
    let lastRange = node;
    for (const member of getMembersOrProperties(node)) {
      if (rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) {
        return void 0;
      }
      const memberStart = member.getStart(sourceFile);
      const memberIndentation = ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options);
      if (indentation === void 0) {
        indentation = memberIndentation;
      } else if (memberIndentation !== indentation) {
        return void 0;
      }
      lastRange = member;
    }
    return indentation;
  }
  computeIndentationForNewMember(sourceFile, node) {
    const nodeStart = node.getStart(sourceFile);
    return ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options) + (this.formatContext.options.indentSize ?? 4);
  }
  getInsertNodeAtStartInsertOptions(sourceFile, node, indentation) {
    const members = getMembersOrProperties(node);
    const isEmpty = members.length === 0;
    const isFirstInsertion = addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(node), { node, sourceFile });
    const insertTrailingComma = isObjectLiteralExpression(node) && (!isJsonSourceFile(sourceFile) || !isEmpty);
    const insertLeadingComma = isObjectLiteralExpression(node) && isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion;
    return {
      indentation,
      prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter,
      suffix: insertTrailingComma ? "," : isInterfaceDeclaration(node) && isEmpty ? ";" : ""
    };
  }
  insertNodeAfterComma(sourceFile, after, newNode) {
    const endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
    this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
  }
  insertNodeAfter(sourceFile, after, newNode) {
    const endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
    this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
  }
  insertNodeAtEndOfList(sourceFile, list, newNode) {
    this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
  }
  insertNodesAfter(sourceFile, after, newNodes) {
    const endPosition = this.insertNodeAfterWorker(sourceFile, after, first(newNodes));
    this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
  }
  insertNodeAfterWorker(sourceFile, after, newNode) {
    if (needSemicolonBetween(after, newNode)) {
      if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
        this.replaceRange(sourceFile, createRange(after.end), factory.createToken(27 /* SemicolonToken */));
      }
    }
    const endPosition = getAdjustedEndPosition(sourceFile, after, {});
    return endPosition;
  }
  getInsertNodeAfterOptions(sourceFile, after) {
    const options = this.getInsertNodeAfterOptionsWorker(after);
    return {
      ...options,
      prefix: after.end === sourceFile.end && isStatement(after) ? options.prefix ? `
${options.prefix}` : "\n" : options.prefix
    };
  }
  getInsertNodeAfterOptionsWorker(node) {
    switch (node.kind) {
      case 262 /* ClassDeclaration */:
      case 266 /* ModuleDeclaration */:
        return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
      case 259 /* VariableDeclaration */:
      case 11 /* StringLiteral */:
      case 80 /* Identifier */:
        return { prefix: ", " };
      case 302 /* PropertyAssignment */:
        return { suffix: "," + this.newLineCharacter };
      case 95 /* ExportKeyword */:
        return { prefix: " " };
      case 168 /* Parameter */:
        return {};
      default:
        Debug.assert(isStatement(node) || isClassOrTypeElement(node));
        return { suffix: this.newLineCharacter };
    }
  }
  insertName(sourceFile, node, name) {
    Debug.assert(!node.name);
    if (node.kind === 218 /* ArrowFunction */) {
      const arrow = findChildOfKind(node, 39 /* EqualsGreaterThanToken */, sourceFile);
      const lparen = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile);
      if (lparen) {
        this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [factory.createToken(100 /* FunctionKeyword */), factory.createIdentifier(name)], { joiner: " " });
        deleteNode(this, sourceFile, arrow);
      } else {
        this.insertText(sourceFile, first(node.parameters).getStart(sourceFile), `function ${name}(`);
        this.replaceRange(sourceFile, arrow, factory.createToken(22 /* CloseParenToken */));
      }
      if (node.body.kind !== 240 /* Block */) {
        this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [factory.createToken(19 /* OpenBraceToken */), factory.createToken(107 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
        this.insertNodesAt(sourceFile, node.body.end, [factory.createToken(27 /* SemicolonToken */), factory.createToken(20 /* CloseBraceToken */)], { joiner: " " });
      }
    } else {
      const pos = findChildOfKind(node, node.kind === 217 /* FunctionExpression */ ? 100 /* FunctionKeyword */ : 86 /* ClassKeyword */, sourceFile).end;
      this.insertNodeAt(sourceFile, pos, factory.createIdentifier(name), { prefix: " " });
    }
  }
  insertExportModifier(sourceFile, node) {
    this.insertText(sourceFile, node.getStart(sourceFile), "export ");
  }
  insertImportSpecifierAtIndex(sourceFile, importSpecifier, namedImports, index) {
    const prevSpecifier = namedImports.elements[index - 1];
    if (prevSpecifier) {
      this.insertNodeInListAfter(sourceFile, prevSpecifier, importSpecifier);
    } else {
      this.insertNodeBefore(
        sourceFile,
        namedImports.elements[0],
        importSpecifier,
        !positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile)
      );
    }
  }
  /**
   * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
   * i.e. arguments in arguments lists, parameters in parameter lists etc.
   * Note that separators are part of the node in statements and class elements.
   */
  insertNodeInListAfter(sourceFile, after, newNode, containingList = ts_formatting_exports.SmartIndenter.getContainingList(after, sourceFile)) {
    if (!containingList) {
      Debug.fail("node is not a list element");
      return;
    }
    const index = indexOfNode(containingList, after);
    if (index < 0) {
      return;
    }
    const end = after.getEnd();
    if (index !== containingList.length - 1) {
      const nextToken = getTokenAtPosition(sourceFile, after.end);
      if (nextToken && isSeparator(after, nextToken)) {
        const nextNode = containingList[index + 1];
        const startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart());
        const suffix = `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, startPos)}`;
        this.insertNodesAt(sourceFile, startPos, [newNode], { suffix });
      }
    } else {
      const afterStart = after.getStart(sourceFile);
      const afterStartLinePosition = getLineStartPositionForPosition(afterStart, sourceFile);
      let separator;
      let multilineList = false;
      if (containingList.length === 1) {
        separator = 28 /* CommaToken */;
      } else {
        const tokenBeforeInsertPosition = findPrecedingToken(after.pos, sourceFile);
        separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 28 /* CommaToken */;
        const afterMinusOneStartLinePosition = getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
        multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
      }
      if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) {
        multilineList = true;
      }
      if (multilineList) {
        this.replaceRange(sourceFile, createRange(end), factory.createToken(separator));
        const indentation = ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
        let insertPos = skipTrivia(
          sourceFile.text,
          end,
          /*stopAfterLineBreak*/
          true,
          /*stopAtComments*/
          false
        );
        while (insertPos !== end && isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
          insertPos--;
        }
        this.replaceRange(sourceFile, createRange(insertPos), newNode, { indentation, prefix: this.newLineCharacter });
      } else {
        this.replaceRange(sourceFile, createRange(end), newNode, { prefix: `${tokenToString(separator)} ` });
      }
    }
  }
  parenthesizeExpression(sourceFile, expression) {
    this.replaceRange(sourceFile, rangeOfNode(expression), factory.createParenthesizedExpression(expression));
  }
  finishClassesWithNodesInsertedAtStart() {
    this.classesWithNodesInsertedAtStart.forEach(({ node, sourceFile }) => {
      const [openBraceEnd, closeBraceEnd] = getClassOrObjectBraceEnds(node, sourceFile);
      if (openBraceEnd !== void 0 && closeBraceEnd !== void 0) {
        const isEmpty = getMembersOrProperties(node).length === 0;
        const isSingleLine = positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile);
        if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) {
          this.deleteRange(sourceFile, createRange(openBraceEnd, closeBraceEnd - 1));
        }
        if (isSingleLine) {
          this.insertText(sourceFile, closeBraceEnd - 1, this.newLineCharacter);
        }
      }
    });
  }
  finishDeleteDeclarations() {
    const deletedNodesInLists = /* @__PURE__ */ new Set();
    for (const { sourceFile, node } of this.deletedNodes) {
      if (!this.deletedNodes.some((d) => d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) {
        if (isArray(node)) {
          this.deleteRange(sourceFile, rangeOfTypeParameters(sourceFile, node));
        } else {
          deleteDeclaration.deleteDeclaration(this, deletedNodesInLists, sourceFile, node);
        }
      }
    }
    deletedNodesInLists.forEach((node) => {
      const sourceFile = node.getSourceFile();
      const list = ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile);
      if (node !== last(list))
        return;
      const lastNonDeletedIndex = findLastIndex(list, (n) => !deletedNodesInLists.has(n), list.length - 2);
      if (lastNonDeletedIndex !== -1) {
        this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
      }
    });
  }
  /**
   * Note: after calling this, the TextChanges object must be discarded!
   * @param validate only for tests
   *    The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
   *    so we can only call this once and can't get the non-formatted text separately.
   */
  getChanges(validate) {
    this.finishDeleteDeclarations();
    this.finishClassesWithNodesInsertedAtStart();
    const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
    if (this.newFileChanges) {
      this.newFileChanges.forEach((insertions, fileName) => {
        changes.push(changesToText.newFileChanges(fileName, insertions, this.newLineCharacter, this.formatContext));
      });
    }
    return changes;
  }
  createNewFile(oldFile, fileName, statements) {
    this.insertStatementsInNewFile(fileName, statements, oldFile);
  }
};
function updateJSDocHost(parent2) {
  if (parent2.kind !== 218 /* ArrowFunction */) {
    return parent2;
  }
  const jsDocNode = parent2.parent.kind === 171 /* PropertyDeclaration */ ? parent2.parent : parent2.parent.parent;
  jsDocNode.jsDoc = parent2.jsDoc;
  return jsDocNode;
}
function tryMergeJsdocTags(oldTag, newTag) {
  if (oldTag.kind !== newTag.kind) {
    return void 0;
  }
  switch (oldTag.kind) {
    case 347 /* JSDocParameterTag */: {
      const oldParam = oldTag;
      const newParam = newTag;
      return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? factory.createJSDocParameterTag(
        /*tagName*/
        void 0,
        newParam.name,
        /*isBracketed*/
        false,
        newParam.typeExpression,
        newParam.isNameFirst,
        oldParam.comment
      ) : void 0;
    }
    case 348 /* JSDocReturnTag */:
      return factory.createJSDocReturnTag(
        /*tagName*/
        void 0,
        newTag.typeExpression,
        oldTag.comment
      );
    case 350 /* JSDocTypeTag */:
      return factory.createJSDocTypeTag(
        /*tagName*/
        void 0,
        newTag.typeExpression,
        oldTag.comment
      );
  }
}
function startPositionToDeleteNodeInList(sourceFile, node) {
  return skipTrivia(
    sourceFile.text,
    getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: 1 /* IncludeAll */ }),
    /*stopAfterLineBreak*/
    false,
    /*stopAtComments*/
    true
  );
}
function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) {
  const end = startPositionToDeleteNodeInList(sourceFile, nextNode);
  if (prevNode === void 0 || positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) {
    return end;
  }
  const token = findPrecedingToken(nextNode.getStart(sourceFile), sourceFile);
  if (isSeparator(node, token)) {
    const prevToken = findPrecedingToken(node.getStart(sourceFile), sourceFile);
    if (isSeparator(prevNode, prevToken)) {
      const pos = skipTrivia(
        sourceFile.text,
        token.getEnd(),
        /*stopAfterLineBreak*/
        true,
        /*stopAtComments*/
        true
      );
      if (positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) {
        return isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos;
      }
      if (isLineBreak(sourceFile.text.charCodeAt(pos))) {
        return pos;
      }
    }
  }
  return end;
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
  const open = findChildOfKind(cls, 19 /* OpenBraceToken */, sourceFile);
  const close = findChildOfKind(cls, 20 /* CloseBraceToken */, sourceFile);
  return [open == null ? void 0 : open.end, close == null ? void 0 : close.end];
}
function getMembersOrProperties(node) {
  return isObjectLiteralExpression(node) ? node.properties : node.members;
}
var changesToText;
((changesToText2) => {
  function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
    return mapDefined(group(changes, (c) => c.sourceFile.path), (changesInFile) => {
      const sourceFile = changesInFile[0].sourceFile;
      const normalized = stableSort(changesInFile, (a, b) => a.range.pos - b.range.pos || a.range.end - b.range.end);
      for (let i = 0; i < normalized.length - 1; i++) {
        Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", () => `${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`);
      }
      const textChanges2 = mapDefined(normalized, (c) => {
        const span = createTextSpanFromRange(c.range);
        const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile;
        const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate);
        if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) {
          return void 0;
        }
        return createTextChange(span, newText);
      });
      return textChanges2.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges2 } : void 0;
    });
  }
  changesToText2.getTextChangesFromChanges = getTextChangesFromChanges;
  function newFileChanges(fileName, insertions, newLineCharacter, formatContext) {
    const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext);
    return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true };
  }
  changesToText2.newFileChanges = newFileChanges;
  function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) {
    const nonFormattedText = flatMap(insertions, (insertion) => insertion.statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter);
    const sourceFile = createSourceFile(
      "any file name",
      nonFormattedText,
      99 /* ESNext */,
      /*setParentNodes*/
      true,
      scriptKind
    );
    const changes = ts_formatting_exports.formatDocument(sourceFile, formatContext);
    return applyChanges(nonFormattedText, changes) + newLineCharacter;
  }
  changesToText2.newFileChangesWorker = newFileChangesWorker;
  function computeNewText(change, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate) {
    var _a;
    if (change.kind === 0 /* Remove */) {
      return "";
    }
    if (change.kind === 3 /* Text */) {
      return change.text;
    }
    const { options = {}, range: { pos } } = change;
    const format = (n) => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate);
    const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n) => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node);
    const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, "");
    return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix);
  }
  function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) {
    const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter);
    if (validate)
      validate(node, text);
    const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile);
    const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos);
    if (delta === void 0) {
      delta = ts_formatting_exports.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? formatOptions.indentSize || 0 : 0;
    }
    const file = {
      text,
      getLineAndCharacterOfPosition(pos2) {
        return getLineAndCharacterOfPosition(this, pos2);
      }
    };
    const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions });
    return applyChanges(text, changes);
  }
  function getNonformattedText(node, sourceFile, newLineCharacter) {
    const writer = createWriter(newLineCharacter);
    const newLine = getNewLineKind(newLineCharacter);
    createPrinter({
      newLine,
      neverAsciiEscape: true,
      preserveSourceNewlines: true,
      terminateUnterminatedLiterals: true
    }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
    return { text: writer.getText(), node: assignPositionsToNode(node) };
  }
  changesToText2.getNonformattedText = getNonformattedText;
})(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
  for (let i = changes.length - 1; i >= 0; i--) {
    const { span, newText } = changes[i];
    text = `${text.substring(0, span.start)}${newText}${text.substring(textSpanEnd(span))}`;
  }
  return text;
}
function isTrivia2(s) {
  return skipTrivia(s, 0) === s.length;
}
var textChangesTransformationContext = {
  ...nullTransformationContext,
  factory: createNodeFactory(
    nullTransformationContext.factory.flags | 1 /* NoParenthesizerRules */,
    nullTransformationContext.factory.baseFactory
  )
};
function assignPositionsToNode(node) {
  const visited = visitEachChild(node, assignPositionsToNode, textChangesTransformationContext, assignPositionsToNodeArray, assignPositionsToNode);
  const newNode = nodeIsSynthesized(visited) ? visited : Object.create(visited);
  setTextRangePosEnd(newNode, getPos2(node), getEnd(node));
  return newNode;
}
function assignPositionsToNodeArray(nodes, visitor, test, start2, count) {
  const visited = visitNodes2(nodes, visitor, test, start2, count);
  if (!visited) {
    return visited;
  }
  Debug.assert(nodes);
  const nodeArray = visited === nodes ? factory.createNodeArray(visited.slice(0)) : visited;
  setTextRangePosEnd(nodeArray, getPos2(nodes), getEnd(nodes));
  return nodeArray;
}
function createWriter(newLine) {
  let lastNonTriviaPosition = 0;
  const writer = createTextWriter(newLine);
  const onBeforeEmitNode = (node) => {
    if (node) {
      setPos(node, lastNonTriviaPosition);
    }
  };
  const onAfterEmitNode = (node) => {
    if (node) {
      setEnd(node, lastNonTriviaPosition);
    }
  };
  const onBeforeEmitNodeArray = (nodes) => {
    if (nodes) {
      setPos(nodes, lastNonTriviaPosition);
    }
  };
  const onAfterEmitNodeArray = (nodes) => {
    if (nodes) {
      setEnd(nodes, lastNonTriviaPosition);
    }
  };
  const onBeforeEmitToken = (node) => {
    if (node) {
      setPos(node, lastNonTriviaPosition);
    }
  };
  const onAfterEmitToken = (node) => {
    if (node) {
      setEnd(node, lastNonTriviaPosition);
    }
  };
  function setLastNonTriviaPosition(s, force) {
    if (force || !isTrivia2(s)) {
      lastNonTriviaPosition = writer.getTextPos();
      let i = 0;
      while (isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) {
        i++;
      }
      lastNonTriviaPosition -= i;
    }
  }
  function write(s) {
    writer.write(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeComment(s) {
    writer.writeComment(s);
  }
  function writeKeyword(s) {
    writer.writeKeyword(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeOperator(s) {
    writer.writeOperator(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writePunctuation(s) {
    writer.writePunctuation(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeTrailingSemicolon(s) {
    writer.writeTrailingSemicolon(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeParameter(s) {
    writer.writeParameter(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeProperty(s) {
    writer.writeProperty(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeSpace(s) {
    writer.writeSpace(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeStringLiteral(s) {
    writer.writeStringLiteral(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeSymbol(s, sym) {
    writer.writeSymbol(s, sym);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeLine(force) {
    writer.writeLine(force);
  }
  function increaseIndent() {
    writer.increaseIndent();
  }
  function decreaseIndent() {
    writer.decreaseIndent();
  }
  function getText() {
    return writer.getText();
  }
  function rawWrite(s) {
    writer.rawWrite(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      false
    );
  }
  function writeLiteral(s) {
    writer.writeLiteral(s);
    setLastNonTriviaPosition(
      s,
      /*force*/
      true
    );
  }
  function getTextPos() {
    return writer.getTextPos();
  }
  function getLine() {
    return writer.getLine();
  }
  function getColumn() {
    return writer.getColumn();
  }
  function getIndent() {
    return writer.getIndent();
  }
  function isAtStartOfLine() {
    return writer.isAtStartOfLine();
  }
  function clear2() {
    writer.clear();
    lastNonTriviaPosition = 0;
  }
  return {
    onBeforeEmitNode,
    onAfterEmitNode,
    onBeforeEmitNodeArray,
    onAfterEmitNodeArray,
    onBeforeEmitToken,
    onAfterEmitToken,
    write,
    writeComment,
    writeKeyword,
    writeOperator,
    writePunctuation,
    writeTrailingSemicolon,
    writeParameter,
    writeProperty,
    writeSpace,
    writeStringLiteral,
    writeSymbol,
    writeLine,
    increaseIndent,
    decreaseIndent,
    getText,
    rawWrite,
    writeLiteral,
    getTextPos,
    getLine,
    getColumn,
    getIndent,
    isAtStartOfLine,
    hasTrailingComment: () => writer.hasTrailingComment(),
    hasTrailingWhitespace: () => writer.hasTrailingWhitespace(),
    clear: clear2
  };
}
function getInsertionPositionAtSourceFileTop(sourceFile) {
  let lastPrologue;
  for (const node of sourceFile.statements) {
    if (isPrologueDirective(node)) {
      lastPrologue = node;
    } else {
      break;
    }
  }
  let position = 0;
  const text = sourceFile.text;
  if (lastPrologue) {
    position = lastPrologue.end;
    advancePastLineBreak();
    return position;
  }
  const shebang = getShebang(text);
  if (shebang !== void 0) {
    position = shebang.length;
    advancePastLineBreak();
  }
  const ranges = getLeadingCommentRanges(text, position);
  if (!ranges)
    return position;
  let lastComment;
  let firstNodeLine;
  for (const range of ranges) {
    if (range.kind === 3 /* MultiLineCommentTrivia */) {
      if (isPinnedComment(text, range.pos)) {
        lastComment = { range, pinnedOrTripleSlash: true };
        continue;
      }
    } else if (isRecognizedTripleSlashComment(text, range.pos, range.end)) {
      lastComment = { range, pinnedOrTripleSlash: true };
      continue;
    }
    if (lastComment) {
      if (lastComment.pinnedOrTripleSlash)
        break;
      const commentLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
      const lastCommentEndLine = sourceFile.getLineAndCharacterOfPosition(lastComment.range.end).line;
      if (commentLine >= lastCommentEndLine + 2)
        break;
    }
    if (sourceFile.statements.length) {
      if (firstNodeLine === void 0)
        firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line;
      const commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
      if (firstNodeLine < commentEndLine + 2)
        break;
    }
    lastComment = { range, pinnedOrTripleSlash: false };
  }
  if (lastComment) {
    position = lastComment.range.end;
    advancePastLineBreak();
  }
  return position;
  function advancePastLineBreak() {
    if (position < text.length) {
      const charCode = text.charCodeAt(position);
      if (isLineBreak(charCode)) {
        position++;
        if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) {
          position++;
        }
      }
    }
  }
}
function isValidLocationToAddComment(sourceFile, position) {
  return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position) && !isInJSXText(sourceFile, position);
}
function needSemicolonBetween(a, b) {
  return (isPropertySignature(a) || isPropertyDeclaration(a)) && isClassOrTypeElement(b) && b.name.kind === 166 /* ComputedPropertyName */ || isStatementButNotDeclaration(a) && isStatementButNotDeclaration(b);
}
var deleteDeclaration;
((_deleteDeclaration) => {
  function deleteDeclaration2(changes, deletedNodesInLists, sourceFile, node) {
    switch (node.kind) {
      case 168 /* Parameter */: {
        const oldFunction = node.parent;
        if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && !findChildOfKind(oldFunction, 21 /* OpenParenToken */, sourceFile)) {
          changes.replaceNodeWithText(sourceFile, node, "()");
        } else {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        }
        break;
      }
      case 271 /* ImportDeclaration */:
      case 270 /* ImportEqualsDeclaration */:
        const isFirstImport = sourceFile.imports.length && node === first(sourceFile.imports).parent || node === find(sourceFile.statements, isAnyImportSyntax);
        deleteNode(changes, sourceFile, node, {
          leadingTriviaOption: isFirstImport ? 0 /* Exclude */ : hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */
        });
        break;
      case 207 /* BindingElement */:
        const pattern = node.parent;
        const preserveComma = pattern.kind === 206 /* ArrayBindingPattern */ && node !== last(pattern.elements);
        if (preserveComma) {
          deleteNode(changes, sourceFile, node);
        } else {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        }
        break;
      case 259 /* VariableDeclaration */:
        deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
        break;
      case 167 /* TypeParameter */:
        deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        break;
      case 275 /* ImportSpecifier */:
        const namedImports = node.parent;
        if (namedImports.elements.length === 1) {
          deleteImportBinding(changes, sourceFile, namedImports);
        } else {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        }
        break;
      case 273 /* NamespaceImport */:
        deleteImportBinding(changes, sourceFile, node);
        break;
      case 27 /* SemicolonToken */:
        deleteNode(changes, sourceFile, node, { trailingTriviaOption: 0 /* Exclude */ });
        break;
      case 100 /* FunctionKeyword */:
        deleteNode(changes, sourceFile, node, { leadingTriviaOption: 0 /* Exclude */ });
        break;
      case 262 /* ClassDeclaration */:
      case 261 /* FunctionDeclaration */:
        deleteNode(changes, sourceFile, node, { leadingTriviaOption: hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ });
        break;
      default:
        if (!node.parent) {
          deleteNode(changes, sourceFile, node);
        } else if (isImportClause(node.parent) && node.parent.name === node) {
          deleteDefaultImport(changes, sourceFile, node.parent);
        } else if (isCallExpression(node.parent) && contains(node.parent.arguments, node)) {
          deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
        } else {
          deleteNode(changes, sourceFile, node);
        }
    }
  }
  _deleteDeclaration.deleteDeclaration = deleteDeclaration2;
  function deleteDefaultImport(changes, sourceFile, importClause) {
    if (!importClause.namedBindings) {
      deleteNode(changes, sourceFile, importClause.parent);
    } else {
      const start2 = importClause.name.getStart(sourceFile);
      const nextToken = getTokenAtPosition(sourceFile, importClause.name.end);
      if (nextToken && nextToken.kind === 28 /* CommaToken */) {
        const end = skipTrivia(
          sourceFile.text,
          nextToken.end,
          /*stopAfterLineBreak*/
          false,
          /*stopAtComments*/
          true
        );
        changes.deleteRange(sourceFile, { pos: start2, end });
      } else {
        deleteNode(changes, sourceFile, importClause.name);
      }
    }
  }
  function deleteImportBinding(changes, sourceFile, node) {
    if (node.parent.name) {
      const previousToken = Debug.checkDefined(getTokenAtPosition(sourceFile, node.pos - 1));
      changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
    } else {
      const importDecl = getAncestor(node, 271 /* ImportDeclaration */);
      deleteNode(changes, sourceFile, importDecl);
    }
  }
  function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
    const { parent: parent2 } = node;
    if (parent2.kind === 298 /* CatchClause */) {
      changes.deleteNodeRange(sourceFile, findChildOfKind(parent2, 21 /* OpenParenToken */, sourceFile), findChildOfKind(parent2, 22 /* CloseParenToken */, sourceFile));
      return;
    }
    if (parent2.declarations.length !== 1) {
      deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
      return;
    }
    const gp = parent2.parent;
    switch (gp.kind) {
      case 249 /* ForOfStatement */:
      case 248 /* ForInStatement */:
        changes.replaceNode(sourceFile, node, factory.createObjectLiteralExpression());
        break;
      case 247 /* ForStatement */:
        deleteNode(changes, sourceFile, parent2);
        break;
      case 242 /* VariableStatement */:
        deleteNode(changes, sourceFile, gp, { leadingTriviaOption: hasJSDocNodes(gp) ? 2 /* JSDoc */ : 3 /* StartLine */ });
        break;
      default:
        Debug.assertNever(gp);
    }
  }
})(deleteDeclaration || (deleteDeclaration = {}));
function deleteNode(changes, sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ }) {
  const startPosition = getAdjustedStartPosition(sourceFile, node, options);
  const endPosition = getAdjustedEndPosition(sourceFile, node, options);
  changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
  const containingList = Debug.checkDefined(ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile));
  const index = indexOfNode(containingList, node);
  Debug.assert(index !== -1);
  if (containingList.length === 1) {
    deleteNode(changes, sourceFile, node);
    return;
  }
  Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
  deletedNodesInLists.add(node);
  changes.deleteRange(sourceFile, {
    pos: startPositionToDeleteNodeInList(sourceFile, node),
    end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1])
  });
}

// src/services/_namespaces/ts.formatting.ts
var ts_formatting_exports = {};
__export(ts_formatting_exports, {
  FormattingContext: () => FormattingContext,
  FormattingRequestKind: () => FormattingRequestKind,
  RuleAction: () => RuleAction,
  RuleFlags: () => RuleFlags,
  SmartIndenter: () => SmartIndenter,
  anyContext: () => anyContext,
  createTextRangeWithKind: () => createTextRangeWithKind,
  formatDocument: () => formatDocument,
  formatNodeGivenIndentation: () => formatNodeGivenIndentation,
  formatOnClosingCurly: () => formatOnClosingCurly,
  formatOnEnter: () => formatOnEnter,
  formatOnOpeningCurly: () => formatOnOpeningCurly,
  formatOnSemicolon: () => formatOnSemicolon,
  formatSelection: () => formatSelection,
  getAllRules: () => getAllRules,
  getFormatContext: () => getFormatContext,
  getFormattingScanner: () => getFormattingScanner,
  getIndentationString: () => getIndentationString,
  getRangeOfEnclosingComment: () => getRangeOfEnclosingComment
});

// src/services/formatting/formattingContext.ts
var FormattingRequestKind = /* @__PURE__ */ ((FormattingRequestKind2) => {
  FormattingRequestKind2[FormattingRequestKind2["FormatDocument"] = 0] = "FormatDocument";
  FormattingRequestKind2[FormattingRequestKind2["FormatSelection"] = 1] = "FormatSelection";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnEnter"] = 2] = "FormatOnEnter";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnSemicolon"] = 3] = "FormatOnSemicolon";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace";
  FormattingRequestKind2[FormattingRequestKind2["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace";
  return FormattingRequestKind2;
})(FormattingRequestKind || {});
var FormattingContext = class {
  constructor(sourceFile, formattingRequestKind, options) {
    this.sourceFile = sourceFile;
    this.formattingRequestKind = formattingRequestKind;
    this.options = options;
  }
  updateContext(currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
    this.currentTokenSpan = Debug.checkDefined(currentRange);
    this.currentTokenParent = Debug.checkDefined(currentTokenParent);
    this.nextTokenSpan = Debug.checkDefined(nextRange);
    this.nextTokenParent = Debug.checkDefined(nextTokenParent);
    this.contextNode = Debug.checkDefined(commonParent);
    this.contextNodeAllOnSameLine = void 0;
    this.nextNodeAllOnSameLine = void 0;
    this.tokensAreOnSameLine = void 0;
    this.contextNodeBlockIsOnOneLine = void 0;
    this.nextNodeBlockIsOnOneLine = void 0;
  }
  ContextNodeAllOnSameLine() {
    if (this.contextNodeAllOnSameLine === void 0) {
      this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
    }
    return this.contextNodeAllOnSameLine;
  }
  NextNodeAllOnSameLine() {
    if (this.nextNodeAllOnSameLine === void 0) {
      this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
    }
    return this.nextNodeAllOnSameLine;
  }
  TokensAreOnSameLine() {
    if (this.tokensAreOnSameLine === void 0) {
      const startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
      const endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
      this.tokensAreOnSameLine = startLine === endLine;
    }
    return this.tokensAreOnSameLine;
  }
  ContextNodeBlockIsOnOneLine() {
    if (this.contextNodeBlockIsOnOneLine === void 0) {
      this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
    }
    return this.contextNodeBlockIsOnOneLine;
  }
  NextNodeBlockIsOnOneLine() {
    if (this.nextNodeBlockIsOnOneLine === void 0) {
      this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
    }
    return this.nextNodeBlockIsOnOneLine;
  }
  NodeIsOnOneLine(node) {
    const startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
    const endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
    return startLine === endLine;
  }
  BlockIsOnOneLine(node) {
    const openBrace = findChildOfKind(node, 19 /* OpenBraceToken */, this.sourceFile);
    const closeBrace = findChildOfKind(node, 20 /* CloseBraceToken */, this.sourceFile);
    if (openBrace && closeBrace) {
      const startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
      const endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
      return startLine === endLine;
    }
    return false;
  }
};

// src/services/formatting/formattingScanner.ts
var standardScanner = createScanner(
  99 /* Latest */,
  /*skipTrivia*/
  false,
  0 /* Standard */
);
var jsxScanner = createScanner(
  99 /* Latest */,
  /*skipTrivia*/
  false,
  1 /* JSX */
);
function getFormattingScanner(text, languageVariant, startPos, endPos, cb) {
  const scanner2 = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
  scanner2.setText(text);
  scanner2.resetTokenState(startPos);
  let wasNewLine = true;
  let leadingTrivia;
  let trailingTrivia;
  let savedPos;
  let lastScanAction;
  let lastTokenInfo;
  const res = cb({
    advance,
    readTokenInfo,
    readEOFTokenRange,
    isOnToken,
    isOnEOF,
    getCurrentLeadingTrivia: () => leadingTrivia,
    lastTrailingTriviaWasNewLine: () => wasNewLine,
    skipToEndOf,
    skipToStartOf,
    getTokenFullStart: () => (lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart(),
    getStartPos: () => (lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart()
  });
  lastTokenInfo = void 0;
  scanner2.setText(void 0);
  return res;
  function advance() {
    lastTokenInfo = void 0;
    const isStarted = scanner2.getTokenFullStart() !== startPos;
    if (isStarted) {
      wasNewLine = !!trailingTrivia && last(trailingTrivia).kind === 4 /* NewLineTrivia */;
    } else {
      scanner2.scan();
    }
    leadingTrivia = void 0;
    trailingTrivia = void 0;
    let pos = scanner2.getTokenFullStart();
    while (pos < endPos) {
      const t = scanner2.getToken();
      if (!isTrivia(t)) {
        break;
      }
      scanner2.scan();
      const item = {
        pos,
        end: scanner2.getTokenFullStart(),
        kind: t
      };
      pos = scanner2.getTokenFullStart();
      leadingTrivia = append(leadingTrivia, item);
    }
    savedPos = scanner2.getTokenFullStart();
  }
  function shouldRescanGreaterThanToken(node) {
    switch (node.kind) {
      case 34 /* GreaterThanEqualsToken */:
      case 72 /* GreaterThanGreaterThanEqualsToken */:
      case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
      case 49 /* GreaterThanGreaterThanToken */:
        return true;
    }
    return false;
  }
  function shouldRescanJsxIdentifier(node) {
    if (node.parent) {
      switch (node.parent.kind) {
        case 290 /* JsxAttribute */:
        case 285 /* JsxOpeningElement */:
        case 286 /* JsxClosingElement */:
        case 284 /* JsxSelfClosingElement */:
          return isKeyword(node.kind) || node.kind === 80 /* Identifier */;
      }
    }
    return false;
  }
  function shouldRescanJsxText(node) {
    return isJsxText(node) || isJsxElement(node) && (lastTokenInfo == null ? void 0 : lastTokenInfo.token.kind) === 12 /* JsxText */;
  }
  function shouldRescanSlashToken(container) {
    return container.kind === 14 /* RegularExpressionLiteral */;
  }
  function shouldRescanTemplateToken(container) {
    return container.kind === 17 /* TemplateMiddle */ || container.kind === 18 /* TemplateTail */;
  }
  function shouldRescanJsxAttributeValue(node) {
    return node.parent && isJsxAttribute(node.parent) && node.parent.initializer === node;
  }
  function startsWithSlashToken(t) {
    return t === 44 /* SlashToken */ || t === 69 /* SlashEqualsToken */;
  }
  function readTokenInfo(n) {
    Debug.assert(isOnToken());
    const expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ : shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ : shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ : shouldRescanJsxText(n) ? 5 /* RescanJsxText */ : shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ : 0 /* Scan */;
    if (lastTokenInfo && expectedScanAction === lastScanAction) {
      return fixTokenKind(lastTokenInfo, n);
    }
    if (scanner2.getTokenFullStart() !== savedPos) {
      Debug.assert(lastTokenInfo !== void 0);
      scanner2.resetTokenState(savedPos);
      scanner2.scan();
    }
    let currentToken = getNextToken(n, expectedScanAction);
    const token = createTextRangeWithKind(
      scanner2.getTokenFullStart(),
      scanner2.getTokenEnd(),
      currentToken
    );
    if (trailingTrivia) {
      trailingTrivia = void 0;
    }
    while (scanner2.getTokenFullStart() < endPos) {
      currentToken = scanner2.scan();
      if (!isTrivia(currentToken)) {
        break;
      }
      const trivia = createTextRangeWithKind(
        scanner2.getTokenFullStart(),
        scanner2.getTokenEnd(),
        currentToken
      );
      if (!trailingTrivia) {
        trailingTrivia = [];
      }
      trailingTrivia.push(trivia);
      if (currentToken === 4 /* NewLineTrivia */) {
        scanner2.scan();
        break;
      }
    }
    lastTokenInfo = { leadingTrivia, trailingTrivia, token };
    return fixTokenKind(lastTokenInfo, n);
  }
  function getNextToken(n, expectedScanAction) {
    const token = scanner2.getToken();
    lastScanAction = 0 /* Scan */;
    switch (expectedScanAction) {
      case 1 /* RescanGreaterThanToken */:
        if (token === 32 /* GreaterThanToken */) {
          lastScanAction = 1 /* RescanGreaterThanToken */;
          const newToken = scanner2.reScanGreaterToken();
          Debug.assert(n.kind === newToken);
          return newToken;
        }
        break;
      case 2 /* RescanSlashToken */:
        if (startsWithSlashToken(token)) {
          lastScanAction = 2 /* RescanSlashToken */;
          const newToken = scanner2.reScanSlashToken();
          Debug.assert(n.kind === newToken);
          return newToken;
        }
        break;
      case 3 /* RescanTemplateToken */:
        if (token === 20 /* CloseBraceToken */) {
          lastScanAction = 3 /* RescanTemplateToken */;
          return scanner2.reScanTemplateToken(
            /*isTaggedTemplate*/
            false
          );
        }
        break;
      case 4 /* RescanJsxIdentifier */:
        lastScanAction = 4 /* RescanJsxIdentifier */;
        return scanner2.scanJsxIdentifier();
      case 5 /* RescanJsxText */:
        lastScanAction = 5 /* RescanJsxText */;
        return scanner2.reScanJsxToken(
          /*allowMultilineJsxText*/
          false
        );
      case 6 /* RescanJsxAttributeValue */:
        lastScanAction = 6 /* RescanJsxAttributeValue */;
        return scanner2.reScanJsxAttributeValue();
      case 0 /* Scan */:
        break;
      default:
        Debug.assertNever(expectedScanAction);
    }
    return token;
  }
  function readEOFTokenRange() {
    Debug.assert(isOnEOF());
    return createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), 1 /* EndOfFileToken */);
  }
  function isOnToken() {
    const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken();
    return current !== 1 /* EndOfFileToken */ && !isTrivia(current);
  }
  function isOnEOF() {
    const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken();
    return current === 1 /* EndOfFileToken */;
  }
  function fixTokenKind(tokenInfo, container) {
    if (isToken(container) && tokenInfo.token.kind !== container.kind) {
      tokenInfo.token.kind = container.kind;
    }
    return tokenInfo;
  }
  function skipToEndOf(node) {
    scanner2.resetTokenState(node.end);
    savedPos = scanner2.getTokenFullStart();
    lastScanAction = void 0;
    lastTokenInfo = void 0;
    wasNewLine = false;
    leadingTrivia = void 0;
    trailingTrivia = void 0;
  }
  function skipToStartOf(node) {
    scanner2.resetTokenState(node.pos);
    savedPos = scanner2.getTokenFullStart();
    lastScanAction = void 0;
    lastTokenInfo = void 0;
    wasNewLine = false;
    leadingTrivia = void 0;
    trailingTrivia = void 0;
  }
}

// src/services/formatting/rule.ts
var anyContext = emptyArray;
var RuleAction = /* @__PURE__ */ ((RuleAction2) => {
  RuleAction2[RuleAction2["None"] = 0] = "None";
  RuleAction2[RuleAction2["StopProcessingSpaceActions"] = 1] = "StopProcessingSpaceActions";
  RuleAction2[RuleAction2["StopProcessingTokenActions"] = 2] = "StopProcessingTokenActions";
  RuleAction2[RuleAction2["InsertSpace"] = 4] = "InsertSpace";
  RuleAction2[RuleAction2["InsertNewLine"] = 8] = "InsertNewLine";
  RuleAction2[RuleAction2["DeleteSpace"] = 16] = "DeleteSpace";
  RuleAction2[RuleAction2["DeleteToken"] = 32] = "DeleteToken";
  RuleAction2[RuleAction2["InsertTrailingSemicolon"] = 64] = "InsertTrailingSemicolon";
  RuleAction2[RuleAction2["StopAction"] = 3] = "StopAction";
  RuleAction2[RuleAction2["ModifySpaceAction"] = 28] = "ModifySpaceAction";
  RuleAction2[RuleAction2["ModifyTokenAction"] = 96] = "ModifyTokenAction";
  return RuleAction2;
})(RuleAction || {});
var RuleFlags = /* @__PURE__ */ ((RuleFlags2) => {
  RuleFlags2[RuleFlags2["None"] = 0] = "None";
  RuleFlags2[RuleFlags2["CanDeleteNewLines"] = 1] = "CanDeleteNewLines";
  return RuleFlags2;
})(RuleFlags || {});

// src/services/formatting/rules.ts
function getAllRules() {
  const allTokens = [];
  for (let token = 0 /* FirstToken */; token <= 164 /* LastToken */; token++) {
    if (token !== 1 /* EndOfFileToken */) {
      allTokens.push(token);
    }
  }
  function anyTokenExcept(...tokens) {
    return { tokens: allTokens.filter((t) => !tokens.some((t2) => t2 === t)), isSpecific: false };
  }
  const anyToken = { tokens: allTokens, isSpecific: false };
  const anyTokenIncludingMultilineComments = tokenRangeFrom([...allTokens, 3 /* MultiLineCommentTrivia */]);
  const anyTokenIncludingEOF = tokenRangeFrom([...allTokens, 1 /* EndOfFileToken */]);
  const keywords = tokenRangeFromRange(83 /* FirstKeyword */, 164 /* LastKeyword */);
  const binaryOperators = tokenRangeFromRange(30 /* FirstBinaryOperator */, 79 /* LastBinaryOperator */);
  const binaryKeywordOperators = [
    103 /* InKeyword */,
    104 /* InstanceOfKeyword */,
    164 /* OfKeyword */,
    130 /* AsKeyword */,
    142 /* IsKeyword */,
    152 /* SatisfiesKeyword */
  ];
  const unaryPrefixOperators = [46 /* PlusPlusToken */, 47 /* MinusMinusToken */, 55 /* TildeToken */, 54 /* ExclamationToken */];
  const unaryPrefixExpressions = [
    9 /* NumericLiteral */,
    10 /* BigIntLiteral */,
    80 /* Identifier */,
    21 /* OpenParenToken */,
    23 /* OpenBracketToken */,
    19 /* OpenBraceToken */,
    110 /* ThisKeyword */,
    105 /* NewKeyword */
  ];
  const unaryPreincrementExpressions = [80 /* Identifier */, 21 /* OpenParenToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */];
  const unaryPostincrementExpressions = [80 /* Identifier */, 22 /* CloseParenToken */, 24 /* CloseBracketToken */, 105 /* NewKeyword */];
  const unaryPredecrementExpressions = [80 /* Identifier */, 21 /* OpenParenToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */];
  const unaryPostdecrementExpressions = [80 /* Identifier */, 22 /* CloseParenToken */, 24 /* CloseBracketToken */, 105 /* NewKeyword */];
  const comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
  const typeNames = [80 /* Identifier */, ...typeKeywords];
  const functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
  const typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([80 /* Identifier */, 3 /* MultiLineCommentTrivia */, 86 /* ClassKeyword */, 95 /* ExportKeyword */, 102 /* ImportKeyword */]);
  const controlOpenBraceLeftTokenRange = tokenRangeFrom([22 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 92 /* DoKeyword */, 113 /* TryKeyword */, 98 /* FinallyKeyword */, 93 /* ElseKeyword */]);
  const highPriorityCommonRules = [
    // Leave comments alone
    rule("IgnoreBeforeComment", anyToken, comments, anyContext, 1 /* StopProcessingSpaceActions */),
    rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, anyContext, 1 /* StopProcessingSpaceActions */),
    rule("NotSpaceBeforeColon", anyToken, 59 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
    rule("SpaceAfterColon", 59 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeQuestionMark", anyToken, 58 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
    // insert space after '?' only when it is used in conditional operator
    rule("SpaceAfterQuestionMarkInConditionalOperator", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */),
    // in other cases there should be no space between '?' and next token
    rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeDot", anyToken, [25 /* DotToken */, 29 /* QuestionDotToken */], [isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral], 16 /* DeleteSpace */),
    rule("NoSpaceAfterDot", [25 /* DotToken */, 29 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBetweenImportParenInImportType", 102 /* ImportKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */),
    // Special handling of unary operators.
    // Prefix operators generally shouldn't have a space between
    // them and their target unary expression.
    rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterUnaryPreincrementOperator", 46 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterUnaryPredecrementOperator", 47 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
    // More unary operator special-casing.
    // DevDiv 181814: Be careful when removing leading whitespace
    // around unary operators.  Examples:
    //      1 - -2  --X--> 1--2
    //      a + ++b --X--> a+++b
    rule("SpaceAfterPostincrementWhenFollowedByAdd", 46 /* PlusPlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterAddWhenFollowedByUnaryPlus", 40 /* PlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterAddWhenFollowedByPreincrement", 40 /* PlusToken */, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 47 /* MinusMinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 41 /* MinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterSubtractWhenFollowedByPredecrement", 41 /* MinusToken */, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterCloseBrace", 20 /* CloseBraceToken */, [28 /* CommaToken */, 27 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // For functions and control block place } on a new line [multi-line rule]
    rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 20 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */),
    // Space/new line after }.
    rule("SpaceAfterCloseBrace", 20 /* CloseBraceToken */, anyTokenExcept(22 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */),
    // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
    // Also should not apply to })
    rule("SpaceBetweenCloseBraceAndElse", 20 /* CloseBraceToken */, 93 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBetweenCloseBraceAndWhile", 20 /* CloseBraceToken */, 117 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
    // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];'
    rule("SpaceAfterConditionalClosingParen", 22 /* CloseParenToken */, 23 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenFunctionKeywordAndStar", 100 /* FunctionKeyword */, 42 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */),
    rule("SpaceAfterStarInGeneratorDeclaration", 42 /* AsteriskToken */, 80 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */),
    rule("SpaceAfterFunctionInFuncDecl", 100 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */),
    // Insert new line after { and before } in multi-line contexts.
    rule("NewLineAfterOpenBraceInBlockContext", 19 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */),
    // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token.
    // Though, we do extra check on the context to make sure we are dealing with get/set node. Example:
    //      get x() {}
    //      set x(val) {}
    rule("SpaceAfterGetSetInMember", [139 /* GetKeyword */, 153 /* SetKeyword */], 80 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenYieldKeywordAndStar", 127 /* YieldKeyword */, 42 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */),
    rule("SpaceBetweenYieldOrYieldStarAndOperand", [127 /* YieldKeyword */, 42 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */),
    rule("NoSpaceBetweenReturnAndSemicolon", 107 /* ReturnKeyword */, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("SpaceAfterCertainKeywords", [115 /* VarKeyword */, 111 /* ThrowKeyword */, 105 /* NewKeyword */, 91 /* DeleteKeyword */, 107 /* ReturnKeyword */, 114 /* TypeOfKeyword */, 135 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceAfterLetConstInVariableDeclaration", [121 /* LetKeyword */, 87 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */),
    rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */),
    // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
    rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterVoidOperator", 116 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */),
    // Async-await
    rule("SpaceBetweenAsyncAndOpenParen", 134 /* AsyncKeyword */, 21 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBetweenAsyncAndFunctionKeyword", 134 /* AsyncKeyword */, [100 /* FunctionKeyword */, 80 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Template string
    rule("NoSpaceBetweenTagAndTemplateString", [80 /* Identifier */, 22 /* CloseParenToken */], [15 /* NoSubstitutionTemplateLiteral */, 16 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // JSX opening elements
    rule("SpaceBeforeJsxAttribute", anyToken, 80 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 44 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 44 /* SlashToken */, 32 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 64 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterEqualInJsxAttribute", 64 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // TypeScript-specific rules
    // Use of module as a function call. e.g.: import m2 = module("m2");
    rule("NoSpaceAfterModuleImport", [144 /* ModuleKeyword */, 149 /* RequireKeyword */], 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Add a space around certain TypeScript keywords
    rule(
      "SpaceAfterCertainTypeScriptKeywords",
      [
        128 /* AbstractKeyword */,
        129 /* AccessorKeyword */,
        86 /* ClassKeyword */,
        138 /* DeclareKeyword */,
        90 /* DefaultKeyword */,
        94 /* EnumKeyword */,
        95 /* ExportKeyword */,
        96 /* ExtendsKeyword */,
        139 /* GetKeyword */,
        119 /* ImplementsKeyword */,
        102 /* ImportKeyword */,
        120 /* InterfaceKeyword */,
        144 /* ModuleKeyword */,
        145 /* NamespaceKeyword */,
        123 /* PrivateKeyword */,
        125 /* PublicKeyword */,
        124 /* ProtectedKeyword */,
        148 /* ReadonlyKeyword */,
        153 /* SetKeyword */,
        126 /* StaticKeyword */,
        156 /* TypeKeyword */,
        160 /* FromKeyword */,
        143 /* KeyOfKeyword */,
        140 /* InferKeyword */
      ],
      anyToken,
      [isNonJsxSameLineTokenContext],
      4 /* InsertSpace */
    ),
    rule(
      "SpaceBeforeCertainTypeScriptKeywords",
      anyToken,
      [96 /* ExtendsKeyword */, 119 /* ImplementsKeyword */, 160 /* FromKeyword */],
      [isNonJsxSameLineTokenContext],
      4 /* InsertSpace */
    ),
    // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
    rule("SpaceAfterModuleName", 11 /* StringLiteral */, 19 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */),
    // Lambda expressions
    rule("SpaceBeforeArrow", anyToken, 39 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceAfterArrow", 39 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Optional parameters and let args
    rule("NoSpaceAfterEllipsis", 26 /* DotDotDotToken */, 80 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOptionalParameters", 58 /* QuestionToken */, [22 /* CloseParenToken */, 28 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
    // Remove spaces in empty interface literals. e.g.: x: {}
    rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */),
    // generics and type assertions
    rule("NoSpaceBeforeOpenAngularBracket", typeNames, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBetweenCloseParenAndAngularBracket", 22 /* CloseParenToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenAngularBracket", 30 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseAngularBracket", anyToken, 32 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterCloseAngularBracket", 32 /* GreaterThanToken */, [21 /* OpenParenToken */, 23 /* OpenBracketToken */, 32 /* GreaterThanToken */, 28 /* CommaToken */], [
      isNonJsxSameLineTokenContext,
      isTypeArgumentOrParameterOrAssertionContext,
      isNotFunctionDeclContext,
      isNonTypeAssertionContext
    ], 16 /* DeleteSpace */),
    // decorators
    rule("SpaceBeforeAt", [22 /* CloseParenToken */, 80 /* Identifier */], 60 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterAt", 60 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert space after @ in decorator
    rule(
      "SpaceAfterDecorator",
      anyToken,
      [
        128 /* AbstractKeyword */,
        80 /* Identifier */,
        95 /* ExportKeyword */,
        90 /* DefaultKeyword */,
        86 /* ClassKeyword */,
        126 /* StaticKeyword */,
        125 /* PublicKeyword */,
        123 /* PrivateKeyword */,
        124 /* ProtectedKeyword */,
        139 /* GetKeyword */,
        153 /* SetKeyword */,
        23 /* OpenBracketToken */,
        42 /* AsteriskToken */
      ],
      [isEndOfDecoratorContextOnSameLine],
      4 /* InsertSpace */
    ),
    rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 54 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterNewKeywordOnConstructorSignature", 105 /* NewKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */),
    rule("SpaceLessThanAndNonJSXTypeAnnotation", 30 /* LessThanToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */)
  ];
  const userConfigurableRules = [
    // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
    rule("SpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("SpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */),
    rule("NoSpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */),
    // Insert space after function keyword for anonymous functions
    rule("SpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */),
    // Insert space after keywords in control flow statements
    rule("SpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */),
    // Insert space after opening and before closing nonempty parenthesis
    rule("SpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBetweenOpenParens", 21 /* OpenParenToken */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenParens", 21 /* OpenParenToken */, 22 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert space after opening and before closing nonempty brackets
    rule("SpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenBrackets", 23 /* OpenBracketToken */, 24 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
    rule("SpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
    rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert a space after opening and before closing empty brace brackets
    rule("SpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */),
    rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // Insert space after opening and before closing template string braces
    rule("SpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 16 /* DeleteSpace */, 1 /* CanDeleteNewLines */),
    rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // No space after { and before } in JSX expression
    rule("SpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
    rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
    rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
    // Insert space after semicolon in for statement
    rule("SpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */),
    // Insert space before and after binary operators
    rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
    rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */),
    // Open Brace braces after control block
    rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
    // Open Brace braces after function
    // TypeScript: Function can have return types, which can be made of tons of different token kinds
    rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
    // Open Brace braces after TypeScript module/class/interface
    rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
    rule("SpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */),
    rule("NoSpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */),
    rule("SpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */),
    rule("NoSpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */),
    rule("NoOptionalSemicolon", 27 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", "remove" /* Remove */), isSemicolonDeletionContext], 32 /* DeleteToken */),
    rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", "insert" /* Insert */), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */)
  ];
  const lowPriorityCommonRules = [
    // Space after keyword but not before ; or : or ?
    rule("NoSpaceBeforeSemicolon", anyToken, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
    rule("NoSpaceBeforeComma", anyToken, 28 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    // No space before and after indexer `x[]`
    rule("NoSpaceBeforeOpenBracket", anyTokenExcept(134 /* AsyncKeyword */, 84 /* CaseKeyword */), 23 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
    rule("NoSpaceAfterCloseBracket", 24 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */),
    rule("SpaceAfterSemicolon", 27 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Remove extra space between for and await
    rule("SpaceBetweenForAndAwaitKeyword", 99 /* ForKeyword */, 135 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
    // Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
    // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
    rule(
      "SpaceBetweenStatements",
      [22 /* CloseParenToken */, 92 /* DoKeyword */, 93 /* ElseKeyword */, 84 /* CaseKeyword */],
      anyToken,
      [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext],
      4 /* InsertSpace */
    ),
    // This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
    rule("SpaceAfterTryCatchFinally", [113 /* TryKeyword */, 85 /* CatchKeyword */, 98 /* FinallyKeyword */], 19 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */)
  ];
  return [
    ...highPriorityCommonRules,
    ...userConfigurableRules,
    ...lowPriorityCommonRules
  ];
}
function rule(debugName, left, right, context, action, flags = 0 /* None */) {
  return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName, context, action, flags } };
}
function tokenRangeFrom(tokens) {
  return { tokens, isSpecific: true };
}
function toTokenRange(arg) {
  return typeof arg === "number" ? tokenRangeFrom([arg]) : isArray(arg) ? tokenRangeFrom(arg) : arg;
}
function tokenRangeFromRange(from, to, except = []) {
  const tokens = [];
  for (let token = from; token <= to; token++) {
    if (!contains(except, token)) {
      tokens.push(token);
    }
  }
  return tokenRangeFrom(tokens);
}
function optionEquals(optionName, optionValue) {
  return (context) => context.options && context.options[optionName] === optionValue;
}
function isOptionEnabled(optionName) {
  return (context) => context.options && hasProperty(context.options, optionName) && !!context.options[optionName];
}
function isOptionDisabled(optionName) {
  return (context) => context.options && hasProperty(context.options, optionName) && !context.options[optionName];
}
function isOptionDisabledOrUndefined(optionName) {
  return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName];
}
function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) {
  return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine();
}
function isOptionEnabledOrUndefined(optionName) {
  return (context) => !context.options || !hasProperty(context.options, optionName) || !!context.options[optionName];
}
function isForContext(context) {
  return context.contextNode.kind === 247 /* ForStatement */;
}
function isNotForContext(context) {
  return !isForContext(context);
}
function isBinaryOpContext(context) {
  switch (context.contextNode.kind) {
    case 225 /* BinaryExpression */:
      return context.contextNode.operatorToken.kind !== 28 /* CommaToken */;
    case 226 /* ConditionalExpression */:
    case 193 /* ConditionalType */:
    case 233 /* AsExpression */:
    case 280 /* ExportSpecifier */:
    case 275 /* ImportSpecifier */:
    case 181 /* TypePredicate */:
    case 191 /* UnionType */:
    case 192 /* IntersectionType */:
    case 237 /* SatisfiesExpression */:
      return true;
    case 207 /* BindingElement */:
    case 264 /* TypeAliasDeclaration */:
    case 270 /* ImportEqualsDeclaration */:
    case 276 /* ExportAssignment */:
    case 259 /* VariableDeclaration */:
    case 168 /* Parameter */:
    case 305 /* EnumMember */:
    case 171 /* PropertyDeclaration */:
    case 170 /* PropertySignature */:
      return context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */;
    case 248 /* ForInStatement */:
    case 167 /* TypeParameter */:
      return context.currentTokenSpan.kind === 103 /* InKeyword */ || context.nextTokenSpan.kind === 103 /* InKeyword */ || context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */;
    case 249 /* ForOfStatement */:
      return context.currentTokenSpan.kind === 164 /* OfKeyword */ || context.nextTokenSpan.kind === 164 /* OfKeyword */;
  }
  return false;
}
function isNotBinaryOpContext(context) {
  return !isBinaryOpContext(context);
}
function isNotTypeAnnotationContext(context) {
  return !isTypeAnnotationContext(context);
}
function isTypeAnnotationContext(context) {
  const contextKind = context.contextNode.kind;
  return contextKind === 171 /* PropertyDeclaration */ || contextKind === 170 /* PropertySignature */ || contextKind === 168 /* Parameter */ || contextKind === 259 /* VariableDeclaration */ || isFunctionLikeKind(contextKind);
}
function isConditionalOperatorContext(context) {
  return context.contextNode.kind === 226 /* ConditionalExpression */ || context.contextNode.kind === 193 /* ConditionalType */;
}
function isSameLineTokenOrBeforeBlockContext(context) {
  return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
}
function isBraceWrappedContext(context) {
  return context.contextNode.kind === 205 /* ObjectBindingPattern */ || context.contextNode.kind === 199 /* MappedType */ || isSingleLineBlockContext(context);
}
function isBeforeMultilineBlockContext(context) {
  return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
}
function isMultilineBlockContext(context) {
  return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
}
function isSingleLineBlockContext(context) {
  return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
}
function isBlockContext(context) {
  return nodeIsBlockContext(context.contextNode);
}
function isBeforeBlockContext(context) {
  return nodeIsBlockContext(context.nextTokenParent);
}
function nodeIsBlockContext(node) {
  if (nodeIsTypeScriptDeclWithBlockContext(node)) {
    return true;
  }
  switch (node.kind) {
    case 240 /* Block */:
    case 268 /* CaseBlock */:
    case 209 /* ObjectLiteralExpression */:
    case 267 /* ModuleBlock */:
      return true;
  }
  return false;
}
function isFunctionDeclContext(context) {
  switch (context.contextNode.kind) {
    case 261 /* FunctionDeclaration */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
    case 178 /* CallSignature */:
    case 217 /* FunctionExpression */:
    case 175 /* Constructor */:
    case 218 /* ArrowFunction */:
    case 263 /* InterfaceDeclaration */:
      return true;
  }
  return false;
}
function isNotFunctionDeclContext(context) {
  return !isFunctionDeclContext(context);
}
function isFunctionDeclarationOrFunctionExpressionContext(context) {
  return context.contextNode.kind === 261 /* FunctionDeclaration */ || context.contextNode.kind === 217 /* FunctionExpression */;
}
function isTypeScriptDeclWithBlockContext(context) {
  return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
}
function nodeIsTypeScriptDeclWithBlockContext(node) {
  switch (node.kind) {
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
    case 263 /* InterfaceDeclaration */:
    case 265 /* EnumDeclaration */:
    case 186 /* TypeLiteral */:
    case 266 /* ModuleDeclaration */:
    case 277 /* ExportDeclaration */:
    case 278 /* NamedExports */:
    case 271 /* ImportDeclaration */:
    case 274 /* NamedImports */:
      return true;
  }
  return false;
}
function isAfterCodeBlockContext(context) {
  switch (context.currentTokenParent.kind) {
    case 262 /* ClassDeclaration */:
    case 266 /* ModuleDeclaration */:
    case 265 /* EnumDeclaration */:
    case 298 /* CatchClause */:
    case 267 /* ModuleBlock */:
    case 254 /* SwitchStatement */:
      return true;
    case 240 /* Block */: {
      const blockParent = context.currentTokenParent.parent;
      if (!blockParent || blockParent.kind !== 218 /* ArrowFunction */ && blockParent.kind !== 217 /* FunctionExpression */) {
        return true;
      }
    }
  }
  return false;
}
function isControlDeclContext(context) {
  switch (context.contextNode.kind) {
    case 244 /* IfStatement */:
    case 254 /* SwitchStatement */:
    case 247 /* ForStatement */:
    case 248 /* ForInStatement */:
    case 249 /* ForOfStatement */:
    case 246 /* WhileStatement */:
    case 257 /* TryStatement */:
    case 245 /* DoStatement */:
    case 253 /* WithStatement */:
    case 298 /* CatchClause */:
      return true;
    default:
      return false;
  }
}
function isObjectContext(context) {
  return context.contextNode.kind === 209 /* ObjectLiteralExpression */;
}
function isFunctionCallContext(context) {
  return context.contextNode.kind === 212 /* CallExpression */;
}
function isNewContext(context) {
  return context.contextNode.kind === 213 /* NewExpression */;
}
function isFunctionCallOrNewContext(context) {
  return isFunctionCallContext(context) || isNewContext(context);
}
function isPreviousTokenNotComma(context) {
  return context.currentTokenSpan.kind !== 28 /* CommaToken */;
}
function isNextTokenNotCloseBracket(context) {
  return context.nextTokenSpan.kind !== 24 /* CloseBracketToken */;
}
function isNextTokenNotCloseParen(context) {
  return context.nextTokenSpan.kind !== 22 /* CloseParenToken */;
}
function isArrowFunctionContext(context) {
  return context.contextNode.kind === 218 /* ArrowFunction */;
}
function isImportTypeContext(context) {
  return context.contextNode.kind === 204 /* ImportType */;
}
function isNonJsxSameLineTokenContext(context) {
  return context.TokensAreOnSameLine() && context.contextNode.kind !== 12 /* JsxText */;
}
function isNonJsxTextContext(context) {
  return context.contextNode.kind !== 12 /* JsxText */;
}
function isNonJsxElementOrFragmentContext(context) {
  return context.contextNode.kind !== 283 /* JsxElement */ && context.contextNode.kind !== 287 /* JsxFragment */;
}
function isJsxExpressionContext(context) {
  return context.contextNode.kind === 293 /* JsxExpression */ || context.contextNode.kind === 292 /* JsxSpreadAttribute */;
}
function isNextTokenParentJsxAttribute(context) {
  return context.nextTokenParent.kind === 290 /* JsxAttribute */;
}
function isJsxAttributeContext(context) {
  return context.contextNode.kind === 290 /* JsxAttribute */;
}
function isJsxSelfClosingElementContext(context) {
  return context.contextNode.kind === 284 /* JsxSelfClosingElement */;
}
function isNotBeforeBlockInFunctionDeclarationContext(context) {
  return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
}
function isEndOfDecoratorContextOnSameLine(context) {
  return context.TokensAreOnSameLine() && hasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent);
}
function nodeIsInDecoratorContext(node) {
  while (node && isExpression(node)) {
    node = node.parent;
  }
  return node && node.kind === 169 /* Decorator */;
}
function isStartOfVariableDeclarationList(context) {
  return context.currentTokenParent.kind === 260 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
}
function isNotFormatOnEnter(context) {
  return context.formattingRequestKind !== 2 /* FormatOnEnter */;
}
function isModuleDeclContext(context) {
  return context.contextNode.kind === 266 /* ModuleDeclaration */;
}
function isObjectTypeContext(context) {
  return context.contextNode.kind === 186 /* TypeLiteral */;
}
function isConstructorSignatureContext(context) {
  return context.contextNode.kind === 179 /* ConstructSignature */;
}
function isTypeArgumentOrParameterOrAssertion(token, parent2) {
  if (token.kind !== 30 /* LessThanToken */ && token.kind !== 32 /* GreaterThanToken */) {
    return false;
  }
  switch (parent2.kind) {
    case 182 /* TypeReference */:
    case 215 /* TypeAssertionExpression */:
    case 264 /* TypeAliasDeclaration */:
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
    case 263 /* InterfaceDeclaration */:
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 218 /* ArrowFunction */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 178 /* CallSignature */:
    case 179 /* ConstructSignature */:
    case 212 /* CallExpression */:
    case 213 /* NewExpression */:
    case 232 /* ExpressionWithTypeArguments */:
      return true;
    default:
      return false;
  }
}
function isTypeArgumentOrParameterOrAssertionContext(context) {
  return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
}
function isTypeAssertionContext(context) {
  return context.contextNode.kind === 215 /* TypeAssertionExpression */;
}
function isNonTypeAssertionContext(context) {
  return !isTypeAssertionContext(context);
}
function isVoidOpContext(context) {
  return context.currentTokenSpan.kind === 116 /* VoidKeyword */ && context.currentTokenParent.kind === 221 /* VoidExpression */;
}
function isYieldOrYieldStarWithOperand(context) {
  return context.contextNode.kind === 228 /* YieldExpression */ && context.contextNode.expression !== void 0;
}
function isNonNullAssertionContext(context) {
  return context.contextNode.kind === 234 /* NonNullExpression */;
}
function isNotStatementConditionContext(context) {
  return !isStatementConditionContext(context);
}
function isStatementConditionContext(context) {
  switch (context.contextNode.kind) {
    case 244 /* IfStatement */:
    case 247 /* ForStatement */:
    case 248 /* ForInStatement */:
    case 249 /* ForOfStatement */:
    case 245 /* DoStatement */:
    case 246 /* WhileStatement */:
      return true;
    default:
      return false;
  }
}
function isSemicolonDeletionContext(context) {
  let nextTokenKind = context.nextTokenSpan.kind;
  let nextTokenStart = context.nextTokenSpan.pos;
  if (isTrivia(nextTokenKind)) {
    const nextRealToken = context.nextTokenParent === context.currentTokenParent ? findNextToken(
      context.currentTokenParent,
      findAncestor(context.currentTokenParent, (a) => !a.parent),
      context.sourceFile
    ) : context.nextTokenParent.getFirstToken(context.sourceFile);
    if (!nextRealToken) {
      return true;
    }
    nextTokenKind = nextRealToken.kind;
    nextTokenStart = nextRealToken.getStart(context.sourceFile);
  }
  const startLine = context.sourceFile.getLineAndCharacterOfPosition(context.currentTokenSpan.pos).line;
  const endLine = context.sourceFile.getLineAndCharacterOfPosition(nextTokenStart).line;
  if (startLine === endLine) {
    return nextTokenKind === 20 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */;
  }
  if (nextTokenKind === 239 /* SemicolonClassElement */ || nextTokenKind === 27 /* SemicolonToken */) {
    return false;
  }
  if (context.contextNode.kind === 263 /* InterfaceDeclaration */ || context.contextNode.kind === 264 /* TypeAliasDeclaration */) {
    return !isPropertySignature(context.currentTokenParent) || !!context.currentTokenParent.type || nextTokenKind !== 21 /* OpenParenToken */;
  }
  if (isPropertyDeclaration(context.currentTokenParent)) {
    return !context.currentTokenParent.initializer;
  }
  return context.currentTokenParent.kind !== 247 /* ForStatement */ && context.currentTokenParent.kind !== 241 /* EmptyStatement */ && context.currentTokenParent.kind !== 239 /* SemicolonClassElement */ && nextTokenKind !== 23 /* OpenBracketToken */ && nextTokenKind !== 21 /* OpenParenToken */ && nextTokenKind !== 40 /* PlusToken */ && nextTokenKind !== 41 /* MinusToken */ && nextTokenKind !== 44 /* SlashToken */ && nextTokenKind !== 14 /* RegularExpressionLiteral */ && nextTokenKind !== 28 /* CommaToken */ && nextTokenKind !== 227 /* TemplateExpression */ && nextTokenKind !== 16 /* TemplateHead */ && nextTokenKind !== 15 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 25 /* DotToken */;
}
function isSemicolonInsertionContext(context) {
  return positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile);
}
function isNotPropertyAccessOnIntegerLiteral(context) {
  return !isPropertyAccessExpression(context.contextNode) || !isNumericLiteral(context.contextNode.expression) || context.contextNode.expression.getText().indexOf(".") !== -1;
}

// src/services/formatting/rulesMap.ts
function getFormatContext(options, host) {
  return { options, getRules: getRulesMap(), host };
}
var rulesMapCache;
function getRulesMap() {
  if (rulesMapCache === void 0) {
    rulesMapCache = createRulesMap(getAllRules());
  }
  return rulesMapCache;
}
function getRuleActionExclusion(ruleAction) {
  let mask2 = 0 /* None */;
  if (ruleAction & 1 /* StopProcessingSpaceActions */) {
    mask2 |= 28 /* ModifySpaceAction */;
  }
  if (ruleAction & 2 /* StopProcessingTokenActions */) {
    mask2 |= 96 /* ModifyTokenAction */;
  }
  if (ruleAction & 28 /* ModifySpaceAction */) {
    mask2 |= 28 /* ModifySpaceAction */;
  }
  if (ruleAction & 96 /* ModifyTokenAction */) {
    mask2 |= 96 /* ModifyTokenAction */;
  }
  return mask2;
}
function createRulesMap(rules) {
  const map2 = buildMap(rules);
  return (context) => {
    const bucket = map2[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)];
    if (bucket) {
      const rules2 = [];
      let ruleActionMask = 0;
      for (const rule2 of bucket) {
        const acceptRuleActions = ~getRuleActionExclusion(ruleActionMask);
        if (rule2.action & acceptRuleActions && every(rule2.context, (c) => c(context))) {
          rules2.push(rule2);
          ruleActionMask |= rule2.action;
        }
      }
      if (rules2.length) {
        return rules2;
      }
    }
  };
}
function buildMap(rules) {
  const map2 = new Array(mapRowLength * mapRowLength);
  const rulesBucketConstructionStateList = new Array(map2.length);
  for (const rule2 of rules) {
    const specificRule = rule2.leftTokenRange.isSpecific && rule2.rightTokenRange.isSpecific;
    for (const left of rule2.leftTokenRange.tokens) {
      for (const right of rule2.rightTokenRange.tokens) {
        const index = getRuleBucketIndex(left, right);
        let rulesBucket = map2[index];
        if (rulesBucket === void 0) {
          rulesBucket = map2[index] = [];
        }
        addRule(rulesBucket, rule2.rule, specificRule, rulesBucketConstructionStateList, index);
      }
    }
  }
  return map2;
}
function getRuleBucketIndex(row, column) {
  Debug.assert(row <= 164 /* LastKeyword */ && column <= 164 /* LastKeyword */, "Must compute formatting context from tokens");
  return row * mapRowLength + column;
}
var maskBitSize = 5;
var mask = 31;
var mapRowLength = 164 /* LastToken */ + 1;
var RulesPosition = ((RulesPosition2) => {
  RulesPosition2[RulesPosition2["StopRulesSpecific"] = 0] = "StopRulesSpecific";
  RulesPosition2[RulesPosition2["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny";
  RulesPosition2[RulesPosition2["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific";
  RulesPosition2[RulesPosition2["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny";
  RulesPosition2[RulesPosition2["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific";
  RulesPosition2[RulesPosition2["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny";
  return RulesPosition2;
})(RulesPosition || {});
function addRule(rules, rule2, specificTokens, constructionState, rulesBucketIndex) {
  const position = rule2.action & 3 /* StopAction */ ? specificTokens ? 0 /* StopRulesSpecific */ : RulesPosition.StopRulesAny : rule2.context !== anyContext ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny;
  const state = constructionState[rulesBucketIndex] || 0;
  rules.splice(getInsertionIndex(state, position), 0, rule2);
  constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position);
}
function getInsertionIndex(indexBitmap, maskPosition) {
  let index = 0;
  for (let pos = 0; pos <= maskPosition; pos += maskBitSize) {
    index += indexBitmap & mask;
    indexBitmap >>= maskBitSize;
  }
  return index;
}
function increaseInsertionIndex(indexBitmap, maskPosition) {
  const value = (indexBitmap >> maskPosition & mask) + 1;
  Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
  return indexBitmap & ~(mask << maskPosition) | value << maskPosition;
}

// src/services/formatting/formatting.ts
function createTextRangeWithKind(pos, end, kind) {
  const textRangeWithKind = { pos, end, kind };
  if (Debug.isDebugging) {
    Object.defineProperty(textRangeWithKind, "__debugKind", {
      get: () => Debug.formatSyntaxKind(kind)
    });
  }
  return textRangeWithKind;
}
function formatOnEnter(position, sourceFile, formatContext) {
  const line = sourceFile.getLineAndCharacterOfPosition(position).line;
  if (line === 0) {
    return [];
  }
  let endOfFormatSpan = getEndLinePosition(line, sourceFile);
  while (isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
    endOfFormatSpan--;
  }
  if (isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
    endOfFormatSpan--;
  }
  const span = {
    // get start position for the previous line
    pos: getStartPositionOfLine(line - 1, sourceFile),
    // end value is exclusive so add 1 to the result
    end: endOfFormatSpan + 1
  };
  return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */);
}
function formatOnSemicolon(position, sourceFile, formatContext) {
  const semicolon = findImmediatelyPrecedingTokenOfKind(position, 27 /* SemicolonToken */, sourceFile);
  return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */);
}
function formatOnOpeningCurly(position, sourceFile, formatContext) {
  const openingCurly = findImmediatelyPrecedingTokenOfKind(position, 19 /* OpenBraceToken */, sourceFile);
  if (!openingCurly) {
    return [];
  }
  const curlyBraceRange = openingCurly.parent;
  const outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
  const textRange = {
    pos: getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile),
    // TODO: GH#18217
    end: position
  };
  return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */);
}
function formatOnClosingCurly(position, sourceFile, formatContext) {
  const precedingToken = findImmediatelyPrecedingTokenOfKind(position, 20 /* CloseBraceToken */, sourceFile);
  return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */);
}
function formatDocument(sourceFile, formatContext) {
  const span = {
    pos: 0,
    end: sourceFile.text.length
  };
  return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */);
}
function formatSelection(start2, end, sourceFile, formatContext) {
  const span = {
    pos: getLineStartPositionForPosition(start2, sourceFile),
    end
  };
  return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */);
}
function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) {
  const precedingToken = findPrecedingToken(end, sourceFile);
  return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? precedingToken : void 0;
}
function findOutermostNodeWithinListLevel(node) {
  let current = node;
  while (current && current.parent && current.parent.end === node.end && !isListElement(current.parent, current)) {
    current = current.parent;
  }
  return current;
}
function isListElement(parent2, node) {
  switch (parent2.kind) {
    case 262 /* ClassDeclaration */:
    case 263 /* InterfaceDeclaration */:
      return rangeContainsRange(parent2.members, node);
    case 266 /* ModuleDeclaration */:
      const body = parent2.body;
      return !!body && body.kind === 267 /* ModuleBlock */ && rangeContainsRange(body.statements, node);
    case 311 /* SourceFile */:
    case 240 /* Block */:
    case 267 /* ModuleBlock */:
      return rangeContainsRange(parent2.statements, node);
    case 298 /* CatchClause */:
      return rangeContainsRange(parent2.block.statements, node);
  }
  return false;
}
function findEnclosingNode(range, sourceFile) {
  return find2(sourceFile);
  function find2(n) {
    const candidate = forEachChild(n, (c) => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c);
    if (candidate) {
      const result = find2(candidate);
      if (result) {
        return result;
      }
    }
    return n;
  }
}
function prepareRangeContainsErrorFunction(errors, originalRange) {
  if (!errors.length) {
    return rangeHasNoErrors;
  }
  const sorted = errors.filter((d) => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length)).sort((e1, e2) => e1.start - e2.start);
  if (!sorted.length) {
    return rangeHasNoErrors;
  }
  let index = 0;
  return (r) => {
    while (true) {
      if (index >= sorted.length) {
        return false;
      }
      const error = sorted[index];
      if (r.end <= error.start) {
        return false;
      }
      if (startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {
        return true;
      }
      index++;
    }
  };
  function rangeHasNoErrors() {
    return false;
  }
}
function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
  const start2 = enclosingNode.getStart(sourceFile);
  if (start2 === originalRange.pos && enclosingNode.end === originalRange.end) {
    return start2;
  }
  const precedingToken = findPrecedingToken(originalRange.pos, sourceFile);
  if (!precedingToken) {
    return enclosingNode.pos;
  }
  if (precedingToken.end >= originalRange.pos) {
    return enclosingNode.pos;
  }
  return precedingToken.end;
}
function getOwnOrInheritedDelta(n, options, sourceFile) {
  let previousLine = -1 /* Unknown */;
  let child;
  while (n) {
    const line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
    if (previousLine !== -1 /* Unknown */ && line !== previousLine) {
      break;
    }
    if (SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
      return options.indentSize;
    }
    previousLine = line;
    child = n;
    n = n.parent;
  }
  return 0;
}
function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) {
  const range = { pos: node.pos, end: node.end };
  return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, (scanner2) => formatSpanWorker(
    range,
    node,
    initialIndentation,
    delta,
    scanner2,
    formatContext,
    1 /* FormatSelection */,
    (_) => false,
    // assume that node does not have any errors
    sourceFileLike
  ));
}
function formatNodeLines(node, sourceFile, formatContext, requestKind) {
  if (!node) {
    return [];
  }
  const span = {
    pos: getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
    end: node.end
  };
  return formatSpan(span, sourceFile, formatContext, requestKind);
}
function formatSpan(originalRange, sourceFile, formatContext, requestKind) {
  const enclosingNode = findEnclosingNode(originalRange, sourceFile);
  return getFormattingScanner(
    sourceFile.text,
    sourceFile.languageVariant,
    getScanStartPosition(enclosingNode, originalRange, sourceFile),
    originalRange.end,
    (scanner2) => formatSpanWorker(
      originalRange,
      enclosingNode,
      SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options),
      getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile),
      scanner2,
      formatContext,
      requestKind,
      prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange),
      sourceFile
    )
  );
}
function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, { options, getRules, host }, requestKind, rangeContainsError, sourceFile) {
  var _a;
  const formattingContext = new FormattingContext(sourceFile, requestKind, options);
  let previousRangeTriviaEnd;
  let previousRange;
  let previousParent;
  let previousRangeStartLine;
  let lastIndentedLine;
  let indentationOnLastIndentedLine = -1 /* Unknown */;
  const edits = [];
  formattingScanner.advance();
  if (formattingScanner.isOnToken()) {
    const startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
    let undecoratedStartLine = startLine;
    if (hasDecorators(enclosingNode)) {
      undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
    }
    processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
  }
  if (!formattingScanner.isOnToken()) {
    const indentation = SmartIndenter.nodeWillIndentChild(
      options,
      enclosingNode,
      /*child*/
      void 0,
      sourceFile,
      /*indentByDefault*/
      false
    ) ? initialIndentation + options.indentSize : initialIndentation;
    const leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
    if (leadingTrivia) {
      indentTriviaItems(
        leadingTrivia,
        indentation,
        /*indentNextTokenOrTrivia*/
        false,
        (item) => processRange(
          item,
          sourceFile.getLineAndCharacterOfPosition(item.pos),
          enclosingNode,
          enclosingNode,
          /*dynamicIndentation*/
          void 0
        )
      );
      if (options.trimTrailingWhitespace !== false) {
        trimTrailingWhitespacesForRemainingRange(leadingTrivia);
      }
    }
  }
  if (previousRange && formattingScanner.getTokenFullStart() >= originalRange.end) {
    const tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : void 0;
    if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) {
      const parent2 = ((_a = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) == null ? void 0 : _a.parent) || previousParent;
      processPair(
        tokenInfo,
        sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line,
        parent2,
        previousRange,
        previousRangeStartLine,
        previousParent,
        parent2,
        /*dynamicIndentation*/
        void 0
      );
    }
  }
  return edits;
  function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
    if (rangeOverlapsWithStartEnd(range, startPos, endPos) || rangeContainsStartEnd(range, startPos, endPos)) {
      if (inheritedIndentation !== -1 /* Unknown */) {
        return inheritedIndentation;
      }
    } else {
      const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
      const startLinePosition = getLineStartPositionForPosition(startPos, sourceFile);
      const column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
      if (startLine !== parentStartLine || startPos === column) {
        const baseIndentSize = SmartIndenter.getBaseIndentation(options);
        return baseIndentSize > column ? baseIndentSize : column;
      }
    }
    return -1 /* Unknown */;
  }
  function computeIndentation(node, startLine, inheritedIndentation, parent2, parentDynamicIndentation, effectiveParentStartLine) {
    const delta2 = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
    if (effectiveParentStartLine === startLine) {
      return {
        indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
        delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta2)
      };
    } else if (inheritedIndentation === -1 /* Unknown */) {
      if (node.kind === 21 /* OpenParenToken */ && startLine === lastIndentedLine) {
        return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
      } else if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent2, node, startLine, sourceFile) || SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent2, node, startLine, sourceFile) || SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent2, node, startLine, sourceFile)) {
        return { indentation: parentDynamicIndentation.getIndentation(), delta: delta2 };
      } else {
        return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta2 };
      }
    } else {
      return { indentation: inheritedIndentation, delta: delta2 };
    }
  }
  function getFirstNonDecoratorTokenOfNode(node) {
    if (canHaveModifiers(node)) {
      const modifier = find(node.modifiers, isModifier, findIndex(node.modifiers, isDecorator));
      if (modifier)
        return modifier.kind;
    }
    switch (node.kind) {
      case 262 /* ClassDeclaration */:
        return 86 /* ClassKeyword */;
      case 263 /* InterfaceDeclaration */:
        return 120 /* InterfaceKeyword */;
      case 261 /* FunctionDeclaration */:
        return 100 /* FunctionKeyword */;
      case 265 /* EnumDeclaration */:
        return 265 /* EnumDeclaration */;
      case 176 /* GetAccessor */:
        return 139 /* GetKeyword */;
      case 177 /* SetAccessor */:
        return 153 /* SetKeyword */;
      case 173 /* MethodDeclaration */:
        if (node.asteriskToken) {
          return 42 /* AsteriskToken */;
        }
      case 171 /* PropertyDeclaration */:
      case 168 /* Parameter */:
        const name = getNameOfDeclaration(node);
        if (name) {
          return name.kind;
        }
    }
  }
  function getDynamicIndentation(node, nodeStartLine, indentation, delta2) {
    return {
      getIndentationForComment: (kind, tokenIndentation, container) => {
        switch (kind) {
          case 20 /* CloseBraceToken */:
          case 24 /* CloseBracketToken */:
          case 22 /* CloseParenToken */:
            return indentation + getDelta(container);
        }
        return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation;
      },
      // if list end token is LessThanToken '>' then its delta should be explicitly suppressed
      // so that LessThanToken as a binary operator can still be indented.
      // foo.then
      //     <
      //         number,
      //         string,
      //     >();
      // vs
      // var a = xValue
      //     > yValue;
      getIndentationForToken: (line, kind, container, suppressDelta) => !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation,
      getIndentation: () => indentation,
      getDelta,
      recomputeIndentation: (lineAdded, parent2) => {
        if (SmartIndenter.shouldIndentChildNode(options, parent2, node, sourceFile)) {
          indentation += lineAdded ? options.indentSize : -options.indentSize;
          delta2 = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
        }
      }
    };
    function shouldAddDelta(line, kind, container) {
      switch (kind) {
        case 19 /* OpenBraceToken */:
        case 20 /* CloseBraceToken */:
        case 22 /* CloseParenToken */:
        case 93 /* ElseKeyword */:
        case 117 /* WhileKeyword */:
        case 60 /* AtToken */:
          return false;
        case 44 /* SlashToken */:
        case 32 /* GreaterThanToken */:
          switch (container.kind) {
            case 285 /* JsxOpeningElement */:
            case 286 /* JsxClosingElement */:
            case 284 /* JsxSelfClosingElement */:
              return false;
          }
          break;
        case 23 /* OpenBracketToken */:
        case 24 /* CloseBracketToken */:
          if (container.kind !== 199 /* MappedType */) {
            return false;
          }
          break;
      }
      return nodeStartLine !== line && !(hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node));
    }
    function getDelta(child) {
      return SmartIndenter.nodeWillIndentChild(
        options,
        node,
        child,
        sourceFile,
        /*indentByDefault*/
        true
      ) ? delta2 : 0;
    }
  }
  function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta2) {
    if (!rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
      return;
    }
    const nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta2);
    let childContextNode = contextNode;
    forEachChild(
      node,
      (child) => {
        processChildNode(
          child,
          /*inheritedIndentation*/
          -1 /* Unknown */,
          node,
          nodeDynamicIndentation,
          nodeStartLine,
          undecoratedNodeStartLine,
          /*isListItem*/
          false
        );
      },
      (nodes) => {
        processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
      }
    );
    while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
      const tokenInfo = formattingScanner.readTokenInfo(node);
      if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) {
        break;
      }
      consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
    }
    function processChildNode(child, inheritedIndentation, parent2, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
      Debug.assert(!nodeIsSynthesized(child));
      if (nodeIsMissing(child) || isGrammarError(parent2, child)) {
        return inheritedIndentation;
      }
      const childStartPos = child.getStart(sourceFile);
      const childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
      let undecoratedChildStartLine = childStartLine;
      if (hasDecorators(child)) {
        undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
      }
      let childIndentationAmount = -1 /* Unknown */;
      if (isListItem && rangeContainsRange(originalRange, parent2)) {
        childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
        if (childIndentationAmount !== -1 /* Unknown */) {
          inheritedIndentation = childIndentationAmount;
        }
      }
      if (!rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
        if (child.end < originalRange.pos) {
          formattingScanner.skipToEndOf(child);
        }
        return inheritedIndentation;
      }
      if (child.getFullWidth() === 0) {
        return inheritedIndentation;
      }
      while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
        const tokenInfo = formattingScanner.readTokenInfo(node);
        if (tokenInfo.token.end > originalRange.end) {
          return inheritedIndentation;
        }
        if (tokenInfo.token.end > childStartPos) {
          if (tokenInfo.token.pos > childStartPos) {
            formattingScanner.skipToStartOf(child);
          }
          break;
        }
        consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
      }
      if (!formattingScanner.isOnToken() || formattingScanner.getTokenFullStart() >= originalRange.end) {
        return inheritedIndentation;
      }
      if (isToken(child)) {
        const tokenInfo = formattingScanner.readTokenInfo(child);
        if (child.kind !== 12 /* JsxText */) {
          Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
          consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
          return inheritedIndentation;
        }
      }
      const effectiveParentStartLine = child.kind === 169 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
      const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
      processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
      childContextNode = node;
      if (isFirstListItem && parent2.kind === 208 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
        inheritedIndentation = childIndentation.indentation;
      }
      return inheritedIndentation;
    }
    function processChildNodes(nodes, parent2, parentStartLine, parentDynamicIndentation) {
      Debug.assert(isNodeArray(nodes));
      Debug.assert(!nodeIsSynthesized(nodes));
      const listStartToken = getOpenTokenForList(parent2, nodes);
      let listDynamicIndentation = parentDynamicIndentation;
      let startLine = parentStartLine;
      if (!rangeOverlapsWithStartEnd(originalRange, nodes.pos, nodes.end)) {
        if (nodes.end < originalRange.pos) {
          formattingScanner.skipToEndOf(nodes);
        }
        return;
      }
      if (listStartToken !== 0 /* Unknown */) {
        while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
          const tokenInfo = formattingScanner.readTokenInfo(parent2);
          if (tokenInfo.token.end > nodes.pos) {
            break;
          } else if (tokenInfo.token.kind === listStartToken) {
            startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
            consumeTokenAndAdvanceScanner(tokenInfo, parent2, parentDynamicIndentation, parent2);
            let indentationOnListStartToken;
            if (indentationOnLastIndentedLine !== -1 /* Unknown */) {
              indentationOnListStartToken = indentationOnLastIndentedLine;
            } else {
              const startLinePosition = getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile);
              indentationOnListStartToken = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options);
            }
            listDynamicIndentation = getDynamicIndentation(parent2, parentStartLine, indentationOnListStartToken, options.indentSize);
          } else {
            consumeTokenAndAdvanceScanner(tokenInfo, parent2, parentDynamicIndentation, parent2);
          }
        }
      }
      let inheritedIndentation = -1 /* Unknown */;
      for (let i = 0; i < nodes.length; i++) {
        const child = nodes[i];
        inheritedIndentation = processChildNode(
          child,
          inheritedIndentation,
          node,
          listDynamicIndentation,
          startLine,
          startLine,
          /*isListItem*/
          true,
          /*isFirstListItem*/
          i === 0
        );
      }
      const listEndToken = getCloseTokenForOpenToken(listStartToken);
      if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) {
        let tokenInfo = formattingScanner.readTokenInfo(parent2);
        if (tokenInfo.token.kind === 28 /* CommaToken */) {
          consumeTokenAndAdvanceScanner(tokenInfo, parent2, listDynamicIndentation, parent2);
          tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent2) : void 0;
        }
        if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent2, tokenInfo.token)) {
          consumeTokenAndAdvanceScanner(
            tokenInfo,
            parent2,
            listDynamicIndentation,
            parent2,
            /*isListEndToken*/
            true
          );
        }
      }
    }
    function consumeTokenAndAdvanceScanner(currentTokenInfo, parent2, dynamicIndentation, container, isListEndToken) {
      Debug.assert(rangeContainsRange(parent2, currentTokenInfo.token));
      const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
      let indentToken = false;
      if (currentTokenInfo.leadingTrivia) {
        processTrivia(currentTokenInfo.leadingTrivia, parent2, childContextNode, dynamicIndentation);
      }
      let lineAction = 0 /* None */;
      const isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token);
      const tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
      if (isTokenInRange) {
        const rangeHasError = rangeContainsError(currentTokenInfo.token);
        const savePreviousRange = previousRange;
        lineAction = processRange(currentTokenInfo.token, tokenStart, parent2, childContextNode, dynamicIndentation);
        if (!rangeHasError) {
          if (lineAction === 0 /* None */) {
            const prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
            indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
          } else {
            indentToken = lineAction === 1 /* LineAdded */;
          }
        }
      }
      if (currentTokenInfo.trailingTrivia) {
        previousRangeTriviaEnd = last(currentTokenInfo.trailingTrivia).end;
        processTrivia(currentTokenInfo.trailingTrivia, parent2, childContextNode, dynamicIndentation);
      }
      if (indentToken) {
        const tokenIndentation = isTokenInRange && !rangeContainsError(currentTokenInfo.token) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) : -1 /* Unknown */;
        let indentNextTokenOrTrivia = true;
        if (currentTokenInfo.leadingTrivia) {
          const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
          indentNextTokenOrTrivia = indentTriviaItems(
            currentTokenInfo.leadingTrivia,
            commentIndentation,
            indentNextTokenOrTrivia,
            (item) => insertIndentation(
              item.pos,
              commentIndentation,
              /*lineAdded*/
              false
            )
          );
        }
        if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) {
          insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */);
          lastIndentedLine = tokenStart.line;
          indentationOnLastIndentedLine = tokenIndentation;
        }
      }
      formattingScanner.advance();
      childContextNode = parent2;
    }
  }
  function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) {
    for (const triviaItem of trivia) {
      const triviaInRange = rangeContainsRange(originalRange, triviaItem);
      switch (triviaItem.kind) {
        case 3 /* MultiLineCommentTrivia */:
          if (triviaInRange) {
            indentMultilineComment(
              triviaItem,
              commentIndentation,
              /*firstLineIsIndented*/
              !indentNextTokenOrTrivia
            );
          }
          indentNextTokenOrTrivia = false;
          break;
        case 2 /* SingleLineCommentTrivia */:
          if (indentNextTokenOrTrivia && triviaInRange) {
            indentSingleLine(triviaItem);
          }
          indentNextTokenOrTrivia = false;
          break;
        case 4 /* NewLineTrivia */:
          indentNextTokenOrTrivia = true;
          break;
      }
    }
    return indentNextTokenOrTrivia;
  }
  function processTrivia(trivia, parent2, contextNode, dynamicIndentation) {
    for (const triviaItem of trivia) {
      if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) {
        const triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
        processRange(triviaItem, triviaItemStart, parent2, contextNode, dynamicIndentation);
      }
    }
  }
  function processRange(range, rangeStart, parent2, contextNode, dynamicIndentation) {
    const rangeHasError = rangeContainsError(range);
    let lineAction = 0 /* None */;
    if (!rangeHasError) {
      if (!previousRange) {
        const originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
        trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
      } else {
        lineAction = processPair(range, rangeStart.line, parent2, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
      }
    }
    previousRange = range;
    previousRangeTriviaEnd = range.end;
    previousParent = parent2;
    previousRangeStartLine = rangeStart.line;
    return lineAction;
  }
  function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent2, contextNode, dynamicIndentation) {
    formattingContext.updateContext(previousItem, previousParent2, currentItem, currentParent, contextNode);
    const rules = getRules(formattingContext);
    let trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false;
    let lineAction = 0 /* None */;
    if (rules) {
      forEachRight(rules, (rule2) => {
        lineAction = applyRuleEdits(rule2, previousItem, previousStartLine, currentItem, currentStartLine);
        if (dynamicIndentation) {
          switch (lineAction) {
            case 2 /* LineRemoved */:
              if (currentParent.getStart(sourceFile) === currentItem.pos) {
                dynamicIndentation.recomputeIndentation(
                  /*lineAddedByFormatting*/
                  false,
                  contextNode
                );
              }
              break;
            case 1 /* LineAdded */:
              if (currentParent.getStart(sourceFile) === currentItem.pos) {
                dynamicIndentation.recomputeIndentation(
                  /*lineAddedByFormatting*/
                  true,
                  contextNode
                );
              }
              break;
            default:
              Debug.assert(lineAction === 0 /* None */);
          }
        }
        trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule2.action & 16 /* DeleteSpace */) && rule2.flags !== 1 /* CanDeleteNewLines */;
      });
    } else {
      trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.kind !== 1 /* EndOfFileToken */;
    }
    if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) {
      trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem);
    }
    return lineAction;
  }
  function insertIndentation(pos, indentation, lineAdded) {
    const indentationString = getIndentationString(indentation, options);
    if (lineAdded) {
      recordReplace(pos, 0, indentationString);
    } else {
      const tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
      const startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile);
      if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
        recordReplace(startLinePosition, tokenStart.character, indentationString);
      }
    }
  }
  function characterToColumn(startLinePosition, characterInLine) {
    let column = 0;
    for (let i = 0; i < characterInLine; i++) {
      if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) {
        column += options.tabSize - column % options.tabSize;
      } else {
        column++;
      }
    }
    return column;
  }
  function indentationIsDifferent(indentationString, startLinePosition) {
    return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length);
  }
  function indentMultilineComment(commentRange, indentation, firstLineIsIndented, indentFinalLine = true) {
    let startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
    const endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
    if (startLine === endLine) {
      if (!firstLineIsIndented) {
        insertIndentation(
          commentRange.pos,
          indentation,
          /*lineAdded*/
          false
        );
      }
      return;
    }
    const parts = [];
    let startPos = commentRange.pos;
    for (let line = startLine; line < endLine; line++) {
      const endOfLine = getEndLinePosition(line, sourceFile);
      parts.push({ pos: startPos, end: endOfLine });
      startPos = getStartPositionOfLine(line + 1, sourceFile);
    }
    if (indentFinalLine) {
      parts.push({ pos: startPos, end: commentRange.end });
    }
    if (parts.length === 0)
      return;
    const startLinePos = getStartPositionOfLine(startLine, sourceFile);
    const nonWhitespaceColumnInFirstPart = SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
    let startIndex = 0;
    if (firstLineIsIndented) {
      startIndex = 1;
      startLine++;
    }
    const delta2 = indentation - nonWhitespaceColumnInFirstPart.column;
    for (let i = startIndex; i < parts.length; i++, startLine++) {
      const startLinePos2 = getStartPositionOfLine(startLine, sourceFile);
      const nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
      const newIndentation = nonWhitespaceCharacterAndColumn.column + delta2;
      if (newIndentation > 0) {
        const indentationString = getIndentationString(newIndentation, options);
        recordReplace(startLinePos2, nonWhitespaceCharacterAndColumn.character, indentationString);
      } else {
        recordDelete(startLinePos2, nonWhitespaceCharacterAndColumn.character);
      }
    }
  }
  function trimTrailingWhitespacesForLines(line1, line2, range) {
    for (let line = line1; line < line2; line++) {
      const lineStartPosition = getStartPositionOfLine(line, sourceFile);
      const lineEndPosition = getEndLinePosition(line, sourceFile);
      if (range && (isComment(range.kind) || isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
        continue;
      }
      const whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
      if (whitespaceStart !== -1) {
        Debug.assert(whitespaceStart === lineStartPosition || !isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1)));
        recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
      }
    }
  }
  function getTrailingWhitespaceStartPosition(start2, end) {
    let pos = end;
    while (pos >= start2 && isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) {
      pos--;
    }
    if (pos !== end) {
      return pos + 1;
    }
    return -1;
  }
  function trimTrailingWhitespacesForRemainingRange(trivias) {
    let startPos = previousRange ? previousRange.end : originalRange.pos;
    for (const trivia of trivias) {
      if (isComment(trivia.kind)) {
        if (startPos < trivia.pos) {
          trimTrailingWitespacesForPositions(startPos, trivia.pos - 1, previousRange);
        }
        startPos = trivia.end + 1;
      }
    }
    if (startPos < originalRange.end) {
      trimTrailingWitespacesForPositions(startPos, originalRange.end, previousRange);
    }
  }
  function trimTrailingWitespacesForPositions(startPos, endPos, previousRange2) {
    const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
    const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line;
    trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange2);
  }
  function recordDelete(start2, len) {
    if (len) {
      edits.push(createTextChangeFromStartLength(start2, len, ""));
    }
  }
  function recordReplace(start2, len, newText) {
    if (len || newText) {
      edits.push(createTextChangeFromStartLength(start2, len, newText));
    }
  }
  function recordInsert(start2, text) {
    if (text) {
      edits.push(createTextChangeFromStartLength(start2, 0, text));
    }
  }
  function applyRuleEdits(rule2, previousRange2, previousStartLine, currentRange, currentStartLine) {
    const onLaterLine = currentStartLine !== previousStartLine;
    switch (rule2.action) {
      case 1 /* StopProcessingSpaceActions */:
        return 0 /* None */;
      case 16 /* DeleteSpace */:
        if (previousRange2.end !== currentRange.pos) {
          recordDelete(previousRange2.end, currentRange.pos - previousRange2.end);
          return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
        }
        break;
      case 32 /* DeleteToken */:
        recordDelete(previousRange2.pos, previousRange2.end - previousRange2.pos);
        break;
      case 8 /* InsertNewLine */:
        if (rule2.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
          return 0 /* None */;
        }
        const lineDelta = currentStartLine - previousStartLine;
        if (lineDelta !== 1) {
          recordReplace(previousRange2.end, currentRange.pos - previousRange2.end, getNewLineOrDefaultFromHost(host, options));
          return onLaterLine ? 0 /* None */ : 1 /* LineAdded */;
        }
        break;
      case 4 /* InsertSpace */:
        if (rule2.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
          return 0 /* None */;
        }
        const posDelta = currentRange.pos - previousRange2.end;
        if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange2.end) !== 32 /* space */) {
          recordReplace(previousRange2.end, currentRange.pos - previousRange2.end, " ");
          return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
        }
        break;
      case 64 /* InsertTrailingSemicolon */:
        recordInsert(previousRange2.end, ";");
    }
    return 0 /* None */;
  }
}
function getRangeOfEnclosingComment(sourceFile, position, precedingToken, tokenAtPosition = getTokenAtPosition(sourceFile, position)) {
  const jsdoc = findAncestor(tokenAtPosition, isJSDoc);
  if (jsdoc)
    tokenAtPosition = jsdoc.parent;
  const tokenStart = tokenAtPosition.getStart(sourceFile);
  if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
    return void 0;
  }
  precedingToken = precedingToken === null ? void 0 : precedingToken === void 0 ? findPrecedingToken(position, sourceFile) : precedingToken;
  const trailingRangesOfPreviousToken = precedingToken && getTrailingCommentRanges(sourceFile.text, precedingToken.end);
  const leadingCommentRangesOfNextToken = getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
  const commentRanges = concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
  return commentRanges && find(commentRanges, (range) => rangeContainsPositionExclusive(range, position) || // The end marker of a single-line comment does not include the newline character.
  // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
  //
  //    // asdf   ^\n
  //
  // But for closed multi-line comments, we don't want to be inside the comment in the following case:
  //
  //    /* asdf */^
  //
  // However, unterminated multi-line comments *do* contain their end.
  //
  // Internally, we represent the end of the comment at the newline and closing '/', respectively.
  //
  position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()));
}
function getOpenTokenForList(node, list) {
  switch (node.kind) {
    case 175 /* Constructor */:
    case 261 /* FunctionDeclaration */:
    case 217 /* FunctionExpression */:
    case 173 /* MethodDeclaration */:
    case 172 /* MethodSignature */:
    case 218 /* ArrowFunction */:
    case 178 /* CallSignature */:
    case 179 /* ConstructSignature */:
    case 183 /* FunctionType */:
    case 184 /* ConstructorType */:
    case 176 /* GetAccessor */:
    case 177 /* SetAccessor */:
      if (node.typeParameters === list) {
        return 30 /* LessThanToken */;
      } else if (node.parameters === list) {
        return 21 /* OpenParenToken */;
      }
      break;
    case 212 /* CallExpression */:
    case 213 /* NewExpression */:
      if (node.typeArguments === list) {
        return 30 /* LessThanToken */;
      } else if (node.arguments === list) {
        return 21 /* OpenParenToken */;
      }
      break;
    case 262 /* ClassDeclaration */:
    case 230 /* ClassExpression */:
    case 263 /* InterfaceDeclaration */:
    case 264 /* TypeAliasDeclaration */:
      if (node.typeParameters === list) {
        return 30 /* LessThanToken */;
      }
      break;
    case 182 /* TypeReference */:
    case 214 /* TaggedTemplateExpression */:
    case 185 /* TypeQuery */:
    case 232 /* ExpressionWithTypeArguments */:
    case 204 /* ImportType */:
      if (node.typeArguments === list) {
        return 30 /* LessThanToken */;
      }
      break;
    case 186 /* TypeLiteral */:
      return 19 /* OpenBraceToken */;
  }
  return 0 /* Unknown */;
}
function getCloseTokenForOpenToken(kind) {
  switch (kind) {
    case 21 /* OpenParenToken */:
      return 22 /* CloseParenToken */;
    case 30 /* LessThanToken */:
      return 32 /* GreaterThanToken */;
    case 19 /* OpenBraceToken */:
      return 20 /* CloseBraceToken */;
  }
  return 0 /* Unknown */;
}
var internedSizes;
var internedTabsIndentation;
var internedSpacesIndentation;
function getIndentationString(indentation, options) {
  const resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
  if (resetInternedStrings) {
    internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
    internedTabsIndentation = internedSpacesIndentation = void 0;
  }
  if (!options.convertTabsToSpaces) {
    const tabs = Math.floor(indentation / options.tabSize);
    const spaces = indentation - tabs * options.tabSize;
    let tabString;
    if (!internedTabsIndentation) {
      internedTabsIndentation = [];
    }
    if (internedTabsIndentation[tabs] === void 0) {
      internedTabsIndentation[tabs] = tabString = repeatString("	", tabs);
    } else {
      tabString = internedTabsIndentation[tabs];
    }
    return spaces ? tabString + repeatString(" ", spaces) : tabString;
  } else {
    let spacesString;
    const quotient = Math.floor(indentation / options.indentSize);
    const remainder = indentation % options.indentSize;
    if (!internedSpacesIndentation) {
      internedSpacesIndentation = [];
    }
    if (internedSpacesIndentation[quotient] === void 0) {
      spacesString = repeatString(" ", options.indentSize * quotient);
      internedSpacesIndentation[quotient] = spacesString;
    } else {
      spacesString = internedSpacesIndentation[quotient];
    }
    return remainder ? spacesString + repeatString(" ", remainder) : spacesString;
  }
}

// src/services/formatting/smartIndenter.ts
var SmartIndenter;
((SmartIndenter2) => {
  let Value;
  ((Value2) => {
    Value2[Value2["Unknown"] = -1] = "Unknown";
  })(Value || (Value = {}));
  function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace = false) {
    if (position > sourceFile.text.length) {
      return getBaseIndentation(options);
    }
    if (options.indentStyle === 0 /* None */) {
      return 0;
    }
    const precedingToken = findPrecedingToken(
      position,
      sourceFile,
      /*startNode*/
      void 0,
      /*excludeJsdoc*/
      true
    );
    const enclosingCommentRange = getRangeOfEnclosingComment(sourceFile, position, precedingToken || null);
    if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
      return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
    }
    if (!precedingToken) {
      return getBaseIndentation(options);
    }
    const precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
    if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) {
      return 0;
    }
    const lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
    const currentToken = getTokenAtPosition(sourceFile, position);
    const isObjectLiteral = currentToken.kind === 19 /* OpenBraceToken */ && currentToken.parent.kind === 209 /* ObjectLiteralExpression */;
    if (options.indentStyle === 1 /* Block */ || isObjectLiteral) {
      return getBlockIndent(sourceFile, position, options);
    }
    if (precedingToken.kind === 28 /* CommaToken */ && precedingToken.parent.kind !== 225 /* BinaryExpression */) {
      const actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
      if (actualIndentation !== -1 /* Unknown */) {
        return actualIndentation;
      }
    }
    const containerList = getListByPosition(position, precedingToken.parent, sourceFile);
    if (containerList && !rangeContainsRange(containerList, precedingToken)) {
      const useTheSameBaseIndentation = [217 /* FunctionExpression */, 218 /* ArrowFunction */].indexOf(currentToken.parent.kind) !== -1;
      const indentSize = useTheSameBaseIndentation ? 0 : options.indentSize;
      return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize;
    }
    return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options);
  }
  SmartIndenter2.getIndentation = getIndentation;
  function getCommentIndent(sourceFile, position, options, enclosingCommentRange) {
    const previousLine = getLineAndCharacterOfPosition(sourceFile, position).line - 1;
    const commentStartLine = getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line;
    Debug.assert(commentStartLine >= 0);
    if (previousLine <= commentStartLine) {
      return findFirstNonWhitespaceColumn(getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options);
    }
    const startPositionOfLine = getStartPositionOfLine(previousLine, sourceFile);
    const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options);
    if (column === 0) {
      return column;
    }
    const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character);
    return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column;
  }
  function getBlockIndent(sourceFile, position, options) {
    let current = position;
    while (current > 0) {
      const char = sourceFile.text.charCodeAt(current);
      if (!isWhiteSpaceLike(char)) {
        break;
      }
      current--;
    }
    const lineStart = getLineStartPositionForPosition(current, sourceFile);
    return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
  }
  function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) {
    let previous;
    let current = precedingToken;
    while (current) {
      if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(
        options,
        current,
        previous,
        sourceFile,
        /*isNextChild*/
        true
      )) {
        const currentStart = getStartLineAndCharacterForNode(current, sourceFile);
        const nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
        const indentationDelta = nextTokenKind !== 0 /* Unknown */ ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0;
        return getIndentationForNodeWorker(
          current,
          currentStart,
          /*ignoreActualIndentationRange*/
          void 0,
          indentationDelta,
          sourceFile,
          /*isNextChild*/
          true,
          options
        );
      }
      const actualIndentation = getActualIndentationForListItem(
        current,
        sourceFile,
        options,
        /*listIndentsChild*/
        true
      );
      if (actualIndentation !== -1 /* Unknown */) {
        return actualIndentation;
      }
      previous = current;
      current = current.parent;
    }
    return getBaseIndentation(options);
  }
  function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
    const start2 = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
    return getIndentationForNodeWorker(
      n,
      start2,
      ignoreActualIndentationRange,
      /*indentationDelta*/
      0,
      sourceFile,
      /*isNextChild*/
      false,
      options
    );
  }
  SmartIndenter2.getIndentationForNode = getIndentationForNode;
  function getBaseIndentation(options) {
    return options.baseIndentSize || 0;
  }
  SmartIndenter2.getBaseIndentation = getBaseIndentation;
  function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
    var _a;
    let parent2 = current.parent;
    while (parent2) {
      let useActualIndentation = true;
      if (ignoreActualIndentationRange) {
        const start2 = current.getStart(sourceFile);
        useActualIndentation = start2 < ignoreActualIndentationRange.pos || start2 > ignoreActualIndentationRange.end;
      }
      const containingListOrParentStart = getContainingListOrParentStart(parent2, current, sourceFile);
      const parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent2, current, currentStart.line, sourceFile);
      if (useActualIndentation) {
        const firstListChild = (_a = getContainingList(current, sourceFile)) == null ? void 0 : _a[0];
        const listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line;
        let actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild);
        if (actualIndentation !== -1 /* Unknown */) {
          return actualIndentation + indentationDelta;
        }
        actualIndentation = getActualIndentationForNode(current, parent2, currentStart, parentAndChildShareLine, sourceFile, options);
        if (actualIndentation !== -1 /* Unknown */) {
          return actualIndentation + indentationDelta;
        }
      }
      if (shouldIndentChildNode(options, parent2, current, sourceFile, isNextChild) && !parentAndChildShareLine) {
        indentationDelta += options.indentSize;
      }
      const useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent2, current, currentStart.line, sourceFile);
      current = parent2;
      parent2 = current.parent;
      currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart;
    }
    return indentationDelta + getBaseIndentation(options);
  }
  function getContainingListOrParentStart(parent2, child, sourceFile) {
    const containingList = getContainingList(child, sourceFile);
    const startPos = containingList ? containingList.pos : parent2.getStart(sourceFile);
    return sourceFile.getLineAndCharacterOfPosition(startPos);
  }
  function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) {
    const commaItemInfo = findListItemInfo(commaToken);
    if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
      return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
    } else {
      return -1 /* Unknown */;
    }
  }
  function getActualIndentationForNode(current, parent2, currentLineAndChar, parentAndChildShareLine, sourceFile, options) {
    const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent2.kind === 311 /* SourceFile */ || !parentAndChildShareLine);
    if (!useActualIndentation) {
      return -1 /* Unknown */;
    }
    return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
  }
  let NextTokenKind;
  ((NextTokenKind2) => {
    NextTokenKind2[NextTokenKind2["Unknown"] = 0] = "Unknown";
    NextTokenKind2[NextTokenKind2["OpenBrace"] = 1] = "OpenBrace";
    NextTokenKind2[NextTokenKind2["CloseBrace"] = 2] = "CloseBrace";
  })(NextTokenKind || (NextTokenKind = {}));
  function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
    const nextToken = findNextToken(precedingToken, current, sourceFile);
    if (!nextToken) {
      return 0 /* Unknown */;
    }
    if (nextToken.kind === 19 /* OpenBraceToken */) {
      return 1 /* OpenBrace */;
    } else if (nextToken.kind === 20 /* CloseBraceToken */) {
      const nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
      return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
    }
    return 0 /* Unknown */;
  }
  function getStartLineAndCharacterForNode(n, sourceFile) {
    return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
  }
  function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent2, child, childStartLine, sourceFile) {
    if (!(isCallExpression(parent2) && contains(parent2.arguments, child))) {
      return false;
    }
    const expressionOfCallExpressionEnd = parent2.expression.getEnd();
    const expressionOfCallExpressionEndLine = getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line;
    return expressionOfCallExpressionEndLine === childStartLine;
  }
  SmartIndenter2.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
  function childStartsOnTheSameLineWithElseInIfStatement(parent2, child, childStartLine, sourceFile) {
    if (parent2.kind === 244 /* IfStatement */ && parent2.elseStatement === child) {
      const elseKeyword = findChildOfKind(parent2, 93 /* ElseKeyword */, sourceFile);
      Debug.assert(elseKeyword !== void 0);
      const elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
      return elseKeywordStartLine === childStartLine;
    }
    return false;
  }
  SmartIndenter2.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
  function childIsUnindentedBranchOfConditionalExpression(parent2, child, childStartLine, sourceFile) {
    if (isConditionalExpression(parent2) && (child === parent2.whenTrue || child === parent2.whenFalse)) {
      const conditionEndLine = getLineAndCharacterOfPosition(sourceFile, parent2.condition.end).line;
      if (child === parent2.whenTrue) {
        return childStartLine === conditionEndLine;
      } else {
        const trueStartLine = getStartLineAndCharacterForNode(parent2.whenTrue, sourceFile).line;
        const trueEndLine = getLineAndCharacterOfPosition(sourceFile, parent2.whenTrue.end).line;
        return conditionEndLine === trueStartLine && trueEndLine === childStartLine;
      }
    }
    return false;
  }
  SmartIndenter2.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression;
  function argumentStartsOnSameLineAsPreviousArgument(parent2, child, childStartLine, sourceFile) {
    if (isCallOrNewExpression(parent2)) {
      if (!parent2.arguments)
        return false;
      const currentNode = find(parent2.arguments, (arg) => arg.pos === child.pos);
      if (!currentNode)
        return false;
      const currentIndex = parent2.arguments.indexOf(currentNode);
      if (currentIndex === 0)
        return false;
      const previousNode = parent2.arguments[currentIndex - 1];
      const lineOfPreviousNode = getLineAndCharacterOfPosition(sourceFile, previousNode.getEnd()).line;
      if (childStartLine === lineOfPreviousNode) {
        return true;
      }
    }
    return false;
  }
  SmartIndenter2.argumentStartsOnSameLineAsPreviousArgument = argumentStartsOnSameLineAsPreviousArgument;
  function getContainingList(node, sourceFile) {
    return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile);
  }
  SmartIndenter2.getContainingList = getContainingList;
  function getListByPosition(pos, node, sourceFile) {
    return node && getListByRange(pos, pos, node, sourceFile);
  }
  function getListByRange(start2, end, node, sourceFile) {
    switch (node.kind) {
      case 182 /* TypeReference */:
        return getList(node.typeArguments);
      case 209 /* ObjectLiteralExpression */:
        return getList(node.properties);
      case 208 /* ArrayLiteralExpression */:
        return getList(node.elements);
      case 186 /* TypeLiteral */:
        return getList(node.members);
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
      case 218 /* ArrowFunction */:
      case 173 /* MethodDeclaration */:
      case 172 /* MethodSignature */:
      case 178 /* CallSignature */:
      case 175 /* Constructor */:
      case 184 /* ConstructorType */:
      case 179 /* ConstructSignature */:
        return getList(node.typeParameters) || getList(node.parameters);
      case 176 /* GetAccessor */:
        return getList(node.parameters);
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
      case 263 /* InterfaceDeclaration */:
      case 264 /* TypeAliasDeclaration */:
      case 351 /* JSDocTemplateTag */:
        return getList(node.typeParameters);
      case 213 /* NewExpression */:
      case 212 /* CallExpression */:
        return getList(node.typeArguments) || getList(node.arguments);
      case 260 /* VariableDeclarationList */:
        return getList(node.declarations);
      case 274 /* NamedImports */:
      case 278 /* NamedExports */:
        return getList(node.elements);
      case 205 /* ObjectBindingPattern */:
      case 206 /* ArrayBindingPattern */:
        return getList(node.elements);
    }
    function getList(list) {
      return list && rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start2, end) ? list : void 0;
    }
  }
  function getVisualListRange(node, list, sourceFile) {
    const children = node.getChildren(sourceFile);
    for (let i = 1; i < children.length - 1; i++) {
      if (children[i].pos === list.pos && children[i].end === list.end) {
        return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) };
      }
    }
    return list;
  }
  function getActualIndentationForListStartLine(list, sourceFile, options) {
    if (!list) {
      return -1 /* Unknown */;
    }
    return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options);
  }
  function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) {
    if (node.parent && node.parent.kind === 260 /* VariableDeclarationList */) {
      return -1 /* Unknown */;
    }
    const containingList = getContainingList(node, sourceFile);
    if (containingList) {
      const index = containingList.indexOf(node);
      if (index !== -1) {
        const result = deriveActualIndentationFromList(containingList, index, sourceFile, options);
        if (result !== -1 /* Unknown */) {
          return result;
        }
      }
      return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0);
    }
    return -1 /* Unknown */;
  }
  function deriveActualIndentationFromList(list, index, sourceFile, options) {
    Debug.assert(index >= 0 && index < list.length);
    const node = list[index];
    let lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
    for (let i = index - 1; i >= 0; i--) {
      if (list[i].kind === 28 /* CommaToken */) {
        continue;
      }
      const prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
      if (prevEndLine !== lineAndCharacter.line) {
        return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
      }
      lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile);
    }
    return -1 /* Unknown */;
  }
  function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) {
    const lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
    return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
  }
  function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
    let character = 0;
    let column = 0;
    for (let pos = startPos; pos < endPos; pos++) {
      const ch = sourceFile.text.charCodeAt(pos);
      if (!isWhiteSpaceSingleLine(ch)) {
        break;
      }
      if (ch === 9 /* tab */) {
        column += options.tabSize + column % options.tabSize;
      } else {
        column++;
      }
      character++;
    }
    return { column, character };
  }
  SmartIndenter2.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn;
  function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
    return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
  }
  SmartIndenter2.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
  function nodeWillIndentChild(settings, parent2, child, sourceFile, indentByDefault) {
    const childKind = child ? child.kind : 0 /* Unknown */;
    switch (parent2.kind) {
      case 243 /* ExpressionStatement */:
      case 262 /* ClassDeclaration */:
      case 230 /* ClassExpression */:
      case 263 /* InterfaceDeclaration */:
      case 265 /* EnumDeclaration */:
      case 264 /* TypeAliasDeclaration */:
      case 208 /* ArrayLiteralExpression */:
      case 240 /* Block */:
      case 267 /* ModuleBlock */:
      case 209 /* ObjectLiteralExpression */:
      case 186 /* TypeLiteral */:
      case 199 /* MappedType */:
      case 188 /* TupleType */:
      case 216 /* ParenthesizedExpression */:
      case 210 /* PropertyAccessExpression */:
      case 212 /* CallExpression */:
      case 213 /* NewExpression */:
      case 242 /* VariableStatement */:
      case 276 /* ExportAssignment */:
      case 252 /* ReturnStatement */:
      case 226 /* ConditionalExpression */:
      case 206 /* ArrayBindingPattern */:
      case 205 /* ObjectBindingPattern */:
      case 285 /* JsxOpeningElement */:
      case 288 /* JsxOpeningFragment */:
      case 284 /* JsxSelfClosingElement */:
      case 293 /* JsxExpression */:
      case 172 /* MethodSignature */:
      case 178 /* CallSignature */:
      case 179 /* ConstructSignature */:
      case 168 /* Parameter */:
      case 183 /* FunctionType */:
      case 184 /* ConstructorType */:
      case 195 /* ParenthesizedType */:
      case 214 /* TaggedTemplateExpression */:
      case 222 /* AwaitExpression */:
      case 278 /* NamedExports */:
      case 274 /* NamedImports */:
      case 280 /* ExportSpecifier */:
      case 275 /* ImportSpecifier */:
      case 171 /* PropertyDeclaration */:
      case 295 /* CaseClause */:
      case 296 /* DefaultClause */:
        return true;
      case 268 /* CaseBlock */:
        return settings.indentSwitchCase ?? true;
      case 259 /* VariableDeclaration */:
      case 302 /* PropertyAssignment */:
      case 225 /* BinaryExpression */:
        if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 209 /* ObjectLiteralExpression */) {
          return rangeIsOnOneLine(sourceFile, child);
        }
        if (parent2.kind === 225 /* BinaryExpression */ && sourceFile && child && childKind === 283 /* JsxElement */) {
          const parentStartLine = sourceFile.getLineAndCharacterOfPosition(skipTrivia(sourceFile.text, parent2.pos)).line;
          const childStartLine = sourceFile.getLineAndCharacterOfPosition(skipTrivia(sourceFile.text, child.pos)).line;
          return parentStartLine !== childStartLine;
        }
        if (parent2.kind !== 225 /* BinaryExpression */) {
          return true;
        }
        break;
      case 245 /* DoStatement */:
      case 246 /* WhileStatement */:
      case 248 /* ForInStatement */:
      case 249 /* ForOfStatement */:
      case 247 /* ForStatement */:
      case 244 /* IfStatement */:
      case 261 /* FunctionDeclaration */:
      case 217 /* FunctionExpression */:
      case 173 /* MethodDeclaration */:
      case 175 /* Constructor */:
      case 176 /* GetAccessor */:
      case 177 /* SetAccessor */:
        return childKind !== 240 /* Block */;
      case 218 /* ArrowFunction */:
        if (sourceFile && childKind === 216 /* ParenthesizedExpression */) {
          return rangeIsOnOneLine(sourceFile, child);
        }
        return childKind !== 240 /* Block */;
      case 277 /* ExportDeclaration */:
        return childKind !== 278 /* NamedExports */;
      case 271 /* ImportDeclaration */:
        return childKind !== 272 /* ImportClause */ || !!child.namedBindings && child.namedBindings.kind !== 274 /* NamedImports */;
      case 283 /* JsxElement */:
        return childKind !== 286 /* JsxClosingElement */;
      case 287 /* JsxFragment */:
        return childKind !== 289 /* JsxClosingFragment */;
      case 192 /* IntersectionType */:
      case 191 /* UnionType */:
        if (childKind === 186 /* TypeLiteral */ || childKind === 188 /* TupleType */) {
          return false;
        }
        break;
    }
    return indentByDefault;
  }
  SmartIndenter2.nodeWillIndentChild = nodeWillIndentChild;
  function isControlFlowEndingStatement(kind, parent2) {
    switch (kind) {
      case 252 /* ReturnStatement */:
      case 256 /* ThrowStatement */:
      case 250 /* ContinueStatement */:
      case 251 /* BreakStatement */:
        return parent2.kind !== 240 /* Block */;
      default:
        return false;
    }
  }
  function shouldIndentChildNode(settings, parent2, child, sourceFile, isNextChild = false) {
    return nodeWillIndentChild(
      settings,
      parent2,
      child,
      sourceFile,
      /*indentByDefault*/
      false
    ) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent2));
  }
  SmartIndenter2.shouldIndentChildNode = shouldIndentChildNode;
  function rangeIsOnOneLine(sourceFile, range) {
    const rangeStart = skipTrivia(sourceFile.text, range.pos);
    const startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line;
    const endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
    return startLine === endLine;
  }
})(SmartIndenter || (SmartIndenter = {}));

// src/server/_namespaces/ts.ts
var ts_exports2 = {};
__export(ts_exports2, {
  ANONYMOUS: () => ANONYMOUS,
  AccessFlags: () => AccessFlags,
  AssertionLevel: () => AssertionLevel,
  AssignmentDeclarationKind: () => AssignmentDeclarationKind,
  AssignmentKind: () => AssignmentKind,
  Associativity: () => Associativity,
  BreakpointResolver: () => ts_BreakpointResolver_exports,
  BuilderFileEmit: () => BuilderFileEmit,
  BuilderProgramKind: () => BuilderProgramKind,
  BuilderState: () => BuilderState,
  BundleFileSectionKind: () => BundleFileSectionKind,
  CallHierarchy: () => ts_CallHierarchy_exports,
  CharacterCodes: () => CharacterCodes,
  CheckFlags: () => CheckFlags,
  CheckMode: () => CheckMode,
  ClassificationType: () => ClassificationType,
  ClassificationTypeNames: () => ClassificationTypeNames,
  CommentDirectiveType: () => CommentDirectiveType,
  Comparison: () => Comparison,
  CompletionInfoFlags: () => CompletionInfoFlags,
  CompletionTriggerKind: () => CompletionTriggerKind,
  Completions: () => ts_Completions_exports,
  ConfigFileProgramReloadLevel: () => ConfigFileProgramReloadLevel,
  ContextFlags: () => ContextFlags,
  CoreServicesShimHostAdapter: () => CoreServicesShimHostAdapter,
  Debug: () => Debug,
  DiagnosticCategory: () => DiagnosticCategory,
  Diagnostics: () => Diagnostics,
  DocumentHighlights: () => DocumentHighlights,
  ElementFlags: () => ElementFlags,
  EmitFlags: () => EmitFlags,
  EmitHint: () => EmitHint,
  EmitOnly: () => EmitOnly,
  EndOfLineState: () => EndOfLineState,
  EnumKind: () => EnumKind,
  ExitStatus: () => ExitStatus,
  ExportKind: () => ExportKind,
  Extension: () => Extension,
  ExternalEmitHelpers: () => ExternalEmitHelpers,
  FileIncludeKind: () => FileIncludeKind,
  FilePreprocessingDiagnosticsKind: () => FilePreprocessingDiagnosticsKind,
  FileSystemEntryKind: () => FileSystemEntryKind,
  FileWatcherEventKind: () => FileWatcherEventKind,
  FindAllReferences: () => ts_FindAllReferences_exports,
  FlattenLevel: () => FlattenLevel,
  FlowFlags: () => FlowFlags,
  ForegroundColorEscapeSequences: () => ForegroundColorEscapeSequences,
  FunctionFlags: () => FunctionFlags,
  GeneratedIdentifierFlags: () => GeneratedIdentifierFlags,
  GetLiteralTextFlags: () => GetLiteralTextFlags,
  GoToDefinition: () => ts_GoToDefinition_exports,
  HighlightSpanKind: () => HighlightSpanKind,
  ImportKind: () => ImportKind,
  ImportsNotUsedAsValues: () => ImportsNotUsedAsValues,
  IndentStyle: () => IndentStyle,
  IndexFlags: () => IndexFlags,
  IndexKind: () => IndexKind,
  InferenceFlags: () => InferenceFlags,
  InferencePriority: () => InferencePriority,
  InlayHintKind: () => InlayHintKind,
  InlayHints: () => ts_InlayHints_exports,
  InternalEmitFlags: () => InternalEmitFlags,
  InternalSymbolName: () => InternalSymbolName,
  InvalidatedProjectKind: () => InvalidatedProjectKind,
  JsDoc: () => ts_JsDoc_exports,
  JsTyping: () => ts_JsTyping_exports,
  JsxEmit: () => JsxEmit,
  JsxFlags: () => JsxFlags,
  JsxReferenceKind: () => JsxReferenceKind,
  LanguageServiceMode: () => LanguageServiceMode,
  LanguageServiceShimHostAdapter: () => LanguageServiceShimHostAdapter,
  LanguageVariant: () => LanguageVariant,
  LexicalEnvironmentFlags: () => LexicalEnvironmentFlags,
  ListFormat: () => ListFormat,
  LogLevel: () => LogLevel,
  MemberOverrideStatus: () => MemberOverrideStatus,
  ModifierFlags: () => ModifierFlags,
  ModuleDetectionKind: () => ModuleDetectionKind,
  ModuleInstanceState: () => ModuleInstanceState,
  ModuleKind: () => ModuleKind,
  ModuleResolutionKind: () => ModuleResolutionKind,
  ModuleSpecifierEnding: () => ModuleSpecifierEnding,
  NavigateTo: () => ts_NavigateTo_exports,
  NavigationBar: () => ts_NavigationBar_exports,
  NewLineKind: () => NewLineKind,
  NodeBuilderFlags: () => NodeBuilderFlags,
  NodeCheckFlags: () => NodeCheckFlags,
  NodeFactoryFlags: () => NodeFactoryFlags,
  NodeFlags: () => NodeFlags,
  NodeResolutionFeatures: () => NodeResolutionFeatures,
  ObjectFlags: () => ObjectFlags,
  OperationCanceledException: () => OperationCanceledException,
  OperatorPrecedence: () => OperatorPrecedence,
  OrganizeImports: () => ts_OrganizeImports_exports,
  OrganizeImportsMode: () => OrganizeImportsMode,
  OuterExpressionKinds: () => OuterExpressionKinds,
  OutliningElementsCollector: () => ts_OutliningElementsCollector_exports,
  OutliningSpanKind: () => OutliningSpanKind,
  OutputFileType: () => OutputFileType,
  PackageJsonAutoImportPreference: () => PackageJsonAutoImportPreference,
  PackageJsonDependencyGroup: () => PackageJsonDependencyGroup,
  PatternMatchKind: () => PatternMatchKind,
  PollingInterval: () => PollingInterval,
  PollingWatchKind: () => PollingWatchKind,
  PragmaKindFlags: () => PragmaKindFlags,
  PrivateIdentifierKind: () => PrivateIdentifierKind,
  ProcessLevel: () => ProcessLevel,
  QuotePreference: () => QuotePreference,
  RelationComparisonResult: () => RelationComparisonResult,
  Rename: () => ts_Rename_exports,
  ScriptElementKind: () => ScriptElementKind,
  ScriptElementKindModifier: () => ScriptElementKindModifier,
  ScriptKind: () => ScriptKind,
  ScriptSnapshot: () => ScriptSnapshot,
  ScriptTarget: () => ScriptTarget,
  SemanticClassificationFormat: () => SemanticClassificationFormat,
  SemanticMeaning: () => SemanticMeaning,
  SemicolonPreference: () => SemicolonPreference,
  SignatureCheckMode: () => SignatureCheckMode,
  SignatureFlags: () => SignatureFlags,
  SignatureHelp: () => ts_SignatureHelp_exports,
  SignatureKind: () => SignatureKind,
  SmartSelectionRange: () => ts_SmartSelectionRange_exports,
  SnippetKind: () => SnippetKind,
  SortKind: () => SortKind,
  StructureIsReused: () => StructureIsReused,
  SymbolAccessibility: () => SymbolAccessibility,
  SymbolDisplay: () => ts_SymbolDisplay_exports,
  SymbolDisplayPartKind: () => SymbolDisplayPartKind,
  SymbolFlags: () => SymbolFlags,
  SymbolFormatFlags: () => SymbolFormatFlags,
  SyntaxKind: () => SyntaxKind,
  SyntheticSymbolKind: () => SyntheticSymbolKind,
  Ternary: () => Ternary,
  ThrottledCancellationToken: () => ThrottledCancellationToken,
  TokenClass: () => TokenClass,
  TokenFlags: () => TokenFlags,
  TransformFlags: () => TransformFlags,
  TypeFacts: () => TypeFacts,
  TypeFlags: () => TypeFlags,
  TypeFormatFlags: () => TypeFormatFlags,
  TypeMapKind: () => TypeMapKind,
  TypePredicateKind: () => TypePredicateKind,
  TypeReferenceSerializationKind: () => TypeReferenceSerializationKind,
  TypeScriptServicesFactory: () => TypeScriptServicesFactory,
  UnionReduction: () => UnionReduction,
  UpToDateStatusType: () => UpToDateStatusType,
  VarianceFlags: () => VarianceFlags,
  Version: () => Version,
  VersionRange: () => VersionRange,
  WatchDirectoryFlags: () => WatchDirectoryFlags,
  WatchDirectoryKind: () => WatchDirectoryKind,
  WatchFileKind: () => WatchFileKind,
  WatchLogLevel: () => WatchLogLevel,
  WatchType: () => WatchType,
  accessPrivateIdentifier: () => accessPrivateIdentifier,
  addEmitFlags: () => addEmitFlags,
  addEmitHelper: () => addEmitHelper,
  addEmitHelpers: () => addEmitHelpers,
  addInternalEmitFlags: () => addInternalEmitFlags,
  addNodeFactoryPatcher: () => addNodeFactoryPatcher,
  addObjectAllocatorPatcher: () => addObjectAllocatorPatcher,
  addRange: () => addRange,
  addRelatedInfo: () => addRelatedInfo,
  addSyntheticLeadingComment: () => addSyntheticLeadingComment,
  addSyntheticTrailingComment: () => addSyntheticTrailingComment,
  addToSeen: () => addToSeen,
  advancedAsyncSuperHelper: () => advancedAsyncSuperHelper,
  affectsDeclarationPathOptionDeclarations: () => affectsDeclarationPathOptionDeclarations,
  affectsEmitOptionDeclarations: () => affectsEmitOptionDeclarations,
  allKeysStartWithDot: () => allKeysStartWithDot,
  altDirectorySeparator: () => altDirectorySeparator,
  and: () => and,
  append: () => append,
  appendIfUnique: () => appendIfUnique,
  arrayFrom: () => arrayFrom,
  arrayIsEqualTo: () => arrayIsEqualTo,
  arrayIsHomogeneous: () => arrayIsHomogeneous,
  arrayIsSorted: () => arrayIsSorted,
  arrayOf: () => arrayOf,
  arrayReverseIterator: () => arrayReverseIterator,
  arrayToMap: () => arrayToMap,
  arrayToMultiMap: () => arrayToMultiMap,
  arrayToNumericMap: () => arrayToNumericMap,
  arraysEqual: () => arraysEqual,
  assertType: () => assertType,
  assign: () => assign,
  assignHelper: () => assignHelper,
  asyncDelegator: () => asyncDelegator,
  asyncGeneratorHelper: () => asyncGeneratorHelper,
  asyncSuperHelper: () => asyncSuperHelper,
  asyncValues: () => asyncValues,
  attachFileToDiagnostics: () => attachFileToDiagnostics,
  awaitHelper: () => awaitHelper,
  awaiterHelper: () => awaiterHelper,
  base64decode: () => base64decode,
  base64encode: () => base64encode,
  binarySearch: () => binarySearch,
  binarySearchKey: () => binarySearchKey,
  bindSourceFile: () => bindSourceFile,
  breakIntoCharacterSpans: () => breakIntoCharacterSpans,
  breakIntoWordSpans: () => breakIntoWordSpans,
  buildLinkParts: () => buildLinkParts,
  buildOpts: () => buildOpts,
  buildOverload: () => buildOverload,
  bundlerModuleNameResolver: () => bundlerModuleNameResolver,
  canBeConvertedToAsync: () => canBeConvertedToAsync,
  canHaveDecorators: () => canHaveDecorators,
  canHaveExportModifier: () => canHaveExportModifier,
  canHaveFlowNode: () => canHaveFlowNode,
  canHaveIllegalDecorators: () => canHaveIllegalDecorators,
  canHaveIllegalModifiers: () => canHaveIllegalModifiers,
  canHaveIllegalType: () => canHaveIllegalType,
  canHaveIllegalTypeParameters: () => canHaveIllegalTypeParameters,
  canHaveJSDoc: () => canHaveJSDoc,
  canHaveLocals: () => canHaveLocals,
  canHaveModifiers: () => canHaveModifiers,
  canHaveSymbol: () => canHaveSymbol,
  canJsonReportNoInputFiles: () => canJsonReportNoInputFiles,
  canProduceDiagnostics: () => canProduceDiagnostics,
  canUsePropertyAccess: () => canUsePropertyAccess,
  canWatchAffectingLocation: () => canWatchAffectingLocation,
  canWatchAtTypes: () => canWatchAtTypes,
  canWatchDirectoryOrFile: () => canWatchDirectoryOrFile,
  cartesianProduct: () => cartesianProduct,
  cast: () => cast,
  chainBundle: () => chainBundle,
  chainDiagnosticMessages: () => chainDiagnosticMessages,
  changeAnyExtension: () => changeAnyExtension,
  changeCompilerHostLikeToUseCache: () => changeCompilerHostLikeToUseCache,
  changeExtension: () => changeExtension,
  changesAffectModuleResolution: () => changesAffectModuleResolution,
  changesAffectingProgramStructure: () => changesAffectingProgramStructure,
  childIsDecorated: () => childIsDecorated,
  classElementOrClassElementParameterIsDecorated: () => classElementOrClassElementParameterIsDecorated,
  classOrConstructorParameterIsDecorated: () => classOrConstructorParameterIsDecorated,
  classPrivateFieldGetHelper: () => classPrivateFieldGetHelper,
  classPrivateFieldInHelper: () => classPrivateFieldInHelper,
  classPrivateFieldSetHelper: () => classPrivateFieldSetHelper,
  classicNameResolver: () => classicNameResolver,
  classifier: () => ts_classifier_exports,
  cleanExtendedConfigCache: () => cleanExtendedConfigCache,
  clear: () => clear,
  clearMap: () => clearMap,
  clearSharedExtendedConfigFileWatcher: () => clearSharedExtendedConfigFileWatcher,
  climbPastPropertyAccess: () => climbPastPropertyAccess,
  climbPastPropertyOrElementAccess: () => climbPastPropertyOrElementAccess,
  clone: () => clone,
  cloneCompilerOptions: () => cloneCompilerOptions,
  closeFileWatcher: () => closeFileWatcher,
  closeFileWatcherOf: () => closeFileWatcherOf,
  codefix: () => ts_codefix_exports,
  collapseTextChangeRangesAcrossMultipleVersions: () => collapseTextChangeRangesAcrossMultipleVersions,
  collectExternalModuleInfo: () => collectExternalModuleInfo,
  combine: () => combine,
  combinePaths: () => combinePaths,
  commentPragmas: () => commentPragmas,
  commonOptionsWithBuild: () => commonOptionsWithBuild,
  commonPackageFolders: () => commonPackageFolders,
  compact: () => compact,
  compareBooleans: () => compareBooleans,
  compareDataObjects: () => compareDataObjects,
  compareDiagnostics: () => compareDiagnostics,
  compareDiagnosticsSkipRelatedInformation: () => compareDiagnosticsSkipRelatedInformation,
  compareEmitHelpers: () => compareEmitHelpers,
  compareNumberOfDirectorySeparators: () => compareNumberOfDirectorySeparators,
  comparePaths: () => comparePaths,
  comparePathsCaseInsensitive: () => comparePathsCaseInsensitive,
  comparePathsCaseSensitive: () => comparePathsCaseSensitive,
  comparePatternKeys: () => comparePatternKeys,
  compareProperties: () => compareProperties,
  compareStringsCaseInsensitive: () => compareStringsCaseInsensitive,
  compareStringsCaseInsensitiveEslintCompatible: () => compareStringsCaseInsensitiveEslintCompatible,
  compareStringsCaseSensitive: () => compareStringsCaseSensitive,
  compareStringsCaseSensitiveUI: () => compareStringsCaseSensitiveUI,
  compareTextSpans: () => compareTextSpans,
  compareValues: () => compareValues,
  compileOnSaveCommandLineOption: () => compileOnSaveCommandLineOption,
  compilerOptionsAffectDeclarationPath: () => compilerOptionsAffectDeclarationPath,
  compilerOptionsAffectEmit: () => compilerOptionsAffectEmit,
  compilerOptionsAffectSemanticDiagnostics: () => compilerOptionsAffectSemanticDiagnostics,
  compilerOptionsDidYouMeanDiagnostics: () => compilerOptionsDidYouMeanDiagnostics,
  compilerOptionsIndicateEsModules: () => compilerOptionsIndicateEsModules,
  compose: () => compose,
  computeCommonSourceDirectoryOfFilenames: () => computeCommonSourceDirectoryOfFilenames,
  computeLineAndCharacterOfPosition: () => computeLineAndCharacterOfPosition,
  computeLineOfPosition: () => computeLineOfPosition,
  computeLineStarts: () => computeLineStarts,
  computePositionOfLineAndCharacter: () => computePositionOfLineAndCharacter,
  computeSignature: () => computeSignature,
  computeSignatureWithDiagnostics: () => computeSignatureWithDiagnostics,
  computeSuggestionDiagnostics: () => computeSuggestionDiagnostics,
  concatenate: () => concatenate,
  concatenateDiagnosticMessageChains: () => concatenateDiagnosticMessageChains,
  consumesNodeCoreModules: () => consumesNodeCoreModules,
  contains: () => contains,
  containsIgnoredPath: () => containsIgnoredPath,
  containsObjectRestOrSpread: () => containsObjectRestOrSpread,
  containsParseError: () => containsParseError,
  containsPath: () => containsPath,
  convertCompilerOptionsForTelemetry: () => convertCompilerOptionsForTelemetry,
  convertCompilerOptionsFromJson: () => convertCompilerOptionsFromJson,
  convertJsonOption: () => convertJsonOption,
  convertToBase64: () => convertToBase64,
  convertToJson: () => convertToJson,
  convertToObject: () => convertToObject,
  convertToOptionsWithAbsolutePaths: () => convertToOptionsWithAbsolutePaths,
  convertToRelativePath: () => convertToRelativePath,
  convertToTSConfig: () => convertToTSConfig,
  convertTypeAcquisitionFromJson: () => convertTypeAcquisitionFromJson,
  copyComments: () => copyComments,
  copyEntries: () => copyEntries,
  copyLeadingComments: () => copyLeadingComments,
  copyProperties: () => copyProperties,
  copyTrailingAsLeadingComments: () => copyTrailingAsLeadingComments,
  copyTrailingComments: () => copyTrailingComments,
  couldStartTrivia: () => couldStartTrivia,
  countWhere: () => countWhere,
  createAbstractBuilder: () => createAbstractBuilder,
  createAccessorPropertyBackingField: () => createAccessorPropertyBackingField,
  createAccessorPropertyGetRedirector: () => createAccessorPropertyGetRedirector,
  createAccessorPropertySetRedirector: () => createAccessorPropertySetRedirector,
  createBaseNodeFactory: () => createBaseNodeFactory,
  createBinaryExpressionTrampoline: () => createBinaryExpressionTrampoline,
  createBindingHelper: () => createBindingHelper,
  createBuildInfo: () => createBuildInfo,
  createBuilderProgram: () => createBuilderProgram,
  createBuilderProgramUsingProgramBuildInfo: () => createBuilderProgramUsingProgramBuildInfo,
  createBuilderStatusReporter: () => createBuilderStatusReporter,
  createCacheWithRedirects: () => createCacheWithRedirects,
  createCacheableExportInfoMap: () => createCacheableExportInfoMap,
  createCachedDirectoryStructureHost: () => createCachedDirectoryStructureHost,
  createClassifier: () => createClassifier,
  createCommentDirectivesMap: () => createCommentDirectivesMap,
  createCompilerDiagnostic: () => createCompilerDiagnostic,
  createCompilerDiagnosticForInvalidCustomType: () => createCompilerDiagnosticForInvalidCustomType,
  createCompilerDiagnosticFromMessageChain: () => createCompilerDiagnosticFromMessageChain,
  createCompilerHost: () => createCompilerHost,
  createCompilerHostFromProgramHost: () => createCompilerHostFromProgramHost,
  createCompilerHostWorker: () => createCompilerHostWorker,
  createDetachedDiagnostic: () => createDetachedDiagnostic,
  createDiagnosticCollection: () => createDiagnosticCollection,
  createDiagnosticForFileFromMessageChain: () => createDiagnosticForFileFromMessageChain,
  createDiagnosticForNode: () => createDiagnosticForNode,
  createDiagnosticForNodeArray: () => createDiagnosticForNodeArray,
  createDiagnosticForNodeArrayFromMessageChain: () => createDiagnosticForNodeArrayFromMessageChain,
  createDiagnosticForNodeFromMessageChain: () => createDiagnosticForNodeFromMessageChain,
  createDiagnosticForNodeInSourceFile: () => createDiagnosticForNodeInSourceFile,
  createDiagnosticForRange: () => createDiagnosticForRange,
  createDiagnosticMessageChainFromDiagnostic: () => createDiagnosticMessageChainFromDiagnostic,
  createDiagnosticReporter: () => createDiagnosticReporter,
  createDocumentPositionMapper: () => createDocumentPositionMapper,
  createDocumentRegistry: () => createDocumentRegistry,
  createDocumentRegistryInternal: () => createDocumentRegistryInternal,
  createEmitAndSemanticDiagnosticsBuilderProgram: () => createEmitAndSemanticDiagnosticsBuilderProgram,
  createEmitHelperFactory: () => createEmitHelperFactory,
  createEmptyExports: () => createEmptyExports,
  createExpressionForJsxElement: () => createExpressionForJsxElement,
  createExpressionForJsxFragment: () => createExpressionForJsxFragment,
  createExpressionForObjectLiteralElementLike: () => createExpressionForObjectLiteralElementLike,
  createExpressionForPropertyName: () => createExpressionForPropertyName,
  createExpressionFromEntityName: () => createExpressionFromEntityName,
  createExternalHelpersImportDeclarationIfNeeded: () => createExternalHelpersImportDeclarationIfNeeded,
  createFileDiagnostic: () => createFileDiagnostic,
  createFileDiagnosticFromMessageChain: () => createFileDiagnosticFromMessageChain,
  createForOfBindingStatement: () => createForOfBindingStatement,
  createGetCanonicalFileName: () => createGetCanonicalFileName,
  createGetSourceFile: () => createGetSourceFile,
  createGetSymbolAccessibilityDiagnosticForNode: () => createGetSymbolAccessibilityDiagnosticForNode,
  createGetSymbolAccessibilityDiagnosticForNodeName: () => createGetSymbolAccessibilityDiagnosticForNodeName,
  createGetSymbolWalker: () => createGetSymbolWalker,
  createIncrementalCompilerHost: () => createIncrementalCompilerHost,
  createIncrementalProgram: () => createIncrementalProgram,
  createInputFiles: () => createInputFiles,
  createInputFilesWithFilePaths: () => createInputFilesWithFilePaths,
  createInputFilesWithFileTexts: () => createInputFilesWithFileTexts,
  createJsxFactoryExpression: () => createJsxFactoryExpression,
  createLanguageService: () => createLanguageService,
  createLanguageServiceSourceFile: () => createLanguageServiceSourceFile,
  createMemberAccessForPropertyName: () => createMemberAccessForPropertyName,
  createModeAwareCache: () => createModeAwareCache,
  createModeAwareCacheKey: () => createModeAwareCacheKey,
  createModuleNotFoundChain: () => createModuleNotFoundChain,
  createModuleResolutionCache: () => createModuleResolutionCache,
  createModuleResolutionLoader: () => createModuleResolutionLoader,
  createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost,
  createMultiMap: () => createMultiMap,
  createNodeConverters: () => createNodeConverters,
  createNodeFactory: () => createNodeFactory,
  createOptionNameMap: () => createOptionNameMap,
  createOverload: () => createOverload,
  createPackageJsonImportFilter: () => createPackageJsonImportFilter,
  createPackageJsonInfo: () => createPackageJsonInfo,
  createParenthesizerRules: () => createParenthesizerRules,
  createPatternMatcher: () => createPatternMatcher,
  createPrependNodes: () => createPrependNodes,
  createPrinter: () => createPrinter,
  createPrinterWithDefaults: () => createPrinterWithDefaults,
  createPrinterWithRemoveComments: () => createPrinterWithRemoveComments,
  createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape,
  createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon,
  createProgram: () => createProgram,
  createProgramHost: () => createProgramHost,
  createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral,
  createQueue: () => createQueue,
  createRange: () => createRange,
  createRedirectedBuilderProgram: () => createRedirectedBuilderProgram,
  createResolutionCache: () => createResolutionCache,
  createRuntimeTypeSerializer: () => createRuntimeTypeSerializer,
  createScanner: () => createScanner,
  createSemanticDiagnosticsBuilderProgram: () => createSemanticDiagnosticsBuilderProgram,
  createSet: () => createSet,
  createSolutionBuilder: () => createSolutionBuilder,
  createSolutionBuilderHost: () => createSolutionBuilderHost,
  createSolutionBuilderWithWatch: () => createSolutionBuilderWithWatch,
  createSolutionBuilderWithWatchHost: () => createSolutionBuilderWithWatchHost,
  createSortedArray: () => createSortedArray,
  createSourceFile: () => createSourceFile,
  createSourceMapGenerator: () => createSourceMapGenerator,
  createSourceMapSource: () => createSourceMapSource,
  createSuperAccessVariableStatement: () => createSuperAccessVariableStatement,
  createSymbolTable: () => createSymbolTable,
  createSymlinkCache: () => createSymlinkCache,
  createSystemWatchFunctions: () => createSystemWatchFunctions,
  createTextChange: () => createTextChange,
  createTextChangeFromStartLength: () => createTextChangeFromStartLength,
  createTextChangeRange: () => createTextChangeRange,
  createTextRangeFromNode: () => createTextRangeFromNode,
  createTextRangeFromSpan: () => createTextRangeFromSpan,
  createTextSpan: () => createTextSpan,
  createTextSpanFromBounds: () => createTextSpanFromBounds,
  createTextSpanFromNode: () => createTextSpanFromNode,
  createTextSpanFromRange: () => createTextSpanFromRange,
  createTextSpanFromStringLiteralLikeContent: () => createTextSpanFromStringLiteralLikeContent,
  createTextWriter: () => createTextWriter,
  createTokenRange: () => createTokenRange,
  createTypeChecker: () => createTypeChecker,
  createTypeReferenceDirectiveResolutionCache: () => createTypeReferenceDirectiveResolutionCache,
  createTypeReferenceResolutionLoader: () => createTypeReferenceResolutionLoader,
  createUnparsedSourceFile: () => createUnparsedSourceFile,
  createWatchCompilerHost: () => createWatchCompilerHost2,
  createWatchCompilerHostOfConfigFile: () => createWatchCompilerHostOfConfigFile,
  createWatchCompilerHostOfFilesAndCompilerOptions: () => createWatchCompilerHostOfFilesAndCompilerOptions,
  createWatchFactory: () => createWatchFactory,
  createWatchHost: () => createWatchHost,
  createWatchProgram: () => createWatchProgram,
  createWatchStatusReporter: () => createWatchStatusReporter,
  createWriteFileMeasuringIO: () => createWriteFileMeasuringIO,
  declarationNameToString: () => declarationNameToString,
  decodeMappings: () => decodeMappings,
  decodedTextSpanIntersectsWith: () => decodedTextSpanIntersectsWith,
  decorateHelper: () => decorateHelper,
  deduplicate: () => deduplicate,
  defaultIncludeSpec: () => defaultIncludeSpec,
  defaultInitCompilerOptions: () => defaultInitCompilerOptions,
  defaultMaximumTruncationLength: () => defaultMaximumTruncationLength,
  detectSortCaseSensitivity: () => detectSortCaseSensitivity,
  diagnosticCategoryName: () => diagnosticCategoryName,
  diagnosticToString: () => diagnosticToString,
  directoryProbablyExists: () => directoryProbablyExists,
  directorySeparator: () => directorySeparator,
  displayPart: () => displayPart,
  displayPartsToString: () => displayPartsToString,
  disposeEmitNodes: () => disposeEmitNodes,
  documentSpansEqual: () => documentSpansEqual,
  dumpTracingLegend: () => dumpTracingLegend,
  elementAt: () => elementAt,
  elideNodes: () => elideNodes,
  emitComments: () => emitComments,
  emitDetachedComments: () => emitDetachedComments,
  emitFiles: () => emitFiles,
  emitFilesAndReportErrors: () => emitFilesAndReportErrors,
  emitFilesAndReportErrorsAndGetExitStatus: () => emitFilesAndReportErrorsAndGetExitStatus,
  emitModuleKindIsNonNodeESM: () => emitModuleKindIsNonNodeESM,
  emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition,
  emitNewLineBeforeLeadingComments: () => emitNewLineBeforeLeadingComments,
  emitNewLineBeforeLeadingCommentsOfPosition: () => emitNewLineBeforeLeadingCommentsOfPosition,
  emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics,
  emitUsingBuildInfo: () => emitUsingBuildInfo,
  emptyArray: () => emptyArray,
  emptyFileSystemEntries: () => emptyFileSystemEntries,
  emptyMap: () => emptyMap,
  emptyOptions: () => emptyOptions,
  emptySet: () => emptySet,
  endsWith: () => endsWith,
  ensurePathIsNonModuleName: () => ensurePathIsNonModuleName,
  ensureScriptKind: () => ensureScriptKind,
  ensureTrailingDirectorySeparator: () => ensureTrailingDirectorySeparator,
  entityNameToString: () => entityNameToString,
  enumerateInsertsAndDeletes: () => enumerateInsertsAndDeletes,
  equalOwnProperties: () => equalOwnProperties,
  equateStringsCaseInsensitive: () => equateStringsCaseInsensitive,
  equateStringsCaseSensitive: () => equateStringsCaseSensitive,
  equateValues: () => equateValues,
  esDecorateHelper: () => esDecorateHelper,
  escapeJsxAttributeString: () => escapeJsxAttributeString,
  escapeLeadingUnderscores: () => escapeLeadingUnderscores,
  escapeNonAsciiString: () => escapeNonAsciiString,
  escapeSnippetText: () => escapeSnippetText,
  escapeString: () => escapeString,
  every: () => every,
  expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression,
  explainFiles: () => explainFiles,
  explainIfFileIsRedirectAndImpliedFormat: () => explainIfFileIsRedirectAndImpliedFormat,
  exportAssignmentIsAlias: () => exportAssignmentIsAlias,
  exportStarHelper: () => exportStarHelper,
  expressionResultIsUnused: () => expressionResultIsUnused,
  extend: () => extend,
  extendsHelper: () => extendsHelper,
  extensionFromPath: () => extensionFromPath,
  extensionIsTS: () => extensionIsTS,
  extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution,
  externalHelpersModuleNameText: () => externalHelpersModuleNameText,
  factory: () => factory,
  fileExtensionIs: () => fileExtensionIs,
  fileExtensionIsOneOf: () => fileExtensionIsOneOf,
  fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics,
  fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire,
  filter: () => filter,
  filterMutate: () => filterMutate,
  filterSemanticDiagnostics: () => filterSemanticDiagnostics,
  find: () => find,
  findAncestor: () => findAncestor,
  findBestPatternMatch: () => findBestPatternMatch,
  findChildOfKind: () => findChildOfKind,
  findComputedPropertyNameCacheAssignment: () => findComputedPropertyNameCacheAssignment,
  findConfigFile: () => findConfigFile,
  findContainingList: () => findContainingList,
  findDiagnosticForNode: () => findDiagnosticForNode,
  findFirstNonJsxWhitespaceToken: () => findFirstNonJsxWhitespaceToken,
  findIndex: () => findIndex,
  findLast: () => findLast,
  findLastIndex: () => findLastIndex,
  findListItemInfo: () => findListItemInfo,
  findMap: () => findMap,
  findModifier: () => findModifier,
  findNextToken: () => findNextToken,
  findPackageJson: () => findPackageJson,
  findPackageJsons: () => findPackageJsons,
  findPrecedingMatchingToken: () => findPrecedingMatchingToken,
  findPrecedingToken: () => findPrecedingToken,
  findSuperStatementIndex: () => findSuperStatementIndex,
  findTokenOnLeftOfPosition: () => findTokenOnLeftOfPosition,
  findUseStrictPrologue: () => findUseStrictPrologue,
  first: () => first,
  firstDefined: () => firstDefined,
  firstDefinedIterator: () => firstDefinedIterator,
  firstIterator: () => firstIterator,
  firstOrOnly: () => firstOrOnly,
  firstOrUndefined: () => firstOrUndefined,
  firstOrUndefinedIterator: () => firstOrUndefinedIterator,
  fixupCompilerOptions: () => fixupCompilerOptions,
  flatMap: () => flatMap,
  flatMapIterator: () => flatMapIterator,
  flatMapToMutable: () => flatMapToMutable,
  flatten: () => flatten,
  flattenCommaList: () => flattenCommaList,
  flattenDestructuringAssignment: () => flattenDestructuringAssignment,
  flattenDestructuringBinding: () => flattenDestructuringBinding,
  flattenDiagnosticMessageText: () => flattenDiagnosticMessageText,
  forEach: () => forEach,
  forEachAncestor: () => forEachAncestor,
  forEachAncestorDirectory: () => forEachAncestorDirectory,
  forEachChild: () => forEachChild,
  forEachChildRecursively: () => forEachChildRecursively,
  forEachEmittedFile: () => forEachEmittedFile,
  forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer,
  forEachEntry: () => forEachEntry,
  forEachExternalModuleToImportFrom: () => forEachExternalModuleToImportFrom,
  forEachImportClauseDeclaration: () => forEachImportClauseDeclaration,
  forEachKey: () => forEachKey,
  forEachLeadingCommentRange: () => forEachLeadingCommentRange,
  forEachNameInAccessChainWalkingLeft: () => forEachNameInAccessChainWalkingLeft,
  forEachPropertyAssignment: () => forEachPropertyAssignment,
  forEachResolvedProjectReference: () => forEachResolvedProjectReference,
  forEachReturnStatement: () => forEachReturnStatement,
  forEachRight: () => forEachRight,
  forEachTrailingCommentRange: () => forEachTrailingCommentRange,
  forEachTsConfigPropArray: () => forEachTsConfigPropArray,
  forEachUnique: () => forEachUnique,
  forEachYieldExpression: () => forEachYieldExpression,
  forSomeAncestorDirectory: () => forSomeAncestorDirectory,
  formatColorAndReset: () => formatColorAndReset,
  formatDiagnostic: () => formatDiagnostic,
  formatDiagnostics: () => formatDiagnostics,
  formatDiagnosticsWithColorAndContext: () => formatDiagnosticsWithColorAndContext,
  formatGeneratedName: () => formatGeneratedName,
  formatGeneratedNamePart: () => formatGeneratedNamePart,
  formatLocation: () => formatLocation,
  formatMessage: () => formatMessage,
  formatStringFromArgs: () => formatStringFromArgs,
  formatting: () => ts_formatting_exports,
  fullTripleSlashAMDReferencePathRegEx: () => fullTripleSlashAMDReferencePathRegEx,
  fullTripleSlashReferencePathRegEx: () => fullTripleSlashReferencePathRegEx,
  generateDjb2Hash: () => generateDjb2Hash,
  generateTSConfig: () => generateTSConfig,
  generatorHelper: () => generatorHelper,
  getAdjustedReferenceLocation: () => getAdjustedReferenceLocation,
  getAdjustedRenameLocation: () => getAdjustedRenameLocation,
  getAliasDeclarationFromName: () => getAliasDeclarationFromName,
  getAllAccessorDeclarations: () => getAllAccessorDeclarations,
  getAllDecoratorsOfClass: () => getAllDecoratorsOfClass,
  getAllDecoratorsOfClassElement: () => getAllDecoratorsOfClassElement,
  getAllJSDocTags: () => getAllJSDocTags,
  getAllJSDocTagsOfKind: () => getAllJSDocTagsOfKind,
  getAllKeys: () => getAllKeys,
  getAllProjectOutputs: () => getAllProjectOutputs,
  getAllSuperTypeNodes: () => getAllSuperTypeNodes,
  getAllUnscopedEmitHelpers: () => getAllUnscopedEmitHelpers,
  getAllowJSCompilerOption: () => getAllowJSCompilerOption,
  getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports,
  getAncestor: () => getAncestor,
  getAnyExtensionFromPath: () => getAnyExtensionFromPath,
  getAreDeclarationMapsEnabled: () => getAreDeclarationMapsEnabled,
  getAssignedExpandoInitializer: () => getAssignedExpandoInitializer,
  getAssignedName: () => getAssignedName,
  getAssignmentDeclarationKind: () => getAssignmentDeclarationKind,
  getAssignmentDeclarationPropertyAccessKind: () => getAssignmentDeclarationPropertyAccessKind,
  getAssignmentTargetKind: () => getAssignmentTargetKind,
  getAutomaticTypeDirectiveNames: () => getAutomaticTypeDirectiveNames,
  getBaseFileName: () => getBaseFileName,
  getBinaryOperatorPrecedence: () => getBinaryOperatorPrecedence,
  getBuildInfo: () => getBuildInfo,
  getBuildInfoFileVersionMap: () => getBuildInfoFileVersionMap,
  getBuildInfoText: () => getBuildInfoText,
  getBuildOrderFromAnyBuildOrder: () => getBuildOrderFromAnyBuildOrder,
  getBuilderCreationParameters: () => getBuilderCreationParameters,
  getBuilderFileEmit: () => getBuilderFileEmit,
  getCheckFlags: () => getCheckFlags,
  getClassExtendsHeritageElement: () => getClassExtendsHeritageElement,
  getClassLikeDeclarationOfSymbol: () => getClassLikeDeclarationOfSymbol,
  getCombinedLocalAndExportSymbolFlags: () => getCombinedLocalAndExportSymbolFlags,
  getCombinedModifierFlags: () => getCombinedModifierFlags,
  getCombinedNodeFlags: () => getCombinedNodeFlags,
  getCombinedNodeFlagsAlwaysIncludeJSDoc: () => getCombinedNodeFlagsAlwaysIncludeJSDoc,
  getCommentRange: () => getCommentRange,
  getCommonSourceDirectory: () => getCommonSourceDirectory,
  getCommonSourceDirectoryOfConfig: () => getCommonSourceDirectoryOfConfig,
  getCompilerOptionValue: () => getCompilerOptionValue,
  getCompilerOptionsDiffValue: () => getCompilerOptionsDiffValue,
  getConditions: () => getConditions,
  getConfigFileParsingDiagnostics: () => getConfigFileParsingDiagnostics,
  getConstantValue: () => getConstantValue,
  getContainerNode: () => getContainerNode,
  getContainingClass: () => getContainingClass,
  getContainingClassStaticBlock: () => getContainingClassStaticBlock,
  getContainingFunction: () => getContainingFunction,
  getContainingFunctionDeclaration: () => getContainingFunctionDeclaration,
  getContainingFunctionOrClassStaticBlock: () => getContainingFunctionOrClassStaticBlock,
  getContainingNodeArray: () => getContainingNodeArray,
  getContainingObjectLiteralElement: () => getContainingObjectLiteralElement,
  getContextualTypeFromParent: () => getContextualTypeFromParent,
  getContextualTypeFromParentOrAncestorTypeNode: () => getContextualTypeFromParentOrAncestorTypeNode,
  getCurrentTime: () => getCurrentTime,
  getDeclarationDiagnostics: () => getDeclarationDiagnostics,
  getDeclarationEmitExtensionForPath: () => getDeclarationEmitExtensionForPath,
  getDeclarationEmitOutputFilePath: () => getDeclarationEmitOutputFilePath,
  getDeclarationEmitOutputFilePathWorker: () => getDeclarationEmitOutputFilePathWorker,
  getDeclarationFromName: () => getDeclarationFromName,
  getDeclarationModifierFlagsFromSymbol: () => getDeclarationModifierFlagsFromSymbol,
  getDeclarationOfKind: () => getDeclarationOfKind,
  getDeclarationsOfKind: () => getDeclarationsOfKind,
  getDeclaredExpandoInitializer: () => getDeclaredExpandoInitializer,
  getDecorators: () => getDecorators,
  getDefaultCompilerOptions: () => getDefaultCompilerOptions2,
  getDefaultExportInfoWorker: () => getDefaultExportInfoWorker,
  getDefaultFormatCodeSettings: () => getDefaultFormatCodeSettings,
  getDefaultLibFileName: () => getDefaultLibFileName,
  getDefaultLibFilePath: () => getDefaultLibFilePath,
  getDefaultLikeExportInfo: () => getDefaultLikeExportInfo,
  getDiagnosticText: () => getDiagnosticText,
  getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan,
  getDirectoryPath: () => getDirectoryPath,
  getDirectoryToWatchFailedLookupLocation: () => getDirectoryToWatchFailedLookupLocation,
  getDirectoryToWatchFailedLookupLocationFromTypeRoot: () => getDirectoryToWatchFailedLookupLocationFromTypeRoot,
  getDocumentPositionMapper: () => getDocumentPositionMapper,
  getESModuleInterop: () => getESModuleInterop,
  getEditsForFileRename: () => getEditsForFileRename,
  getEffectiveBaseTypeNode: () => getEffectiveBaseTypeNode,
  getEffectiveConstraintOfTypeParameter: () => getEffectiveConstraintOfTypeParameter,
  getEffectiveContainerForJSDocTemplateTag: () => getEffectiveContainerForJSDocTemplateTag,
  getEffectiveImplementsTypeNodes: () => getEffectiveImplementsTypeNodes,
  getEffectiveInitializer: () => getEffectiveInitializer,
  getEffectiveJSDocHost: () => getEffectiveJSDocHost,
  getEffectiveModifierFlags: () => getEffectiveModifierFlags,
  getEffectiveModifierFlagsAlwaysIncludeJSDoc: () => getEffectiveModifierFlagsAlwaysIncludeJSDoc,
  getEffectiveModifierFlagsNoCache: () => getEffectiveModifierFlagsNoCache,
  getEffectiveReturnTypeNode: () => getEffectiveReturnTypeNode,
  getEffectiveSetAccessorTypeAnnotationNode: () => getEffectiveSetAccessorTypeAnnotationNode,
  getEffectiveTypeAnnotationNode: () => getEffectiveTypeAnnotationNode,
  getEffectiveTypeParameterDeclarations: () => getEffectiveTypeParameterDeclarations,
  getEffectiveTypeRoots: () => getEffectiveTypeRoots,
  getElementOrPropertyAccessArgumentExpressionOrName: () => getElementOrPropertyAccessArgumentExpressionOrName,
  getElementOrPropertyAccessName: () => getElementOrPropertyAccessName,
  getElementsOfBindingOrAssignmentPattern: () => getElementsOfBindingOrAssignmentPattern,
  getEmitDeclarations: () => getEmitDeclarations,
  getEmitFlags: () => getEmitFlags,
  getEmitHelpers: () => getEmitHelpers,
  getEmitModuleDetectionKind: () => getEmitModuleDetectionKind,
  getEmitModuleKind: () => getEmitModuleKind,
  getEmitModuleResolutionKind: () => getEmitModuleResolutionKind,
  getEmitScriptTarget: () => getEmitScriptTarget,
  getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer,
  getEncodedSemanticClassifications: () => getEncodedSemanticClassifications,
  getEncodedSyntacticClassifications: () => getEncodedSyntacticClassifications,
  getEndLinePosition: () => getEndLinePosition,
  getEntityNameFromTypeNode: () => getEntityNameFromTypeNode,
  getEntrypointsFromPackageJsonInfo: () => getEntrypointsFromPackageJsonInfo,
  getErrorCountForSummary: () => getErrorCountForSummary,
  getErrorSpanForNode: () => getErrorSpanForNode,
  getErrorSummaryText: () => getErrorSummaryText,
  getEscapedTextOfIdentifierOrLiteral: () => getEscapedTextOfIdentifierOrLiteral,
  getEscapedTextOfJsxAttributeName: () => getEscapedTextOfJsxAttributeName,
  getEscapedTextOfJsxNamespacedName: () => getEscapedTextOfJsxNamespacedName,
  getExpandoInitializer: () => getExpandoInitializer,
  getExportAssignmentExpression: () => getExportAssignmentExpression,
  getExportInfoMap: () => getExportInfoMap,
  getExportNeedsImportStarHelper: () => getExportNeedsImportStarHelper,
  getExpressionAssociativity: () => getExpressionAssociativity,
  getExpressionPrecedence: () => getExpressionPrecedence,
  getExternalHelpersModuleName: () => getExternalHelpersModuleName,
  getExternalModuleImportEqualsDeclarationExpression: () => getExternalModuleImportEqualsDeclarationExpression,
  getExternalModuleName: () => getExternalModuleName,
  getExternalModuleNameFromDeclaration: () => getExternalModuleNameFromDeclaration,
  getExternalModuleNameFromPath: () => getExternalModuleNameFromPath,
  getExternalModuleNameLiteral: () => getExternalModuleNameLiteral,
  getExternalModuleRequireArgument: () => getExternalModuleRequireArgument,
  getFallbackOptions: () => getFallbackOptions,
  getFileEmitOutput: () => getFileEmitOutput,
  getFileMatcherPatterns: () => getFileMatcherPatterns,
  getFileNamesFromConfigSpecs: () => getFileNamesFromConfigSpecs,
  getFileWatcherEventKind: () => getFileWatcherEventKind,
  getFilesInErrorForSummary: () => getFilesInErrorForSummary,
  getFirstConstructorWithBody: () => getFirstConstructorWithBody,
  getFirstIdentifier: () => getFirstIdentifier,
  getFirstNonSpaceCharacterPosition: () => getFirstNonSpaceCharacterPosition,
  getFirstProjectOutput: () => getFirstProjectOutput,
  getFixableErrorSpanExpression: () => getFixableErrorSpanExpression,
  getFormatCodeSettingsForWriting: () => getFormatCodeSettingsForWriting,
  getFullWidth: () => getFullWidth,
  getFunctionFlags: () => getFunctionFlags,
  getHeritageClause: () => getHeritageClause,
  getHostSignatureFromJSDoc: () => getHostSignatureFromJSDoc,
  getIdentifierAutoGenerate: () => getIdentifierAutoGenerate,
  getIdentifierGeneratedImportReference: () => getIdentifierGeneratedImportReference,
  getIdentifierTypeArguments: () => getIdentifierTypeArguments,
  getImmediatelyInvokedFunctionExpression: () => getImmediatelyInvokedFunctionExpression,
  getImpliedNodeFormatForFile: () => getImpliedNodeFormatForFile,
  getImpliedNodeFormatForFileWorker: () => getImpliedNodeFormatForFileWorker,
  getImportNeedsImportDefaultHelper: () => getImportNeedsImportDefaultHelper,
  getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper,
  getIndentSize: () => getIndentSize,
  getIndentString: () => getIndentString,
  getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom,
  getInitializedVariables: () => getInitializedVariables,
  getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression,
  getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement,
  getInterfaceBaseTypeNodes: () => getInterfaceBaseTypeNodes,
  getInternalEmitFlags: () => getInternalEmitFlags,
  getInvokedExpression: () => getInvokedExpression,
  getIsolatedModules: () => getIsolatedModules,
  getJSDocAugmentsTag: () => getJSDocAugmentsTag,
  getJSDocClassTag: () => getJSDocClassTag,
  getJSDocCommentRanges: () => getJSDocCommentRanges,
  getJSDocCommentsAndTags: () => getJSDocCommentsAndTags,
  getJSDocDeprecatedTag: () => getJSDocDeprecatedTag,
  getJSDocDeprecatedTagNoCache: () => getJSDocDeprecatedTagNoCache,
  getJSDocEnumTag: () => getJSDocEnumTag,
  getJSDocHost: () => getJSDocHost,
  getJSDocImplementsTags: () => getJSDocImplementsTags,
  getJSDocOverrideTagNoCache: () => getJSDocOverrideTagNoCache,
  getJSDocParameterTags: () => getJSDocParameterTags,
  getJSDocParameterTagsNoCache: () => getJSDocParameterTagsNoCache,
  getJSDocPrivateTag: () => getJSDocPrivateTag,
  getJSDocPrivateTagNoCache: () => getJSDocPrivateTagNoCache,
  getJSDocProtectedTag: () => getJSDocProtectedTag,
  getJSDocProtectedTagNoCache: () => getJSDocProtectedTagNoCache,
  getJSDocPublicTag: () => getJSDocPublicTag,
  getJSDocPublicTagNoCache: () => getJSDocPublicTagNoCache,
  getJSDocReadonlyTag: () => getJSDocReadonlyTag,
  getJSDocReadonlyTagNoCache: () => getJSDocReadonlyTagNoCache,
  getJSDocReturnTag: () => getJSDocReturnTag,
  getJSDocReturnType: () => getJSDocReturnType,
  getJSDocRoot: () => getJSDocRoot,
  getJSDocSatisfiesExpressionType: () => getJSDocSatisfiesExpressionType,
  getJSDocSatisfiesTag: () => getJSDocSatisfiesTag,
  getJSDocTags: () => getJSDocTags,
  getJSDocTagsNoCache: () => getJSDocTagsNoCache,
  getJSDocTemplateTag: () => getJSDocTemplateTag,
  getJSDocThisTag: () => getJSDocThisTag,
  getJSDocType: () => getJSDocType,
  getJSDocTypeAliasName: () => getJSDocTypeAliasName,
  getJSDocTypeAssertionType: () => getJSDocTypeAssertionType,
  getJSDocTypeParameterDeclarations: () => getJSDocTypeParameterDeclarations,
  getJSDocTypeParameterTags: () => getJSDocTypeParameterTags,
  getJSDocTypeParameterTagsNoCache: () => getJSDocTypeParameterTagsNoCache,
  getJSDocTypeTag: () => getJSDocTypeTag,
  getJSXImplicitImportBase: () => getJSXImplicitImportBase,
  getJSXRuntimeImport: () => getJSXRuntimeImport,
  getJSXTransformEnabled: () => getJSXTransformEnabled,
  getKeyForCompilerOptions: () => getKeyForCompilerOptions,
  getLanguageVariant: () => getLanguageVariant,
  getLastChild: () => getLastChild,
  getLeadingCommentRanges: () => getLeadingCommentRanges,
  getLeadingCommentRangesOfNode: () => getLeadingCommentRangesOfNode,
  getLeftmostAccessExpression: () => getLeftmostAccessExpression,
  getLeftmostExpression: () => getLeftmostExpression,
  getLineAndCharacterOfPosition: () => getLineAndCharacterOfPosition,
  getLineInfo: () => getLineInfo,
  getLineOfLocalPosition: () => getLineOfLocalPosition,
  getLineOfLocalPositionFromLineMap: () => getLineOfLocalPositionFromLineMap,
  getLineStartPositionForPosition: () => getLineStartPositionForPosition,
  getLineStarts: () => getLineStarts,
  getLinesBetweenPositionAndNextNonWhitespaceCharacter: () => getLinesBetweenPositionAndNextNonWhitespaceCharacter,
  getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter: () => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter,
  getLinesBetweenPositions: () => getLinesBetweenPositions,
  getLinesBetweenRangeEndAndRangeStart: () => getLinesBetweenRangeEndAndRangeStart,
  getLinesBetweenRangeEndPositions: () => getLinesBetweenRangeEndPositions,
  getLiteralText: () => getLiteralText,
  getLocalNameForExternalImport: () => getLocalNameForExternalImport,
  getLocalSymbolForExportDefault: () => getLocalSymbolForExportDefault,
  getLocaleSpecificMessage: () => getLocaleSpecificMessage,
  getLocaleTimeString: () => getLocaleTimeString,
  getMappedContextSpan: () => getMappedContextSpan,
  getMappedDocumentSpan: () => getMappedDocumentSpan,
  getMappedLocation: () => getMappedLocation,
  getMatchedFileSpec: () => getMatchedFileSpec,
  getMatchedIncludeSpec: () => getMatchedIncludeSpec,
  getMeaningFromDeclaration: () => getMeaningFromDeclaration,
  getMeaningFromLocation: () => getMeaningFromLocation,
  getMembersOfDeclaration: () => getMembersOfDeclaration,
  getModeForFileReference: () => getModeForFileReference,
  getModeForResolutionAtIndex: () => getModeForResolutionAtIndex,
  getModeForUsageLocation: () => getModeForUsageLocation,
  getModifiedTime: () => getModifiedTime,
  getModifiers: () => getModifiers,
  getModuleInstanceState: () => getModuleInstanceState,
  getModuleNameStringLiteralAt: () => getModuleNameStringLiteralAt,
  getModuleSpecifierEndingPreference: () => getModuleSpecifierEndingPreference,
  getModuleSpecifierResolverHost: () => getModuleSpecifierResolverHost,
  getNameForExportedSymbol: () => getNameForExportedSymbol,
  getNameFromIndexInfo: () => getNameFromIndexInfo,
  getNameFromPropertyName: () => getNameFromPropertyName,
  getNameOfAccessExpression: () => getNameOfAccessExpression,
  getNameOfCompilerOptionValue: () => getNameOfCompilerOptionValue,
  getNameOfDeclaration: () => getNameOfDeclaration,
  getNameOfExpando: () => getNameOfExpando,
  getNameOfJSDocTypedef: () => getNameOfJSDocTypedef,
  getNameOrArgument: () => getNameOrArgument,
  getNameTable: () => getNameTable,
  getNamesForExportedSymbol: () => getNamesForExportedSymbol,
  getNamespaceDeclarationNode: () => getNamespaceDeclarationNode,
  getNewLineCharacter: () => getNewLineCharacter,
  getNewLineKind: () => getNewLineKind,
  getNewLineOrDefaultFromHost: () => getNewLineOrDefaultFromHost,
  getNewTargetContainer: () => getNewTargetContainer,
  getNextJSDocCommentLocation: () => getNextJSDocCommentLocation,
  getNodeForGeneratedName: () => getNodeForGeneratedName,
  getNodeId: () => getNodeId,
  getNodeKind: () => getNodeKind,
  getNodeModifiers: () => getNodeModifiers,
  getNodeModulePathParts: () => getNodeModulePathParts,
  getNonAssignedNameOfDeclaration: () => getNonAssignedNameOfDeclaration,
  getNonAssignmentOperatorForCompoundAssignment: () => getNonAssignmentOperatorForCompoundAssignment,
  getNonAugmentationDeclaration: () => getNonAugmentationDeclaration,
  getNonDecoratorTokenPosOfNode: () => getNonDecoratorTokenPosOfNode,
  getNormalizedAbsolutePath: () => getNormalizedAbsolutePath,
  getNormalizedAbsolutePathWithoutRoot: () => getNormalizedAbsolutePathWithoutRoot,
  getNormalizedPathComponents: () => getNormalizedPathComponents,
  getObjectFlags: () => getObjectFlags,
  getOperator: () => getOperator,
  getOperatorAssociativity: () => getOperatorAssociativity,
  getOperatorPrecedence: () => getOperatorPrecedence,
  getOptionFromName: () => getOptionFromName,
  getOptionsForLibraryResolution: () => getOptionsForLibraryResolution,
  getOptionsNameMap: () => getOptionsNameMap,
  getOrCreateEmitNode: () => getOrCreateEmitNode,
  getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded,
  getOrUpdate: () => getOrUpdate,
  getOriginalNode: () => getOriginalNode,
  getOriginalNodeId: () => getOriginalNodeId,
  getOriginalSourceFile: () => getOriginalSourceFile,
  getOutputDeclarationFileName: () => getOutputDeclarationFileName,
  getOutputExtension: () => getOutputExtension,
  getOutputFileNames: () => getOutputFileNames,
  getOutputPathsFor: () => getOutputPathsFor,
  getOutputPathsForBundle: () => getOutputPathsForBundle,
  getOwnEmitOutputFilePath: () => getOwnEmitOutputFilePath,
  getOwnKeys: () => getOwnKeys,
  getOwnValues: () => getOwnValues,
  getPackageJsonInfo: () => getPackageJsonInfo,
  getPackageJsonTypesVersionsPaths: () => getPackageJsonTypesVersionsPaths,
  getPackageJsonsVisibleToFile: () => getPackageJsonsVisibleToFile,
  getPackageNameFromTypesPackageName: () => getPackageNameFromTypesPackageName,
  getPackageScopeForPath: () => getPackageScopeForPath,
  getParameterSymbolFromJSDoc: () => getParameterSymbolFromJSDoc,
  getParameterTypeNode: () => getParameterTypeNode,
  getParentNodeInSpan: () => getParentNodeInSpan,
  getParseTreeNode: () => getParseTreeNode,
  getParsedCommandLineOfConfigFile: () => getParsedCommandLineOfConfigFile,
  getPathComponents: () => getPathComponents,
  getPathComponentsRelativeTo: () => getPathComponentsRelativeTo,
  getPathFromPathComponents: () => getPathFromPathComponents,
  getPathUpdater: () => getPathUpdater,
  getPathsBasePath: () => getPathsBasePath,
  getPatternFromSpec: () => getPatternFromSpec,
  getPendingEmitKind: () => getPendingEmitKind,
  getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter,
  getPossibleGenericSignatures: () => getPossibleGenericSignatures,
  getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension,
  getPossibleTypeArgumentsInfo: () => getPossibleTypeArgumentsInfo,
  getPreEmitDiagnostics: () => getPreEmitDiagnostics,
  getPrecedingNonSpaceCharacterPosition: () => getPrecedingNonSpaceCharacterPosition,
  getPrivateIdentifier: () => getPrivateIdentifier,
  getProperties: () => getProperties,
  getProperty: () => getProperty,
  getPropertyArrayElementValue: () => getPropertyArrayElementValue,
  getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression,
  getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode,
  getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol,
  getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement,
  getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement,
  getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType,
  getQuoteFromPreference: () => getQuoteFromPreference,
  getQuotePreference: () => getQuotePreference,
  getRangesWhere: () => getRangesWhere,
  getRefactorContextSpan: () => getRefactorContextSpan,
  getReferencedFileLocation: () => getReferencedFileLocation,
  getRegexFromPattern: () => getRegexFromPattern,
  getRegularExpressionForWildcard: () => getRegularExpressionForWildcard,
  getRegularExpressionsForWildcards: () => getRegularExpressionsForWildcards,
  getRelativePathFromDirectory: () => getRelativePathFromDirectory,
  getRelativePathFromFile: () => getRelativePathFromFile,
  getRelativePathToDirectoryOrUrl: () => getRelativePathToDirectoryOrUrl,
  getRenameLocation: () => getRenameLocation,
  getReplacementSpanForContextToken: () => getReplacementSpanForContextToken,
  getResolutionDiagnostic: () => getResolutionDiagnostic,
  getResolutionModeOverrideForClause: () => getResolutionModeOverrideForClause,
  getResolveJsonModule: () => getResolveJsonModule,
  getResolvePackageJsonExports: () => getResolvePackageJsonExports,
  getResolvePackageJsonImports: () => getResolvePackageJsonImports,
  getResolvedExternalModuleName: () => getResolvedExternalModuleName,
  getResolvedModule: () => getResolvedModule,
  getResolvedTypeReferenceDirective: () => getResolvedTypeReferenceDirective,
  getRestIndicatorOfBindingOrAssignmentElement: () => getRestIndicatorOfBindingOrAssignmentElement,
  getRestParameterElementType: () => getRestParameterElementType,
  getRightMostAssignedExpression: () => getRightMostAssignedExpression,
  getRootDeclaration: () => getRootDeclaration,
  getRootDirectoryOfResolutionCache: () => getRootDirectoryOfResolutionCache,
  getRootLength: () => getRootLength,
  getRootPathSplitLength: () => getRootPathSplitLength,
  getScriptKind: () => getScriptKind,
  getScriptKindFromFileName: () => getScriptKindFromFileName,
  getScriptTargetFeatures: () => getScriptTargetFeatures,
  getSelectedEffectiveModifierFlags: () => getSelectedEffectiveModifierFlags,
  getSelectedSyntacticModifierFlags: () => getSelectedSyntacticModifierFlags,
  getSemanticClassifications: () => getSemanticClassifications,
  getSemanticJsxChildren: () => getSemanticJsxChildren,
  getSetAccessorTypeAnnotationNode: () => getSetAccessorTypeAnnotationNode,
  getSetAccessorValueParameter: () => getSetAccessorValueParameter,
  getSetExternalModuleIndicator: () => getSetExternalModuleIndicator,
  getShebang: () => getShebang,
  getSingleInitializerOfVariableStatementOrPropertyDeclaration: () => getSingleInitializerOfVariableStatementOrPropertyDeclaration,
  getSingleVariableOfVariableStatement: () => getSingleVariableOfVariableStatement,
  getSnapshotText: () => getSnapshotText,
  getSnippetElement: () => getSnippetElement,
  getSourceFileOfModule: () => getSourceFileOfModule,
  getSourceFileOfNode: () => getSourceFileOfNode,
  getSourceFilePathInNewDir: () => getSourceFilePathInNewDir,
  getSourceFilePathInNewDirWorker: () => getSourceFilePathInNewDirWorker,
  getSourceFileVersionAsHashFromText: () => getSourceFileVersionAsHashFromText,
  getSourceFilesToEmit: () => getSourceFilesToEmit,
  getSourceMapRange: () => getSourceMapRange,
  getSourceMapper: () => getSourceMapper,
  getSourceTextOfNodeFromSourceFile: () => getSourceTextOfNodeFromSourceFile,
  getSpanOfTokenAtPosition: () => getSpanOfTokenAtPosition,
  getSpellingSuggestion: () => getSpellingSuggestion,
  getStartPositionOfLine: () => getStartPositionOfLine,
  getStartPositionOfRange: () => getStartPositionOfRange,
  getStartsOnNewLine: () => getStartsOnNewLine,
  getStaticPropertiesAndClassStaticBlock: () => getStaticPropertiesAndClassStaticBlock,
  getStrictOptionValue: () => getStrictOptionValue,
  getStringComparer: () => getStringComparer,
  getSuperCallFromStatement: () => getSuperCallFromStatement,
  getSuperContainer: () => getSuperContainer,
  getSupportedCodeFixes: () => getSupportedCodeFixes,
  getSupportedExtensions: () => getSupportedExtensions,
  getSupportedExtensionsWithJsonIfResolveJsonModule: () => getSupportedExtensionsWithJsonIfResolveJsonModule,
  getSwitchedType: () => getSwitchedType,
  getSymbolId: () => getSymbolId,
  getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier,
  getSymbolTarget: () => getSymbolTarget,
  getSyntacticClassifications: () => getSyntacticClassifications,
  getSyntacticModifierFlags: () => getSyntacticModifierFlags,
  getSyntacticModifierFlagsNoCache: () => getSyntacticModifierFlagsNoCache,
  getSynthesizedDeepClone: () => getSynthesizedDeepClone,
  getSynthesizedDeepCloneWithReplacements: () => getSynthesizedDeepCloneWithReplacements,
  getSynthesizedDeepClones: () => getSynthesizedDeepClones,
  getSynthesizedDeepClonesWithReplacements: () => getSynthesizedDeepClonesWithReplacements,
  getSyntheticLeadingComments: () => getSyntheticLeadingComments,
  getSyntheticTrailingComments: () => getSyntheticTrailingComments,
  getTargetLabel: () => getTargetLabel,
  getTargetOfBindingOrAssignmentElement: () => getTargetOfBindingOrAssignmentElement,
  getTemporaryModuleResolutionState: () => getTemporaryModuleResolutionState,
  getTextOfConstantValue: () => getTextOfConstantValue,
  getTextOfIdentifierOrLiteral: () => getTextOfIdentifierOrLiteral,
  getTextOfJSDocComment: () => getTextOfJSDocComment,
  getTextOfJsxAttributeName: () => getTextOfJsxAttributeName,
  getTextOfJsxNamespacedName: () => getTextOfJsxNamespacedName,
  getTextOfNode: () => getTextOfNode,
  getTextOfNodeFromSourceText: () => getTextOfNodeFromSourceText,
  getTextOfPropertyName: () => getTextOfPropertyName,
  getThisContainer: () => getThisContainer,
  getThisParameter: () => getThisParameter,
  getTokenAtPosition: () => getTokenAtPosition,
  getTokenPosOfNode: () => getTokenPosOfNode,
  getTokenSourceMapRange: () => getTokenSourceMapRange,
  getTouchingPropertyName: () => getTouchingPropertyName,
  getTouchingToken: () => getTouchingToken,
  getTrailingCommentRanges: () => getTrailingCommentRanges,
  getTrailingSemicolonDeferringWriter: () => getTrailingSemicolonDeferringWriter,
  getTransformFlagsSubtreeExclusions: () => getTransformFlagsSubtreeExclusions,
  getTransformers: () => getTransformers,
  getTsBuildInfoEmitOutputFilePath: () => getTsBuildInfoEmitOutputFilePath,
  getTsConfigObjectLiteralExpression: () => getTsConfigObjectLiteralExpression,
  getTsConfigPropArrayElementValue: () => getTsConfigPropArrayElementValue,
  getTypeAnnotationNode: () => getTypeAnnotationNode,
  getTypeArgumentOrTypeParameterList: () => getTypeArgumentOrTypeParameterList,
  getTypeKeywordOfTypeOnlyImport: () => getTypeKeywordOfTypeOnlyImport,
  getTypeNode: () => getTypeNode,
  getTypeNodeIfAccessible: () => getTypeNodeIfAccessible,
  getTypeParameterFromJsDoc: () => getTypeParameterFromJsDoc,
  getTypeParameterOwner: () => getTypeParameterOwner,
  getTypesPackageName: () => getTypesPackageName,
  getUILocale: () => getUILocale,
  getUniqueName: () => getUniqueName,
  getUniqueSymbolId: () => getUniqueSymbolId,
  getUseDefineForClassFields: () => getUseDefineForClassFields,
  getWatchErrorSummaryDiagnosticMessage: () => getWatchErrorSummaryDiagnosticMessage,
  getWatchFactory: () => getWatchFactory,
  group: () => group,
  groupBy: () => groupBy,
  guessIndentation: () => guessIndentation,
  handleNoEmitOptions: () => handleNoEmitOptions,
  hasAbstractModifier: () => hasAbstractModifier,
  hasAccessorModifier: () => hasAccessorModifier,
  hasAmbientModifier: () => hasAmbientModifier,
  hasChangesInResolutions: () => hasChangesInResolutions,
  hasChildOfKind: () => hasChildOfKind,
  hasContextSensitiveParameters: () => hasContextSensitiveParameters,
  hasDecorators: () => hasDecorators,
  hasDocComment: () => hasDocComment,
  hasDynamicName: () => hasDynamicName,
  hasEffectiveModifier: () => hasEffectiveModifier,
  hasEffectiveModifiers: () => hasEffectiveModifiers,
  hasEffectiveReadonlyModifier: () => hasEffectiveReadonlyModifier,
  hasExtension: () => hasExtension,
  hasIndexSignature: () => hasIndexSignature,
  hasInitializer: () => hasInitializer,
  hasInvalidEscape: () => hasInvalidEscape,
  hasJSDocNodes: () => hasJSDocNodes,
  hasJSDocParameterTags: () => hasJSDocParameterTags,
  hasJSFileExtension: () => hasJSFileExtension,
  hasJsonModuleEmitEnabled: () => hasJsonModuleEmitEnabled,
  hasOnlyExpressionInitializer: () => hasOnlyExpressionInitializer,
  hasOverrideModifier: () => hasOverrideModifier,
  hasPossibleExternalModuleReference: () => hasPossibleExternalModuleReference,
  hasProperty: () => hasProperty,
  hasPropertyAccessExpressionWithName: () => hasPropertyAccessExpressionWithName,
  hasQuestionToken: () => hasQuestionToken,
  hasRecordedExternalHelpers: () => hasRecordedExternalHelpers,
  hasRestParameter: () => hasRestParameter,
  hasScopeMarker: () => hasScopeMarker,
  hasStaticModifier: () => hasStaticModifier,
  hasSyntacticModifier: () => hasSyntacticModifier,
  hasSyntacticModifiers: () => hasSyntacticModifiers,
  hasTSFileExtension: () => hasTSFileExtension,
  hasTabstop: () => hasTabstop,
  hasTrailingDirectorySeparator: () => hasTrailingDirectorySeparator,
  hasType: () => hasType,
  hasTypeArguments: () => hasTypeArguments,
  hasZeroOrOneAsteriskCharacter: () => hasZeroOrOneAsteriskCharacter,
  helperString: () => helperString,
  hostGetCanonicalFileName: () => hostGetCanonicalFileName,
  hostUsesCaseSensitiveFileNames: () => hostUsesCaseSensitiveFileNames,
  idText: () => idText,
  identifierIsThisKeyword: () => identifierIsThisKeyword,
  identifierToKeywordKind: () => identifierToKeywordKind,
  identity: () => identity,
  identitySourceMapConsumer: () => identitySourceMapConsumer,
  ignoreSourceNewlines: () => ignoreSourceNewlines,
  ignoredPaths: () => ignoredPaths,
  importDefaultHelper: () => importDefaultHelper,
  importFromModuleSpecifier: () => importFromModuleSpecifier,
  importNameElisionDisabled: () => importNameElisionDisabled,
  importStarHelper: () => importStarHelper,
  indexOfAnyCharCode: () => indexOfAnyCharCode,
  indexOfNode: () => indexOfNode,
  indicesOf: () => indicesOf,
  inferredTypesContainingFile: () => inferredTypesContainingFile,
  insertImports: () => insertImports,
  insertLeadingStatement: () => insertLeadingStatement,
  insertSorted: () => insertSorted,
  insertStatementAfterCustomPrologue: () => insertStatementAfterCustomPrologue,
  insertStatementAfterStandardPrologue: () => insertStatementAfterStandardPrologue,
  insertStatementsAfterCustomPrologue: () => insertStatementsAfterCustomPrologue,
  insertStatementsAfterStandardPrologue: () => insertStatementsAfterStandardPrologue,
  intersperse: () => intersperse,
  intrinsicTagNameToString: () => intrinsicTagNameToString,
  introducesArgumentsExoticObject: () => introducesArgumentsExoticObject,
  inverseJsxOptionMap: () => inverseJsxOptionMap,
  isAbstractConstructorSymbol: () => isAbstractConstructorSymbol,
  isAbstractModifier: () => isAbstractModifier,
  isAccessExpression: () => isAccessExpression,
  isAccessibilityModifier: () => isAccessibilityModifier,
  isAccessor: () => isAccessor,
  isAccessorModifier: () => isAccessorModifier,
  isAliasSymbolDeclaration: () => isAliasSymbolDeclaration,
  isAliasableExpression: () => isAliasableExpression,
  isAmbientModule: () => isAmbientModule,
  isAmbientPropertyDeclaration: () => isAmbientPropertyDeclaration,
  isAnonymousFunctionDefinition: () => isAnonymousFunctionDefinition,
  isAnyDirectorySeparator: () => isAnyDirectorySeparator,
  isAnyImportOrBareOrAccessedRequire: () => isAnyImportOrBareOrAccessedRequire,
  isAnyImportOrReExport: () => isAnyImportOrReExport,
  isAnyImportSyntax: () => isAnyImportSyntax,
  isAnySupportedFileExtension: () => isAnySupportedFileExtension,
  isApplicableVersionedTypesKey: () => isApplicableVersionedTypesKey,
  isArgumentExpressionOfElementAccess: () => isArgumentExpressionOfElementAccess,
  isArray: () => isArray,
  isArrayBindingElement: () => isArrayBindingElement,
  isArrayBindingOrAssignmentElement: () => isArrayBindingOrAssignmentElement,
  isArrayBindingOrAssignmentPattern: () => isArrayBindingOrAssignmentPattern,
  isArrayBindingPattern: () => isArrayBindingPattern,
  isArrayLiteralExpression: () => isArrayLiteralExpression,
  isArrayLiteralOrObjectLiteralDestructuringPattern: () => isArrayLiteralOrObjectLiteralDestructuringPattern,
  isArrayTypeNode: () => isArrayTypeNode,
  isArrowFunction: () => isArrowFunction,
  isAsExpression: () => isAsExpression,
  isAssertClause: () => isAssertClause,
  isAssertEntry: () => isAssertEntry,
  isAssertionExpression: () => isAssertionExpression,
  isAssertionKey: () => isAssertionKey,
  isAssertsKeyword: () => isAssertsKeyword,
  isAssignmentDeclaration: () => isAssignmentDeclaration,
  isAssignmentExpression: () => isAssignmentExpression,
  isAssignmentOperator: () => isAssignmentOperator,
  isAssignmentPattern: () => isAssignmentPattern,
  isAssignmentTarget: () => isAssignmentTarget,
  isAsteriskToken: () => isAsteriskToken,
  isAsyncFunction: () => isAsyncFunction,
  isAsyncModifier: () => isAsyncModifier,
  isAutoAccessorPropertyDeclaration: () => isAutoAccessorPropertyDeclaration,
  isAwaitExpression: () => isAwaitExpression,
  isAwaitKeyword: () => isAwaitKeyword,
  isBigIntLiteral: () => isBigIntLiteral,
  isBinaryExpression: () => isBinaryExpression,
  isBinaryOperatorToken: () => isBinaryOperatorToken,
  isBindableObjectDefinePropertyCall: () => isBindableObjectDefinePropertyCall,
  isBindableStaticAccessExpression: () => isBindableStaticAccessExpression,
  isBindableStaticElementAccessExpression: () => isBindableStaticElementAccessExpression,
  isBindableStaticNameExpression: () => isBindableStaticNameExpression,
  isBindingElement: () => isBindingElement,
  isBindingElementOfBareOrAccessedRequire: () => isBindingElementOfBareOrAccessedRequire,
  isBindingName: () => isBindingName,
  isBindingOrAssignmentElement: () => isBindingOrAssignmentElement,
  isBindingOrAssignmentPattern: () => isBindingOrAssignmentPattern,
  isBindingPattern: () => isBindingPattern,
  isBlock: () => isBlock,
  isBlockOrCatchScoped: () => isBlockOrCatchScoped,
  isBlockScope: () => isBlockScope,
  isBlockScopedContainerTopLevel: () => isBlockScopedContainerTopLevel,
  isBooleanLiteral: () => isBooleanLiteral,
  isBreakOrContinueStatement: () => isBreakOrContinueStatement,
  isBreakStatement: () => isBreakStatement,
  isBuildInfoFile: () => isBuildInfoFile,
  isBuilderProgram: () => isBuilderProgram2,
  isBundle: () => isBundle,
  isBundleFileTextLike: () => isBundleFileTextLike,
  isCallChain: () => isCallChain,
  isCallExpression: () => isCallExpression,
  isCallExpressionTarget: () => isCallExpressionTarget,
  isCallLikeExpression: () => isCallLikeExpression,
  isCallOrNewExpression: () => isCallOrNewExpression,
  isCallOrNewExpressionTarget: () => isCallOrNewExpressionTarget,
  isCallSignatureDeclaration: () => isCallSignatureDeclaration,
  isCallToHelper: () => isCallToHelper,
  isCaseBlock: () => isCaseBlock,
  isCaseClause: () => isCaseClause,
  isCaseKeyword: () => isCaseKeyword,
  isCaseOrDefaultClause: () => isCaseOrDefaultClause,
  isCatchClause: () => isCatchClause,
  isCatchClauseVariableDeclaration: () => isCatchClauseVariableDeclaration,
  isCatchClauseVariableDeclarationOrBindingElement: () => isCatchClauseVariableDeclarationOrBindingElement,
  isCheckJsEnabledForFile: () => isCheckJsEnabledForFile,
  isChildOfNodeWithKind: () => isChildOfNodeWithKind,
  isCircularBuildOrder: () => isCircularBuildOrder,
  isClassDeclaration: () => isClassDeclaration,
  isClassElement: () => isClassElement,
  isClassExpression: () => isClassExpression,
  isClassLike: () => isClassLike,
  isClassMemberModifier: () => isClassMemberModifier,
  isClassOrTypeElement: () => isClassOrTypeElement,
  isClassStaticBlockDeclaration: () => isClassStaticBlockDeclaration,
  isCollapsedRange: () => isCollapsedRange,
  isColonToken: () => isColonToken,
  isCommaExpression: () => isCommaExpression,
  isCommaListExpression: () => isCommaListExpression,
  isCommaSequence: () => isCommaSequence,
  isCommaToken: () => isCommaToken,
  isComment: () => isComment,
  isCommonJsExportPropertyAssignment: () => isCommonJsExportPropertyAssignment,
  isCommonJsExportedExpression: () => isCommonJsExportedExpression,
  isCompoundAssignment: () => isCompoundAssignment,
  isComputedNonLiteralName: () => isComputedNonLiteralName,
  isComputedPropertyName: () => isComputedPropertyName,
  isConciseBody: () => isConciseBody,
  isConditionalExpression: () => isConditionalExpression,
  isConditionalTypeNode: () => isConditionalTypeNode,
  isConstTypeReference: () => isConstTypeReference,
  isConstructSignatureDeclaration: () => isConstructSignatureDeclaration,
  isConstructorDeclaration: () => isConstructorDeclaration,
  isConstructorTypeNode: () => isConstructorTypeNode,
  isContextualKeyword: () => isContextualKeyword,
  isContinueStatement: () => isContinueStatement,
  isCustomPrologue: () => isCustomPrologue,
  isDebuggerStatement: () => isDebuggerStatement,
  isDeclaration: () => isDeclaration,
  isDeclarationBindingElement: () => isDeclarationBindingElement,
  isDeclarationFileName: () => isDeclarationFileName,
  isDeclarationName: () => isDeclarationName,
  isDeclarationNameOfEnumOrNamespace: () => isDeclarationNameOfEnumOrNamespace,
  isDeclarationReadonly: () => isDeclarationReadonly,
  isDeclarationStatement: () => isDeclarationStatement,
  isDeclarationWithTypeParameterChildren: () => isDeclarationWithTypeParameterChildren,
  isDeclarationWithTypeParameters: () => isDeclarationWithTypeParameters,
  isDecorator: () => isDecorator,
  isDecoratorTarget: () => isDecoratorTarget,
  isDefaultClause: () => isDefaultClause,
  isDefaultImport: () => isDefaultImport,
  isDefaultModifier: () => isDefaultModifier,
  isDefaultedExpandoInitializer: () => isDefaultedExpandoInitializer,
  isDeleteExpression: () => isDeleteExpression,
  isDeleteTarget: () => isDeleteTarget,
  isDeprecatedDeclaration: () => isDeprecatedDeclaration,
  isDestructuringAssignment: () => isDestructuringAssignment,
  isDiagnosticWithLocation: () => isDiagnosticWithLocation,
  isDiskPathRoot: () => isDiskPathRoot,
  isDoStatement: () => isDoStatement,
  isDotDotDotToken: () => isDotDotDotToken,
  isDottedName: () => isDottedName,
  isDynamicName: () => isDynamicName,
  isESSymbolIdentifier: () => isESSymbolIdentifier,
  isEffectiveExternalModule: () => isEffectiveExternalModule,
  isEffectiveModuleDeclaration: () => isEffectiveModuleDeclaration,
  isEffectiveStrictModeSourceFile: () => isEffectiveStrictModeSourceFile,
  isElementAccessChain: () => isElementAccessChain,
  isElementAccessExpression: () => isElementAccessExpression,
  isEmittedFileOfProgram: () => isEmittedFileOfProgram,
  isEmptyArrayLiteral: () => isEmptyArrayLiteral,
  isEmptyBindingElement: () => isEmptyBindingElement,
  isEmptyBindingPattern: () => isEmptyBindingPattern,
  isEmptyObjectLiteral: () => isEmptyObjectLiteral,
  isEmptyStatement: () => isEmptyStatement,
  isEmptyStringLiteral: () => isEmptyStringLiteral,
  isEntityName: () => isEntityName,
  isEntityNameExpression: () => isEntityNameExpression,
  isEnumConst: () => isEnumConst,
  isEnumDeclaration: () => isEnumDeclaration,
  isEnumMember: () => isEnumMember,
  isEqualityOperatorKind: () => isEqualityOperatorKind,
  isEqualsGreaterThanToken: () => isEqualsGreaterThanToken,
  isExclamationToken: () => isExclamationToken,
  isExcludedFile: () => isExcludedFile,
  isExclusivelyTypeOnlyImportOrExport: () => isExclusivelyTypeOnlyImportOrExport,
  isExportAssignment: () => isExportAssignment,
  isExportDeclaration: () => isExportDeclaration,
  isExportModifier: () => isExportModifier,
  isExportName: () => isExportName,
  isExportNamespaceAsDefaultDeclaration: () => isExportNamespaceAsDefaultDeclaration,
  isExportOrDefaultModifier: () => isExportOrDefaultModifier,
  isExportSpecifier: () => isExportSpecifier,
  isExportsIdentifier: () => isExportsIdentifier,
  isExportsOrModuleExportsOrAlias: () => isExportsOrModuleExportsOrAlias,
  isExpression: () => isExpression,
  isExpressionNode: () => isExpressionNode,
  isExpressionOfExternalModuleImportEqualsDeclaration: () => isExpressionOfExternalModuleImportEqualsDeclaration,
  isExpressionOfOptionalChainRoot: () => isExpressionOfOptionalChainRoot,
  isExpressionStatement: () => isExpressionStatement,
  isExpressionWithTypeArguments: () => isExpressionWithTypeArguments,
  isExpressionWithTypeArgumentsInClassExtendsClause: () => isExpressionWithTypeArgumentsInClassExtendsClause,
  isExternalModule: () => isExternalModule,
  isExternalModuleAugmentation: () => isExternalModuleAugmentation,
  isExternalModuleImportEqualsDeclaration: () => isExternalModuleImportEqualsDeclaration,
  isExternalModuleIndicator: () => isExternalModuleIndicator,
  isExternalModuleNameRelative: () => isExternalModuleNameRelative,
  isExternalModuleReference: () => isExternalModuleReference,
  isExternalModuleSymbol: () => isExternalModuleSymbol,
  isExternalOrCommonJsModule: () => isExternalOrCommonJsModule,
  isFileLevelUniqueName: () => isFileLevelUniqueName,
  isFileProbablyExternalModule: () => isFileProbablyExternalModule,
  isFirstDeclarationOfSymbolParameter: () => isFirstDeclarationOfSymbolParameter,
  isFixablePromiseHandler: () => isFixablePromiseHandler,
  isForInOrOfStatement: () => isForInOrOfStatement,
  isForInStatement: () => isForInStatement,
  isForInitializer: () => isForInitializer,
  isForOfStatement: () => isForOfStatement,
  isForStatement: () => isForStatement,
  isFunctionBlock: () => isFunctionBlock,
  isFunctionBody: () => isFunctionBody,
  isFunctionDeclaration: () => isFunctionDeclaration,
  isFunctionExpression: () => isFunctionExpression,
  isFunctionExpressionOrArrowFunction: () => isFunctionExpressionOrArrowFunction,
  isFunctionLike: () => isFunctionLike,
  isFunctionLikeDeclaration: () => isFunctionLikeDeclaration,
  isFunctionLikeKind: () => isFunctionLikeKind,
  isFunctionLikeOrClassStaticBlockDeclaration: () => isFunctionLikeOrClassStaticBlockDeclaration,
  isFunctionOrConstructorTypeNode: () => isFunctionOrConstructorTypeNode,
  isFunctionOrModuleBlock: () => isFunctionOrModuleBlock,
  isFunctionSymbol: () => isFunctionSymbol,
  isFunctionTypeNode: () => isFunctionTypeNode,
  isFutureReservedKeyword: () => isFutureReservedKeyword,
  isGeneratedIdentifier: () => isGeneratedIdentifier,
  isGeneratedPrivateIdentifier: () => isGeneratedPrivateIdentifier,
  isGetAccessor: () => isGetAccessor,
  isGetAccessorDeclaration: () => isGetAccessorDeclaration,
  isGetOrSetAccessorDeclaration: () => isGetOrSetAccessorDeclaration,
  isGlobalDeclaration: () => isGlobalDeclaration,
  isGlobalScopeAugmentation: () => isGlobalScopeAugmentation,
  isGrammarError: () => isGrammarError,
  isHeritageClause: () => isHeritageClause,
  isHoistedFunction: () => isHoistedFunction,
  isHoistedVariableStatement: () => isHoistedVariableStatement,
  isIdentifier: () => isIdentifier,
  isIdentifierANonContextualKeyword: () => isIdentifierANonContextualKeyword,
  isIdentifierName: () => isIdentifierName,
  isIdentifierOrThisTypeNode: () => isIdentifierOrThisTypeNode,
  isIdentifierPart: () => isIdentifierPart,
  isIdentifierStart: () => isIdentifierStart,
  isIdentifierText: () => isIdentifierText,
  isIdentifierTypePredicate: () => isIdentifierTypePredicate,
  isIdentifierTypeReference: () => isIdentifierTypeReference,
  isIfStatement: () => isIfStatement,
  isIgnoredFileFromWildCardWatching: () => isIgnoredFileFromWildCardWatching,
  isImplicitGlob: () => isImplicitGlob,
  isImportCall: () => isImportCall,
  isImportClause: () => isImportClause,
  isImportDeclaration: () => isImportDeclaration,
  isImportEqualsDeclaration: () => isImportEqualsDeclaration,
  isImportKeyword: () => isImportKeyword,
  isImportMeta: () => isImportMeta,
  isImportOrExportSpecifier: () => isImportOrExportSpecifier,
  isImportOrExportSpecifierName: () => isImportOrExportSpecifierName,
  isImportSpecifier: () => isImportSpecifier,
  isImportTypeAssertionContainer: () => isImportTypeAssertionContainer,
  isImportTypeNode: () => isImportTypeNode,
  isImportableFile: () => isImportableFile,
  isInComment: () => isInComment,
  isInExpressionContext: () => isInExpressionContext,
  isInJSDoc: () => isInJSDoc,
  isInJSFile: () => isInJSFile,
  isInJSXText: () => isInJSXText,
  isInJsonFile: () => isInJsonFile,
  isInNonReferenceComment: () => isInNonReferenceComment,
  isInReferenceComment: () => isInReferenceComment,
  isInRightSideOfInternalImportEqualsDeclaration: () => isInRightSideOfInternalImportEqualsDeclaration,
  isInString: () => isInString,
  isInTemplateString: () => isInTemplateString,
  isInTopLevelContext: () => isInTopLevelContext,
  isIncrementalCompilation: () => isIncrementalCompilation,
  isIndexSignatureDeclaration: () => isIndexSignatureDeclaration,
  isIndexedAccessTypeNode: () => isIndexedAccessTypeNode,
  isInferTypeNode: () => isInferTypeNode,
  isInfinityOrNaNString: () => isInfinityOrNaNString,
  isInitializedProperty: () => isInitializedProperty,
  isInitializedVariable: () => isInitializedVariable,
  isInsideJsxElement: () => isInsideJsxElement,
  isInsideJsxElementOrAttribute: () => isInsideJsxElementOrAttribute,
  isInsideNodeModules: () => isInsideNodeModules,
  isInsideTemplateLiteral: () => isInsideTemplateLiteral,
  isInstantiatedModule: () => isInstantiatedModule,
  isInterfaceDeclaration: () => isInterfaceDeclaration,
  isInternalDeclaration: () => isInternalDeclaration,
  isInternalModuleImportEqualsDeclaration: () => isInternalModuleImportEqualsDeclaration,
  isInternalName: () => isInternalName,
  isIntersectionTypeNode: () => isIntersectionTypeNode,
  isIntrinsicJsxName: () => isIntrinsicJsxName,
  isIterationStatement: () => isIterationStatement,
  isJSDoc: () => isJSDoc,
  isJSDocAllType: () => isJSDocAllType,
  isJSDocAugmentsTag: () => isJSDocAugmentsTag,
  isJSDocAuthorTag: () => isJSDocAuthorTag,
  isJSDocCallbackTag: () => isJSDocCallbackTag,
  isJSDocClassTag: () => isJSDocClassTag,
  isJSDocCommentContainingNode: () => isJSDocCommentContainingNode,
  isJSDocConstructSignature: () => isJSDocConstructSignature,
  isJSDocDeprecatedTag: () => isJSDocDeprecatedTag,
  isJSDocEnumTag: () => isJSDocEnumTag,
  isJSDocFunctionType: () => isJSDocFunctionType,
  isJSDocImplementsTag: () => isJSDocImplementsTag,
  isJSDocIndexSignature: () => isJSDocIndexSignature,
  isJSDocLikeText: () => isJSDocLikeText,
  isJSDocLink: () => isJSDocLink,
  isJSDocLinkCode: () => isJSDocLinkCode,
  isJSDocLinkLike: () => isJSDocLinkLike,
  isJSDocLinkPlain: () => isJSDocLinkPlain,
  isJSDocMemberName: () => isJSDocMemberName,
  isJSDocNameReference: () => isJSDocNameReference,
  isJSDocNamepathType: () => isJSDocNamepathType,
  isJSDocNamespaceBody: () => isJSDocNamespaceBody,
  isJSDocNode: () => isJSDocNode,
  isJSDocNonNullableType: () => isJSDocNonNullableType,
  isJSDocNullableType: () => isJSDocNullableType,
  isJSDocOptionalParameter: () => isJSDocOptionalParameter,
  isJSDocOptionalType: () => isJSDocOptionalType,
  isJSDocOverloadTag: () => isJSDocOverloadTag,
  isJSDocOverrideTag: () => isJSDocOverrideTag,
  isJSDocParameterTag: () => isJSDocParameterTag,
  isJSDocPrivateTag: () => isJSDocPrivateTag,
  isJSDocPropertyLikeTag: () => isJSDocPropertyLikeTag,
  isJSDocPropertyTag: () => isJSDocPropertyTag,
  isJSDocProtectedTag: () => isJSDocProtectedTag,
  isJSDocPublicTag: () => isJSDocPublicTag,
  isJSDocReadonlyTag: () => isJSDocReadonlyTag,
  isJSDocReturnTag: () => isJSDocReturnTag,
  isJSDocSatisfiesExpression: () => isJSDocSatisfiesExpression,
  isJSDocSatisfiesTag: () => isJSDocSatisfiesTag,
  isJSDocSeeTag: () => isJSDocSeeTag,
  isJSDocSignature: () => isJSDocSignature,
  isJSDocTag: () => isJSDocTag,
  isJSDocTemplateTag: () => isJSDocTemplateTag,
  isJSDocThisTag: () => isJSDocThisTag,
  isJSDocThrowsTag: () => isJSDocThrowsTag,
  isJSDocTypeAlias: () => isJSDocTypeAlias,
  isJSDocTypeAssertion: () => isJSDocTypeAssertion,
  isJSDocTypeExpression: () => isJSDocTypeExpression,
  isJSDocTypeLiteral: () => isJSDocTypeLiteral,
  isJSDocTypeTag: () => isJSDocTypeTag,
  isJSDocTypedefTag: () => isJSDocTypedefTag,
  isJSDocUnknownTag: () => isJSDocUnknownTag,
  isJSDocUnknownType: () => isJSDocUnknownType,
  isJSDocVariadicType: () => isJSDocVariadicType,
  isJSXTagName: () => isJSXTagName,
  isJsonEqual: () => isJsonEqual,
  isJsonSourceFile: () => isJsonSourceFile,
  isJsxAttribute: () => isJsxAttribute,
  isJsxAttributeLike: () => isJsxAttributeLike,
  isJsxAttributeName: () => isJsxAttributeName,
  isJsxAttributes: () => isJsxAttributes,
  isJsxChild: () => isJsxChild,
  isJsxClosingElement: () => isJsxClosingElement,
  isJsxClosingFragment: () => isJsxClosingFragment,
  isJsxElement: () => isJsxElement,
  isJsxExpression: () => isJsxExpression,
  isJsxFragment: () => isJsxFragment,
  isJsxNamespacedName: () => isJsxNamespacedName,
  isJsxOpeningElement: () => isJsxOpeningElement,
  isJsxOpeningFragment: () => isJsxOpeningFragment,
  isJsxOpeningLikeElement: () => isJsxOpeningLikeElement,
  isJsxOpeningLikeElementTagName: () => isJsxOpeningLikeElementTagName,
  isJsxSelfClosingElement: () => isJsxSelfClosingElement,
  isJsxSpreadAttribute: () => isJsxSpreadAttribute,
  isJsxTagNameExpression: () => isJsxTagNameExpression,
  isJsxText: () => isJsxText,
  isJumpStatementTarget: () => isJumpStatementTarget,
  isKeyword: () => isKeyword,
  isKeywordOrPunctuation: () => isKeywordOrPunctuation,
  isKnownSymbol: () => isKnownSymbol,
  isLabelName: () => isLabelName,
  isLabelOfLabeledStatement: () => isLabelOfLabeledStatement,
  isLabeledStatement: () => isLabeledStatement,
  isLateVisibilityPaintedStatement: () => isLateVisibilityPaintedStatement,
  isLeftHandSideExpression: () => isLeftHandSideExpression,
  isLeftHandSideOfAssignment: () => isLeftHandSideOfAssignment,
  isLet: () => isLet,
  isLineBreak: () => isLineBreak,
  isLiteralComputedPropertyDeclarationName: () => isLiteralComputedPropertyDeclarationName,
  isLiteralExpression: () => isLiteralExpression,
  isLiteralExpressionOfObject: () => isLiteralExpressionOfObject,
  isLiteralImportTypeNode: () => isLiteralImportTypeNode,
  isLiteralKind: () => isLiteralKind,
  isLiteralLikeAccess: () => isLiteralLikeAccess,
  isLiteralLikeElementAccess: () => isLiteralLikeElementAccess,
  isLiteralNameOfPropertyDeclarationOrIndexAccess: () => isLiteralNameOfPropertyDeclarationOrIndexAccess,
  isLiteralTypeLikeExpression: () => isLiteralTypeLikeExpression,
  isLiteralTypeLiteral: () => isLiteralTypeLiteral,
  isLiteralTypeNode: () => isLiteralTypeNode,
  isLocalName: () => isLocalName,
  isLogicalOperator: () => isLogicalOperator,
  isLogicalOrCoalescingAssignmentExpression: () => isLogicalOrCoalescingAssignmentExpression,
  isLogicalOrCoalescingAssignmentOperator: () => isLogicalOrCoalescingAssignmentOperator,
  isLogicalOrCoalescingBinaryExpression: () => isLogicalOrCoalescingBinaryExpression,
  isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator,
  isMappedTypeNode: () => isMappedTypeNode,
  isMemberName: () => isMemberName,
  isMetaProperty: () => isMetaProperty,
  isMethodDeclaration: () => isMethodDeclaration,
  isMethodOrAccessor: () => isMethodOrAccessor,
  isMethodSignature: () => isMethodSignature,
  isMinusToken: () => isMinusToken,
  isMissingDeclaration: () => isMissingDeclaration,
  isModifier: () => isModifier,
  isModifierKind: () => isModifierKind,
  isModifierLike: () => isModifierLike,
  isModuleAugmentationExternal: () => isModuleAugmentationExternal,
  isModuleBlock: () => isModuleBlock,
  isModuleBody: () => isModuleBody,
  isModuleDeclaration: () => isModuleDeclaration,
  isModuleExportsAccessExpression: () => isModuleExportsAccessExpression,
  isModuleIdentifier: () => isModuleIdentifier,
  isModuleName: () => isModuleName,
  isModuleOrEnumDeclaration: () => isModuleOrEnumDeclaration,
  isModuleReference: () => isModuleReference,
  isModuleSpecifierLike: () => isModuleSpecifierLike,
  isModuleWithStringLiteralName: () => isModuleWithStringLiteralName,
  isNameOfFunctionDeclaration: () => isNameOfFunctionDeclaration,
  isNameOfModuleDeclaration: () => isNameOfModuleDeclaration,
  isNamedClassElement: () => isNamedClassElement,
  isNamedDeclaration: () => isNamedDeclaration,
  isNamedEvaluation: () => isNamedEvaluation,
  isNamedEvaluationSource: () => isNamedEvaluationSource,
  isNamedExportBindings: () => isNamedExportBindings,
  isNamedExports: () => isNamedExports,
  isNamedImportBindings: () => isNamedImportBindings,
  isNamedImports: () => isNamedImports,
  isNamedImportsOrExports: () => isNamedImportsOrExports,
  isNamedTupleMember: () => isNamedTupleMember,
  isNamespaceBody: () => isNamespaceBody,
  isNamespaceExport: () => isNamespaceExport,
  isNamespaceExportDeclaration: () => isNamespaceExportDeclaration,
  isNamespaceImport: () => isNamespaceImport,
  isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration,
  isNewExpression: () => isNewExpression,
  isNewExpressionTarget: () => isNewExpressionTarget,
  isNightly: () => isNightly,
  isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral,
  isNode: () => isNode,
  isNodeArray: () => isNodeArray,
  isNodeArrayMultiLine: () => isNodeArrayMultiLine,
  isNodeDescendantOf: () => isNodeDescendantOf,
  isNodeKind: () => isNodeKind,
  isNodeLikeSystem: () => isNodeLikeSystem,
  isNodeModulesDirectory: () => isNodeModulesDirectory,
  isNodeWithPossibleHoistedDeclaration: () => isNodeWithPossibleHoistedDeclaration,
  isNonContextualKeyword: () => isNonContextualKeyword,
  isNonExportDefaultModifier: () => isNonExportDefaultModifier,
  isNonGlobalAmbientModule: () => isNonGlobalAmbientModule,
  isNonGlobalDeclaration: () => isNonGlobalDeclaration,
  isNonNullAccess: () => isNonNullAccess,
  isNonNullChain: () => isNonNullChain,
  isNonNullExpression: () => isNonNullExpression,
  isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName,
  isNotEmittedOrPartiallyEmittedNode: () => isNotEmittedOrPartiallyEmittedNode,
  isNotEmittedStatement: () => isNotEmittedStatement,
  isNullishCoalesce: () => isNullishCoalesce,
  isNumber: () => isNumber,
  isNumericLiteral: () => isNumericLiteral,
  isNumericLiteralName: () => isNumericLiteralName,
  isObjectBindingElementWithoutPropertyName: () => isObjectBindingElementWithoutPropertyName,
  isObjectBindingOrAssignmentElement: () => isObjectBindingOrAssignmentElement,
  isObjectBindingOrAssignmentPattern: () => isObjectBindingOrAssignmentPattern,
  isObjectBindingPattern: () => isObjectBindingPattern,
  isObjectLiteralElement: () => isObjectLiteralElement,
  isObjectLiteralElementLike: () => isObjectLiteralElementLike,
  isObjectLiteralExpression: () => isObjectLiteralExpression,
  isObjectLiteralMethod: () => isObjectLiteralMethod,
  isObjectLiteralOrClassExpressionMethodOrAccessor: () => isObjectLiteralOrClassExpressionMethodOrAccessor,
  isObjectTypeDeclaration: () => isObjectTypeDeclaration,
  isOctalDigit: () => isOctalDigit,
  isOmittedExpression: () => isOmittedExpression,
  isOptionalChain: () => isOptionalChain,
  isOptionalChainRoot: () => isOptionalChainRoot,
  isOptionalDeclaration: () => isOptionalDeclaration,
  isOptionalJSDocPropertyLikeTag: () => isOptionalJSDocPropertyLikeTag,
  isOptionalTypeNode: () => isOptionalTypeNode,
  isOuterExpression: () => isOuterExpression,
  isOutermostOptionalChain: () => isOutermostOptionalChain,
  isOverrideModifier: () => isOverrideModifier,
  isPackedArrayLiteral: () => isPackedArrayLiteral,
  isParameter: () => isParameter,
  isParameterDeclaration: () => isParameterDeclaration,
  isParameterOrCatchClauseVariable: () => isParameterOrCatchClauseVariable,
  isParameterPropertyDeclaration: () => isParameterPropertyDeclaration,
  isParameterPropertyModifier: () => isParameterPropertyModifier,
  isParenthesizedExpression: () => isParenthesizedExpression,
  isParenthesizedTypeNode: () => isParenthesizedTypeNode,
  isParseTreeNode: () => isParseTreeNode,
  isPartOfTypeNode: () => isPartOfTypeNode,
  isPartOfTypeQuery: () => isPartOfTypeQuery,
  isPartiallyEmittedExpression: () => isPartiallyEmittedExpression,
  isPatternMatch: () => isPatternMatch,
  isPinnedComment: () => isPinnedComment,
  isPlainJsFile: () => isPlainJsFile,
  isPlusToken: () => isPlusToken,
  isPossiblyTypeArgumentPosition: () => isPossiblyTypeArgumentPosition,
  isPostfixUnaryExpression: () => isPostfixUnaryExpression,
  isPrefixUnaryExpression: () => isPrefixUnaryExpression,
  isPrivateIdentifier: () => isPrivateIdentifier,
  isPrivateIdentifierClassElementDeclaration: () => isPrivateIdentifierClassElementDeclaration,
  isPrivateIdentifierPropertyAccessExpression: () => isPrivateIdentifierPropertyAccessExpression,
  isPrivateIdentifierSymbol: () => isPrivateIdentifierSymbol,
  isProgramBundleEmitBuildInfo: () => isProgramBundleEmitBuildInfo,
  isProgramUptoDate: () => isProgramUptoDate,
  isPrologueDirective: () => isPrologueDirective,
  isPropertyAccessChain: () => isPropertyAccessChain,
  isPropertyAccessEntityNameExpression: () => isPropertyAccessEntityNameExpression,
  isPropertyAccessExpression: () => isPropertyAccessExpression,
  isPropertyAccessOrQualifiedName: () => isPropertyAccessOrQualifiedName,
  isPropertyAccessOrQualifiedNameOrImportTypeNode: () => isPropertyAccessOrQualifiedNameOrImportTypeNode,
  isPropertyAssignment: () => isPropertyAssignment,
  isPropertyDeclaration: () => isPropertyDeclaration,
  isPropertyName: () => isPropertyName,
  isPropertyNameLiteral: () => isPropertyNameLiteral,
  isPropertySignature: () => isPropertySignature,
  isProtoSetter: () => isProtoSetter,
  isPrototypeAccess: () => isPrototypeAccess,
  isPrototypePropertyAssignment: () => isPrototypePropertyAssignment,
  isPunctuation: () => isPunctuation,
  isPushOrUnshiftIdentifier: () => isPushOrUnshiftIdentifier,
  isQualifiedName: () => isQualifiedName,
  isQuestionDotToken: () => isQuestionDotToken,
  isQuestionOrExclamationToken: () => isQuestionOrExclamationToken,
  isQuestionOrPlusOrMinusToken: () => isQuestionOrPlusOrMinusToken,
  isQuestionToken: () => isQuestionToken,
  isRawSourceMap: () => isRawSourceMap,
  isReadonlyKeyword: () => isReadonlyKeyword,
  isReadonlyKeywordOrPlusOrMinusToken: () => isReadonlyKeywordOrPlusOrMinusToken,
  isRecognizedTripleSlashComment: () => isRecognizedTripleSlashComment,
  isReferenceFileLocation: () => isReferenceFileLocation,
  isReferencedFile: () => isReferencedFile,
  isRegularExpressionLiteral: () => isRegularExpressionLiteral,
  isRequireCall: () => isRequireCall,
  isRequireVariableStatement: () => isRequireVariableStatement,
  isRestParameter: () => isRestParameter,
  isRestTypeNode: () => isRestTypeNode,
  isReturnStatement: () => isReturnStatement,
  isReturnStatementWithFixablePromiseHandler: () => isReturnStatementWithFixablePromiseHandler,
  isRightSideOfAccessExpression: () => isRightSideOfAccessExpression,
  isRightSideOfPropertyAccess: () => isRightSideOfPropertyAccess,
  isRightSideOfQualifiedName: () => isRightSideOfQualifiedName,
  isRightSideOfQualifiedNameOrPropertyAccess: () => isRightSideOfQualifiedNameOrPropertyAccess,
  isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName: () => isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName,
  isRootedDiskPath: () => isRootedDiskPath,
  isSameEntityName: () => isSameEntityName,
  isSatisfiesExpression: () => isSatisfiesExpression,
  isScopeMarker: () => isScopeMarker,
  isSemicolonClassElement: () => isSemicolonClassElement,
  isSetAccessor: () => isSetAccessor,
  isSetAccessorDeclaration: () => isSetAccessorDeclaration,
  isShebangTrivia: () => isShebangTrivia,
  isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol,
  isShorthandPropertyAssignment: () => isShorthandPropertyAssignment,
  isSignedNumericLiteral: () => isSignedNumericLiteral,
  isSimpleCopiableExpression: () => isSimpleCopiableExpression,
  isSimpleInlineableExpression: () => isSimpleInlineableExpression,
  isSingleOrDoubleQuote: () => isSingleOrDoubleQuote,
  isSourceFile: () => isSourceFile,
  isSourceFileFromLibrary: () => isSourceFileFromLibrary,
  isSourceFileJS: () => isSourceFileJS,
  isSourceFileNotJS: () => isSourceFileNotJS,
  isSourceFileNotJson: () => isSourceFileNotJson,
  isSourceMapping: () => isSourceMapping,
  isSpecialPropertyDeclaration: () => isSpecialPropertyDeclaration,
  isSpreadAssignment: () => isSpreadAssignment,
  isSpreadElement: () => isSpreadElement,
  isStatement: () => isStatement,
  isStatementButNotDeclaration: () => isStatementButNotDeclaration,
  isStatementOrBlock: () => isStatementOrBlock,
  isStatementWithLocals: () => isStatementWithLocals,
  isStatic: () => isStatic,
  isStaticModifier: () => isStaticModifier,
  isString: () => isString,
  isStringAKeyword: () => isStringAKeyword,
  isStringANonContextualKeyword: () => isStringANonContextualKeyword,
  isStringAndEmptyAnonymousObjectIntersection: () => isStringAndEmptyAnonymousObjectIntersection,
  isStringDoubleQuoted: () => isStringDoubleQuoted,
  isStringLiteral: () => isStringLiteral,
  isStringLiteralLike: () => isStringLiteralLike,
  isStringLiteralOrJsxExpression: () => isStringLiteralOrJsxExpression,
  isStringLiteralOrTemplate: () => isStringLiteralOrTemplate,
  isStringOrNumericLiteralLike: () => isStringOrNumericLiteralLike,
  isStringOrRegularExpressionOrTemplateLiteral: () => isStringOrRegularExpressionOrTemplateLiteral,
  isStringTextContainingNode: () => isStringTextContainingNode,
  isSuperCall: () => isSuperCall,
  isSuperKeyword: () => isSuperKeyword,
  isSuperOrSuperProperty: () => isSuperOrSuperProperty,
  isSuperProperty: () => isSuperProperty,
  isSupportedSourceFileName: () => isSupportedSourceFileName,
  isSwitchStatement: () => isSwitchStatement,
  isSyntaxList: () => isSyntaxList,
  isSyntheticExpression: () => isSyntheticExpression,
  isSyntheticReference: () => isSyntheticReference,
  isTagName: () => isTagName,
  isTaggedTemplateExpression: () => isTaggedTemplateExpression,
  isTaggedTemplateTag: () => isTaggedTemplateTag,
  isTemplateExpression: () => isTemplateExpression,
  isTemplateHead: () => isTemplateHead,
  isTemplateLiteral: () => isTemplateLiteral,
  isTemplateLiteralKind: () => isTemplateLiteralKind,
  isTemplateLiteralToken: () => isTemplateLiteralToken,
  isTemplateLiteralTypeNode: () => isTemplateLiteralTypeNode,
  isTemplateLiteralTypeSpan: () => isTemplateLiteralTypeSpan,
  isTemplateMiddle: () => isTemplateMiddle,
  isTemplateMiddleOrTemplateTail: () => isTemplateMiddleOrTemplateTail,
  isTemplateSpan: () => isTemplateSpan,
  isTemplateTail: () => isTemplateTail,
  isTextWhiteSpaceLike: () => isTextWhiteSpaceLike,
  isThis: () => isThis,
  isThisContainerOrFunctionBlock: () => isThisContainerOrFunctionBlock,
  isThisIdentifier: () => isThisIdentifier,
  isThisInTypeQuery: () => isThisInTypeQuery,
  isThisInitializedDeclaration: () => isThisInitializedDeclaration,
  isThisInitializedObjectBindingExpression: () => isThisInitializedObjectBindingExpression,
  isThisProperty: () => isThisProperty,
  isThisTypeNode: () => isThisTypeNode,
  isThisTypeParameter: () => isThisTypeParameter,
  isThisTypePredicate: () => isThisTypePredicate,
  isThrowStatement: () => isThrowStatement,
  isToken: () => isToken,
  isTokenKind: () => isTokenKind,
  isTraceEnabled: () => isTraceEnabled,
  isTransientSymbol: () => isTransientSymbol,
  isTrivia: () => isTrivia,
  isTryStatement: () => isTryStatement,
  isTupleTypeNode: () => isTupleTypeNode,
  isTypeAlias: () => isTypeAlias,
  isTypeAliasDeclaration: () => isTypeAliasDeclaration,
  isTypeAssertionExpression: () => isTypeAssertionExpression,
  isTypeDeclaration: () => isTypeDeclaration,
  isTypeElement: () => isTypeElement,
  isTypeKeyword: () => isTypeKeyword,
  isTypeKeywordToken: () => isTypeKeywordToken,
  isTypeKeywordTokenOrIdentifier: () => isTypeKeywordTokenOrIdentifier,
  isTypeLiteralNode: () => isTypeLiteralNode,
  isTypeNode: () => isTypeNode,
  isTypeNodeKind: () => isTypeNodeKind,
  isTypeOfExpression: () => isTypeOfExpression,
  isTypeOnlyExportDeclaration: () => isTypeOnlyExportDeclaration,
  isTypeOnlyImportDeclaration: () => isTypeOnlyImportDeclaration,
  isTypeOnlyImportOrExportDeclaration: () => isTypeOnlyImportOrExportDeclaration,
  isTypeOperatorNode: () => isTypeOperatorNode,
  isTypeParameterDeclaration: () => isTypeParameterDeclaration,
  isTypePredicateNode: () => isTypePredicateNode,
  isTypeQueryNode: () => isTypeQueryNode,
  isTypeReferenceNode: () => isTypeReferenceNode,
  isTypeReferenceType: () => isTypeReferenceType,
  isUMDExportSymbol: () => isUMDExportSymbol,
  isUnaryExpression: () => isUnaryExpression,
  isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite,
  isUnicodeIdentifierStart: () => isUnicodeIdentifierStart,
  isUnionTypeNode: () => isUnionTypeNode,
  isUnparsedNode: () => isUnparsedNode,
  isUnparsedPrepend: () => isUnparsedPrepend,
  isUnparsedSource: () => isUnparsedSource,
  isUnparsedTextLike: () => isUnparsedTextLike,
  isUrl: () => isUrl,
  isValidBigIntString: () => isValidBigIntString,
  isValidESSymbolDeclaration: () => isValidESSymbolDeclaration,
  isValidTypeOnlyAliasUseSite: () => isValidTypeOnlyAliasUseSite,
  isValueSignatureDeclaration: () => isValueSignatureDeclaration,
  isVarConst: () => isVarConst,
  isVariableDeclaration: () => isVariableDeclaration,
  isVariableDeclarationInVariableStatement: () => isVariableDeclarationInVariableStatement,
  isVariableDeclarationInitializedToBareOrAccessedRequire: () => isVariableDeclarationInitializedToBareOrAccessedRequire,
  isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire,
  isVariableDeclarationList: () => isVariableDeclarationList,
  isVariableLike: () => isVariableLike,
  isVariableLikeOrAccessor: () => isVariableLikeOrAccessor,
  isVariableStatement: () => isVariableStatement,
  isVoidExpression: () => isVoidExpression,
  isWatchSet: () => isWatchSet,
  isWhileStatement: () => isWhileStatement,
  isWhiteSpaceLike: () => isWhiteSpaceLike,
  isWhiteSpaceSingleLine: () => isWhiteSpaceSingleLine,
  isWithStatement: () => isWithStatement,
  isWriteAccess: () => isWriteAccess,
  isWriteOnlyAccess: () => isWriteOnlyAccess,
  isYieldExpression: () => isYieldExpression,
  jsxModeNeedsExplicitImport: () => jsxModeNeedsExplicitImport,
  keywordPart: () => keywordPart,
  last: () => last,
  lastOrUndefined: () => lastOrUndefined,
  length: () => length,
  libMap: () => libMap,
  libs: () => libs,
  lineBreakPart: () => lineBreakPart,
  linkNamePart: () => linkNamePart,
  linkPart: () => linkPart,
  linkTextPart: () => linkTextPart,
  listFiles: () => listFiles,
  loadModuleFromGlobalCache: () => loadModuleFromGlobalCache,
  loadWithModeAwareCache: () => loadWithModeAwareCache,
  makeIdentifierFromModuleName: () => makeIdentifierFromModuleName,
  makeImport: () => makeImport,
  makeImportIfNecessary: () => makeImportIfNecessary,
  makeStringLiteral: () => makeStringLiteral,
  mangleScopedPackageName: () => mangleScopedPackageName,
  map: () => map,
  mapAllOrFail: () => mapAllOrFail,
  mapDefined: () => mapDefined,
  mapDefinedEntries: () => mapDefinedEntries,
  mapDefinedIterator: () => mapDefinedIterator,
  mapEntries: () => mapEntries,
  mapIterator: () => mapIterator,
  mapOneOrMany: () => mapOneOrMany,
  mapToDisplayParts: () => mapToDisplayParts,
  matchFiles: () => matchFiles,
  matchPatternOrExact: () => matchPatternOrExact,
  matchedText: () => matchedText,
  matchesExclude: () => matchesExclude,
  maybeBind: () => maybeBind,
  maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages,
  memoize: () => memoize,
  memoizeCached: () => memoizeCached,
  memoizeOne: () => memoizeOne,
  memoizeWeak: () => memoizeWeak,
  metadataHelper: () => metadataHelper,
  min: () => min,
  minAndMax: () => minAndMax,
  missingFileModifiedTime: () => missingFileModifiedTime,
  modifierToFlag: () => modifierToFlag,
  modifiersToFlags: () => modifiersToFlags,
  moduleOptionDeclaration: () => moduleOptionDeclaration,
  moduleResolutionIsEqualTo: () => moduleResolutionIsEqualTo,
  moduleResolutionNameAndModeGetter: () => moduleResolutionNameAndModeGetter,
  moduleResolutionOptionDeclarations: () => moduleResolutionOptionDeclarations,
  moduleResolutionSupportsPackageJsonExportsAndImports: () => moduleResolutionSupportsPackageJsonExportsAndImports,
  moduleResolutionUsesNodeModules: () => moduleResolutionUsesNodeModules,
  moduleSpecifiers: () => ts_moduleSpecifiers_exports,
  moveEmitHelpers: () => moveEmitHelpers,
  moveRangeEnd: () => moveRangeEnd,
  moveRangePastDecorators: () => moveRangePastDecorators,
  moveRangePastModifiers: () => moveRangePastModifiers,
  moveRangePos: () => moveRangePos,
  moveSyntheticComments: () => moveSyntheticComments,
  mutateMap: () => mutateMap,
  mutateMapSkippingNewValues: () => mutateMapSkippingNewValues,
  needsParentheses: () => needsParentheses,
  needsScopeMarker: () => needsScopeMarker,
  newCaseClauseTracker: () => newCaseClauseTracker,
  newPrivateEnvironment: () => newPrivateEnvironment,
  noEmitNotification: () => noEmitNotification,
  noEmitSubstitution: () => noEmitSubstitution,
  noTransformers: () => noTransformers,
  noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength,
  nodeCanBeDecorated: () => nodeCanBeDecorated,
  nodeHasName: () => nodeHasName,
  nodeIsDecorated: () => nodeIsDecorated,
  nodeIsMissing: () => nodeIsMissing,
  nodeIsPresent: () => nodeIsPresent,
  nodeIsSynthesized: () => nodeIsSynthesized,
  nodeModuleNameResolver: () => nodeModuleNameResolver,
  nodeModulesPathPart: () => nodeModulesPathPart,
  nodeNextJsonConfigResolver: () => nodeNextJsonConfigResolver,
  nodeOrChildIsDecorated: () => nodeOrChildIsDecorated,
  nodeOverlapsWithStartEnd: () => nodeOverlapsWithStartEnd,
  nodePosToString: () => nodePosToString,
  nodeSeenTracker: () => nodeSeenTracker,
  nodeStartsNewLexicalEnvironment: () => nodeStartsNewLexicalEnvironment,
  nodeToDisplayParts: () => nodeToDisplayParts,
  noop: () => noop,
  noopFileWatcher: () => noopFileWatcher,
  normalizePath: () => normalizePath,
  normalizeSlashes: () => normalizeSlashes,
  not: () => not,
  notImplemented: () => notImplemented,
  notImplementedResolver: () => notImplementedResolver,
  nullNodeConverters: () => nullNodeConverters,
  nullParenthesizerRules: () => nullParenthesizerRules,
  nullTransformationContext: () => nullTransformationContext,
  objectAllocator: () => objectAllocator,
  operatorPart: () => operatorPart,
  optionDeclarations: () => optionDeclarations,
  optionMapToObject: () => optionMapToObject,
  optionsAffectingProgramStructure: () => optionsAffectingProgramStructure,
  optionsForBuild: () => optionsForBuild,
  optionsForWatch: () => optionsForWatch,
  optionsHaveChanges: () => optionsHaveChanges,
  optionsHaveModuleResolutionChanges: () => optionsHaveModuleResolutionChanges,
  or: () => or,
  orderedRemoveItem: () => orderedRemoveItem,
  orderedRemoveItemAt: () => orderedRemoveItemAt,
  outFile: () => outFile,
  packageIdToPackageName: () => packageIdToPackageName,
  packageIdToString: () => packageIdToString,
  padLeft: () => padLeft,
  padRight: () => padRight,
  paramHelper: () => paramHelper,
  parameterIsThisKeyword: () => parameterIsThisKeyword,
  parameterNamePart: () => parameterNamePart,
  parseBaseNodeFactory: () => parseBaseNodeFactory,
  parseBigInt: () => parseBigInt,
  parseBuildCommand: () => parseBuildCommand,
  parseCommandLine: () => parseCommandLine,
  parseCommandLineWorker: () => parseCommandLineWorker,
  parseConfigFileTextToJson: () => parseConfigFileTextToJson,
  parseConfigFileWithSystem: () => parseConfigFileWithSystem,
  parseConfigHostFromCompilerHostLike: () => parseConfigHostFromCompilerHostLike,
  parseCustomTypeOption: () => parseCustomTypeOption,
  parseIsolatedEntityName: () => parseIsolatedEntityName,
  parseIsolatedJSDocComment: () => parseIsolatedJSDocComment,
  parseJSDocTypeExpressionForTests: () => parseJSDocTypeExpressionForTests,
  parseJsonConfigFileContent: () => parseJsonConfigFileContent,
  parseJsonSourceFileConfigFileContent: () => parseJsonSourceFileConfigFileContent,
  parseJsonText: () => parseJsonText,
  parseListTypeOption: () => parseListTypeOption,
  parseNodeFactory: () => parseNodeFactory,
  parseNodeModuleFromPath: () => parseNodeModuleFromPath,
  parsePackageName: () => parsePackageName,
  parsePseudoBigInt: () => parsePseudoBigInt,
  parseValidBigInt: () => parseValidBigInt,
  patchWriteFileEnsuringDirectory: () => patchWriteFileEnsuringDirectory,
  pathContainsNodeModules: () => pathContainsNodeModules,
  pathIsAbsolute: () => pathIsAbsolute,
  pathIsBareSpecifier: () => pathIsBareSpecifier,
  pathIsRelative: () => pathIsRelative,
  patternText: () => patternText,
  perfLogger: () => perfLogger,
  performIncrementalCompilation: () => performIncrementalCompilation,
  performance: () => ts_performance_exports,
  plainJSErrors: () => plainJSErrors,
  positionBelongsToNode: () => positionBelongsToNode,
  positionIsASICandidate: () => positionIsASICandidate,
  positionIsSynthesized: () => positionIsSynthesized,
  positionsAreOnSameLine: () => positionsAreOnSameLine,
  preProcessFile: () => preProcessFile,
  probablyUsesSemicolons: () => probablyUsesSemicolons,
  processCommentPragmas: () => processCommentPragmas,
  processPragmasIntoFields: () => processPragmasIntoFields,
  processTaggedTemplateExpression: () => processTaggedTemplateExpression,
  programContainsEsModules: () => programContainsEsModules,
  programContainsModules: () => programContainsModules,
  projectReferenceIsEqualTo: () => projectReferenceIsEqualTo,
  propKeyHelper: () => propKeyHelper,
  propertyNamePart: () => propertyNamePart,
  pseudoBigIntToString: () => pseudoBigIntToString,
  punctuationPart: () => punctuationPart,
  pushIfUnique: () => pushIfUnique,
  quote: () => quote,
  quotePreferenceFromString: () => quotePreferenceFromString,
  rangeContainsPosition: () => rangeContainsPosition,
  rangeContainsPositionExclusive: () => rangeContainsPositionExclusive,
  rangeContainsRange: () => rangeContainsRange,
  rangeContainsRangeExclusive: () => rangeContainsRangeExclusive,
  rangeContainsStartEnd: () => rangeContainsStartEnd,
  rangeEndIsOnSameLineAsRangeStart: () => rangeEndIsOnSameLineAsRangeStart,
  rangeEndPositionsAreOnSameLine: () => rangeEndPositionsAreOnSameLine,
  rangeEquals: () => rangeEquals,
  rangeIsOnSingleLine: () => rangeIsOnSingleLine,
  rangeOfNode: () => rangeOfNode,
  rangeOfTypeParameters: () => rangeOfTypeParameters,
  rangeOverlapsWithStartEnd: () => rangeOverlapsWithStartEnd,
  rangeStartIsOnSameLineAsRangeEnd: () => rangeStartIsOnSameLineAsRangeEnd,
  rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine,
  readBuilderProgram: () => readBuilderProgram,
  readConfigFile: () => readConfigFile,
  readHelper: () => readHelper,
  readJson: () => readJson,
  readJsonConfigFile: () => readJsonConfigFile,
  readJsonOrUndefined: () => readJsonOrUndefined,
  realizeDiagnostics: () => realizeDiagnostics,
  reduceEachLeadingCommentRange: () => reduceEachLeadingCommentRange,
  reduceEachTrailingCommentRange: () => reduceEachTrailingCommentRange,
  reduceLeft: () => reduceLeft,
  reduceLeftIterator: () => reduceLeftIterator,
  reducePathComponents: () => reducePathComponents,
  refactor: () => ts_refactor_exports,
  regExpEscape: () => regExpEscape,
  relativeComplement: () => relativeComplement,
  removeAllComments: () => removeAllComments,
  removeEmitHelper: () => removeEmitHelper,
  removeExtension: () => removeExtension,
  removeFileExtension: () => removeFileExtension,
  removeIgnoredPath: () => removeIgnoredPath,
  removeMinAndVersionNumbers: () => removeMinAndVersionNumbers,
  removeOptionality: () => removeOptionality,
  removePrefix: () => removePrefix,
  removeSuffix: () => removeSuffix,
  removeTrailingDirectorySeparator: () => removeTrailingDirectorySeparator,
  repeatString: () => repeatString,
  replaceElement: () => replaceElement,
  resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson,
  resolveConfigFileProjectName: () => resolveConfigFileProjectName,
  resolveJSModule: () => resolveJSModule,
  resolveLibrary: () => resolveLibrary,
  resolveModuleName: () => resolveModuleName,
  resolveModuleNameFromCache: () => resolveModuleNameFromCache,
  resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson,
  resolvePath: () => resolvePath,
  resolveProjectReferencePath: () => resolveProjectReferencePath,
  resolveTripleslashReference: () => resolveTripleslashReference,
  resolveTypeReferenceDirective: () => resolveTypeReferenceDirective,
  resolvingEmptyArray: () => resolvingEmptyArray,
  restHelper: () => restHelper,
  returnFalse: () => returnFalse,
  returnNoopFileWatcher: () => returnNoopFileWatcher,
  returnTrue: () => returnTrue,
  returnUndefined: () => returnUndefined,
  returnsPromise: () => returnsPromise,
  runInitializersHelper: () => runInitializersHelper,
  sameFlatMap: () => sameFlatMap,
  sameMap: () => sameMap,
  sameMapping: () => sameMapping,
  scanShebangTrivia: () => scanShebangTrivia,
  scanTokenAtPosition: () => scanTokenAtPosition,
  scanner: () => scanner,
  screenStartingMessageCodes: () => screenStartingMessageCodes,
  semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations,
  serializeCompilerOptions: () => serializeCompilerOptions,
  server: () => ts_server_exports3,
  servicesVersion: () => servicesVersion,
  setCommentRange: () => setCommentRange,
  setConfigFileInOptions: () => setConfigFileInOptions,
  setConstantValue: () => setConstantValue,
  setEachParent: () => setEachParent,
  setEmitFlags: () => setEmitFlags,
  setFunctionNameHelper: () => setFunctionNameHelper,
  setGetSourceFileAsHashVersioned: () => setGetSourceFileAsHashVersioned,
  setIdentifierAutoGenerate: () => setIdentifierAutoGenerate,
  setIdentifierGeneratedImportReference: () => setIdentifierGeneratedImportReference,
  setIdentifierTypeArguments: () => setIdentifierTypeArguments,
  setInternalEmitFlags: () => setInternalEmitFlags,
  setLocalizedDiagnosticMessages: () => setLocalizedDiagnosticMessages,
  setModuleDefaultHelper: () => setModuleDefaultHelper,
  setNodeFlags: () => setNodeFlags,
  setObjectAllocator: () => setObjectAllocator,
  setOriginalNode: () => setOriginalNode,
  setParent: () => setParent,
  setParentRecursive: () => setParentRecursive,
  setPrivateIdentifier: () => setPrivateIdentifier,
  setResolvedModule: () => setResolvedModule,
  setResolvedTypeReferenceDirective: () => setResolvedTypeReferenceDirective,
  setSnippetElement: () => setSnippetElement,
  setSourceMapRange: () => setSourceMapRange,
  setStackTraceLimit: () => setStackTraceLimit,
  setStartsOnNewLine: () => setStartsOnNewLine,
  setSyntheticLeadingComments: () => setSyntheticLeadingComments,
  setSyntheticTrailingComments: () => setSyntheticTrailingComments,
  setSys: () => setSys,
  setSysLog: () => setSysLog,
  setTextRange: () => setTextRange,
  setTextRangeEnd: () => setTextRangeEnd,
  setTextRangePos: () => setTextRangePos,
  setTextRangePosEnd: () => setTextRangePosEnd,
  setTextRangePosWidth: () => setTextRangePosWidth,
  setTokenSourceMapRange: () => setTokenSourceMapRange,
  setTypeNode: () => setTypeNode,
  setUILocale: () => setUILocale,
  setValueDeclaration: () => setValueDeclaration,
  shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension,
  shouldPreserveConstEnums: () => shouldPreserveConstEnums,
  shouldResolveJsRequire: () => shouldResolveJsRequire,
  shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules,
  showModuleSpecifier: () => showModuleSpecifier,
  signatureHasLiteralTypes: () => signatureHasLiteralTypes,
  signatureHasRestParameter: () => signatureHasRestParameter,
  signatureToDisplayParts: () => signatureToDisplayParts,
  single: () => single,
  singleElementArray: () => singleElementArray,
  singleIterator: () => singleIterator,
  singleOrMany: () => singleOrMany,
  singleOrUndefined: () => singleOrUndefined,
  skipAlias: () => skipAlias,
  skipAssertions: () => skipAssertions,
  skipConstraint: () => skipConstraint,
  skipOuterExpressions: () => skipOuterExpressions,
  skipParentheses: () => skipParentheses,
  skipPartiallyEmittedExpressions: () => skipPartiallyEmittedExpressions,
  skipTrivia: () => skipTrivia,
  skipTypeChecking: () => skipTypeChecking,
  skipTypeParentheses: () => skipTypeParentheses,
  skipWhile: () => skipWhile,
  sliceAfter: () => sliceAfter,
  some: () => some,
  sort: () => sort,
  sortAndDeduplicate: () => sortAndDeduplicate,
  sortAndDeduplicateDiagnostics: () => sortAndDeduplicateDiagnostics,
  sourceFileAffectingCompilerOptions: () => sourceFileAffectingCompilerOptions,
  sourceFileMayBeEmitted: () => sourceFileMayBeEmitted,
  sourceMapCommentRegExp: () => sourceMapCommentRegExp,
  sourceMapCommentRegExpDontCareLineStart: () => sourceMapCommentRegExpDontCareLineStart,
  spacePart: () => spacePart,
  spanMap: () => spanMap,
  spreadArrayHelper: () => spreadArrayHelper,
  stableSort: () => stableSort,
  startEndContainsRange: () => startEndContainsRange,
  startEndOverlapsWithStartEnd: () => startEndOverlapsWithStartEnd,
  startOnNewLine: () => startOnNewLine,
  startTracing: () => startTracing,
  startsWith: () => startsWith,
  startsWithDirectory: () => startsWithDirectory,
  startsWithUnderscore: () => startsWithUnderscore,
  startsWithUseStrict: () => startsWithUseStrict,
  stringContains: () => stringContains,
  stringContainsAt: () => stringContainsAt,
  stringToToken: () => stringToToken,
  stripQuotes: () => stripQuotes,
  supportedDeclarationExtensions: () => supportedDeclarationExtensions,
  supportedJSExtensions: () => supportedJSExtensions,
  supportedJSExtensionsFlat: () => supportedJSExtensionsFlat,
  supportedLocaleDirectories: () => supportedLocaleDirectories,
  supportedTSExtensions: () => supportedTSExtensions,
  supportedTSExtensionsFlat: () => supportedTSExtensionsFlat,
  supportedTSImplementationExtensions: () => supportedTSImplementationExtensions,
  suppressLeadingAndTrailingTrivia: () => suppressLeadingAndTrailingTrivia,
  suppressLeadingTrivia: () => suppressLeadingTrivia,
  suppressTrailingTrivia: () => suppressTrailingTrivia,
  symbolEscapedNameNoDefault: () => symbolEscapedNameNoDefault,
  symbolName: () => symbolName,
  symbolNameNoDefault: () => symbolNameNoDefault,
  symbolPart: () => symbolPart,
  symbolToDisplayParts: () => symbolToDisplayParts,
  syntaxMayBeASICandidate: () => syntaxMayBeASICandidate,
  syntaxRequiresTrailingSemicolonOrASI: () => syntaxRequiresTrailingSemicolonOrASI,
  sys: () => sys,
  sysLog: () => sysLog,
  tagNamesAreEquivalent: () => tagNamesAreEquivalent,
  takeWhile: () => takeWhile,
  targetOptionDeclaration: () => targetOptionDeclaration,
  templateObjectHelper: () => templateObjectHelper,
  testFormatSettings: () => testFormatSettings,
  textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged,
  textChangeRangeNewSpan: () => textChangeRangeNewSpan,
  textChanges: () => ts_textChanges_exports,
  textOrKeywordPart: () => textOrKeywordPart,
  textPart: () => textPart,
  textRangeContainsPositionInclusive: () => textRangeContainsPositionInclusive,
  textSpanContainsPosition: () => textSpanContainsPosition,
  textSpanContainsTextSpan: () => textSpanContainsTextSpan,
  textSpanEnd: () => textSpanEnd,
  textSpanIntersection: () => textSpanIntersection,
  textSpanIntersectsWith: () => textSpanIntersectsWith,
  textSpanIntersectsWithPosition: () => textSpanIntersectsWithPosition,
  textSpanIntersectsWithTextSpan: () => textSpanIntersectsWithTextSpan,
  textSpanIsEmpty: () => textSpanIsEmpty,
  textSpanOverlap: () => textSpanOverlap,
  textSpanOverlapsWith: () => textSpanOverlapsWith,
  textSpansEqual: () => textSpansEqual,
  textToKeywordObj: () => textToKeywordObj,
  timestamp: () => timestamp,
  toArray: () => toArray,
  toBuilderFileEmit: () => toBuilderFileEmit,
  toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit,
  toEditorSettings: () => toEditorSettings,
  toFileNameLowerCase: () => toFileNameLowerCase,
  toLowerCase: () => toLowerCase,
  toPath: () => toPath,
  toProgramEmitPending: () => toProgramEmitPending,
  tokenIsIdentifierOrKeyword: () => tokenIsIdentifierOrKeyword,
  tokenIsIdentifierOrKeywordOrGreaterThan: () => tokenIsIdentifierOrKeywordOrGreaterThan,
  tokenToString: () => tokenToString,
  trace: () => trace,
  tracing: () => tracing,
  tracingEnabled: () => tracingEnabled,
  transform: () => transform,
  transformClassFields: () => transformClassFields,
  transformDeclarations: () => transformDeclarations,
  transformECMAScriptModule: () => transformECMAScriptModule,
  transformES2015: () => transformES2015,
  transformES2016: () => transformES2016,
  transformES2017: () => transformES2017,
  transformES2018: () => transformES2018,
  transformES2019: () => transformES2019,
  transformES2020: () => transformES2020,
  transformES2021: () => transformES2021,
  transformES5: () => transformES5,
  transformESDecorators: () => transformESDecorators,
  transformESNext: () => transformESNext,
  transformGenerators: () => transformGenerators,
  transformJsx: () => transformJsx,
  transformLegacyDecorators: () => transformLegacyDecorators,
  transformModule: () => transformModule,
  transformNodeModule: () => transformNodeModule,
  transformNodes: () => transformNodes,
  transformSystemModule: () => transformSystemModule,
  transformTypeScript: () => transformTypeScript,
  transpile: () => transpile,
  transpileModule: () => transpileModule,
  transpileOptionValueCompilerOptions: () => transpileOptionValueCompilerOptions,
  trimString: () => trimString,
  trimStringEnd: () => trimStringEnd,
  trimStringStart: () => trimStringStart,
  tryAddToSet: () => tryAddToSet,
  tryAndIgnoreErrors: () => tryAndIgnoreErrors,
  tryCast: () => tryCast,
  tryDirectoryExists: () => tryDirectoryExists,
  tryExtractTSExtension: () => tryExtractTSExtension,
  tryFileExists: () => tryFileExists,
  tryGetClassExtendingExpressionWithTypeArguments: () => tryGetClassExtendingExpressionWithTypeArguments,
  tryGetClassImplementingOrExtendingExpressionWithTypeArguments: () => tryGetClassImplementingOrExtendingExpressionWithTypeArguments,
  tryGetDirectories: () => tryGetDirectories,
  tryGetExtensionFromPath: () => tryGetExtensionFromPath2,
  tryGetImportFromModuleSpecifier: () => tryGetImportFromModuleSpecifier,
  tryGetJSDocSatisfiesTypeNode: () => tryGetJSDocSatisfiesTypeNode,
  tryGetModuleNameFromFile: () => tryGetModuleNameFromFile,
  tryGetModuleSpecifierFromDeclaration: () => tryGetModuleSpecifierFromDeclaration,
  tryGetNativePerformanceHooks: () => tryGetNativePerformanceHooks,
  tryGetPropertyAccessOrIdentifierToString: () => tryGetPropertyAccessOrIdentifierToString,
  tryGetPropertyNameOfBindingOrAssignmentElement: () => tryGetPropertyNameOfBindingOrAssignmentElement,
  tryGetSourceMappingURL: () => tryGetSourceMappingURL,
  tryGetTextOfPropertyName: () => tryGetTextOfPropertyName,
  tryIOAndConsumeErrors: () => tryIOAndConsumeErrors,
  tryParsePattern: () => tryParsePattern,
  tryParsePatterns: () => tryParsePatterns,
  tryParseRawSourceMap: () => tryParseRawSourceMap,
  tryReadDirectory: () => tryReadDirectory,
  tryReadFile: () => tryReadFile,
  tryRemoveDirectoryPrefix: () => tryRemoveDirectoryPrefix,
  tryRemoveExtension: () => tryRemoveExtension,
  tryRemovePrefix: () => tryRemovePrefix,
  tryRemoveSuffix: () => tryRemoveSuffix,
  typeAcquisitionDeclarations: () => typeAcquisitionDeclarations,
  typeAliasNamePart: () => typeAliasNamePart,
  typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo,
  typeKeywords: () => typeKeywords,
  typeParameterNamePart: () => typeParameterNamePart,
  typeReferenceResolutionNameAndModeGetter: () => typeReferenceResolutionNameAndModeGetter,
  typeToDisplayParts: () => typeToDisplayParts,
  unchangedPollThresholds: () => unchangedPollThresholds,
  unchangedTextChangeRange: () => unchangedTextChangeRange,
  unescapeLeadingUnderscores: () => unescapeLeadingUnderscores,
  unmangleScopedPackageName: () => unmangleScopedPackageName,
  unorderedRemoveItem: () => unorderedRemoveItem,
  unorderedRemoveItemAt: () => unorderedRemoveItemAt,
  unreachableCodeIsError: () => unreachableCodeIsError,
  unusedLabelIsError: () => unusedLabelIsError,
  unwrapInnermostStatementOfLabel: () => unwrapInnermostStatementOfLabel,
  updateErrorForNoInputFiles: () => updateErrorForNoInputFiles,
  updateLanguageServiceSourceFile: () => updateLanguageServiceSourceFile,
  updateMissingFilePathsWatch: () => updateMissingFilePathsWatch,
  updatePackageJsonWatch: () => updatePackageJsonWatch,
  updateResolutionField: () => updateResolutionField,
  updateSharedExtendedConfigFileWatcher: () => updateSharedExtendedConfigFileWatcher,
  updateSourceFile: () => updateSourceFile,
  updateWatchingWildcardDirectories: () => updateWatchingWildcardDirectories,
  usesExtensionsOnImports: () => usesExtensionsOnImports,
  usingSingleLineStringWriter: () => usingSingleLineStringWriter,
  utf16EncodeAsString: () => utf16EncodeAsString,
  validateLocaleAndSetLanguage: () => validateLocaleAndSetLanguage,
  valuesHelper: () => valuesHelper,
  version: () => version,
  versionMajorMinor: () => versionMajorMinor,
  visitArray: () => visitArray,
  visitCommaListElements: () => visitCommaListElements,
  visitEachChild: () => visitEachChild,
  visitFunctionBody: () => visitFunctionBody,
  visitIterationBody: () => visitIterationBody,
  visitLexicalEnvironment: () => visitLexicalEnvironment,
  visitNode: () => visitNode,
  visitNodes: () => visitNodes2,
  visitParameterList: () => visitParameterList,
  walkUpBindingElementsAndPatterns: () => walkUpBindingElementsAndPatterns,
  walkUpLexicalEnvironments: () => walkUpLexicalEnvironments,
  walkUpOuterExpressions: () => walkUpOuterExpressions,
  walkUpParenthesizedExpressions: () => walkUpParenthesizedExpressions,
  walkUpParenthesizedTypes: () => walkUpParenthesizedTypes,
  walkUpParenthesizedTypesAndGetParentAndChild: () => walkUpParenthesizedTypesAndGetParentAndChild,
  whitespaceOrMapCommentRegExp: () => whitespaceOrMapCommentRegExp,
  writeCommentRange: () => writeCommentRange,
  writeFile: () => writeFile,
  writeFileEnsuringDirectories: () => writeFileEnsuringDirectories,
  zipToModeAwareCache: () => zipToModeAwareCache,
  zipWith: () => zipWith
});

// src/deprecatedCompat/deprecate.ts
var enableDeprecationWarnings = true;
var typeScriptVersion2;
function getTypeScriptVersion() {
  return typeScriptVersion2 ?? (typeScriptVersion2 = new Version(version));
}
function formatDeprecationMessage(name, error, errorAfter, since, message) {
  let deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
  deprecationMessage += `'${name}' `;
  deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated";
  deprecationMessage += error ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : ".";
  deprecationMessage += message ? ` ${formatStringFromArgs(message, [name], 0)}` : "";
  return deprecationMessage;
}
function createErrorDeprecation(name, errorAfter, since, message) {
  const deprecationMessage = formatDeprecationMessage(
    name,
    /*error*/
    true,
    errorAfter,
    since,
    message
  );
  return () => {
    throw new TypeError(deprecationMessage);
  };
}
function createWarningDeprecation(name, errorAfter, since, message) {
  let hasWrittenDeprecation = false;
  return () => {
    if (enableDeprecationWarnings && !hasWrittenDeprecation) {
      Debug.log.warn(formatDeprecationMessage(
        name,
        /*error*/
        false,
        errorAfter,
        since,
        message
      ));
      hasWrittenDeprecation = true;
    }
  };
}
function createDeprecation(name, options = {}) {
  const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion();
  const errorAfter = typeof options.errorAfter === "string" ? new Version(options.errorAfter) : options.errorAfter;
  const warnAfter = typeof options.warnAfter === "string" ? new Version(options.warnAfter) : options.warnAfter;
  const since = typeof options.since === "string" ? new Version(options.since) : options.since ?? warnAfter;
  const error = options.error || errorAfter && version2.compareTo(errorAfter) >= 0;
  const warn = !warnAfter || version2.compareTo(warnAfter) >= 0;
  return error ? createErrorDeprecation(name, errorAfter, since, options.message) : warn ? createWarningDeprecation(name, errorAfter, since, options.message) : noop;
}
function wrapFunction(deprecation, func) {
  return function() {
    deprecation();
    return func.apply(this, arguments);
  };
}
function deprecate(func, options) {
  const deprecation = createDeprecation((options == null ? void 0 : options.name) ?? Debug.getFunctionName(func), options);
  return wrapFunction(deprecation, func);
}

// src/deprecatedCompat/deprecations.ts
function createOverload(name, overloads, binder2, deprecations) {
  Object.defineProperty(call, "name", { ...Object.getOwnPropertyDescriptor(call, "name"), value: name });
  if (deprecations) {
    for (const key of Object.keys(deprecations)) {
      const index = +key;
      if (!isNaN(index) && hasProperty(overloads, `${index}`)) {
        overloads[index] = deprecate(overloads[index], { ...deprecations[index], name });
      }
    }
  }
  const bind = createBinder2(overloads, binder2);
  return call;
  function call(...args) {
    const index = bind(args);
    const fn = index !== void 0 ? overloads[index] : void 0;
    if (typeof fn === "function") {
      return fn(...args);
    }
    throw new TypeError("Invalid arguments");
  }
}
function createBinder2(overloads, binder2) {
  return (args) => {
    for (let i = 0; hasProperty(overloads, `${i}`) && hasProperty(binder2, `${i}`); i++) {
      const fn = binder2[i];
      if (fn(args)) {
        return i;
      }
    }
  };
}
function buildOverload(name) {
  return {
    overload: (overloads) => ({
      bind: (binder2) => ({
        finish: () => createOverload(name, overloads, binder2),
        deprecate: (deprecations) => ({
          finish: () => createOverload(name, overloads, binder2, deprecations)
        })
      })
    })
  };
}

// src/deprecatedCompat/5.0/identifierProperties.ts
addObjectAllocatorPatcher((objectAllocator2) => {
  const Identifier74 = objectAllocator2.getIdentifierConstructor();
  if (!hasProperty(Identifier74.prototype, "originalKeywordKind")) {
    Object.defineProperty(Identifier74.prototype, "originalKeywordKind", {
      get: deprecate(function() {
        return identifierToKeywordKind(this);
      }, {
        name: "originalKeywordKind",
        since: "5.0",
        warnAfter: "5.1",
        errorAfter: "5.2",
        message: "Use 'identifierToKeywordKind(identifier)' instead."
      })
    });
  }
  if (!hasProperty(Identifier74.prototype, "isInJSDocNamespace")) {
    Object.defineProperty(Identifier74.prototype, "isInJSDocNamespace", {
      get: deprecate(function() {
        return this.flags & 2048 /* IdentifierIsInJSDocNamespace */ ? true : void 0;
      }, {
        name: "isInJSDocNamespace",
        since: "5.0",
        warnAfter: "5.1",
        errorAfter: "5.2",
        message: "Use '.parent' or the surrounding context to determine this instead."
      })
    });
  }
});

// src/server/_namespaces/ts.server.ts
var ts_server_exports3 = {};
__export(ts_server_exports3, {
  ActionInvalidate: () => ActionInvalidate,
  ActionPackageInstalled: () => ActionPackageInstalled,
  ActionSet: () => ActionSet,
  ActionWatchTypingLocations: () => ActionWatchTypingLocations,
  Arguments: () => Arguments,
  AutoImportProviderProject: () => AutoImportProviderProject,
  CharRangeSection: () => CharRangeSection,
  CommandNames: () => CommandNames,
  ConfigFileDiagEvent: () => ConfigFileDiagEvent,
  ConfiguredProject: () => ConfiguredProject2,
  Errors: () => Errors,
  EventBeginInstallTypes: () => EventBeginInstallTypes,
  EventEndInstallTypes: () => EventEndInstallTypes,
  EventInitializationFailed: () => EventInitializationFailed,
  EventTypesRegistry: () => EventTypesRegistry,
  ExternalProject: () => ExternalProject2,
  GcTimer: () => GcTimer,
  InferredProject: () => InferredProject2,
  LargeFileReferencedEvent: () => LargeFileReferencedEvent,
  LineIndex: () => LineIndex,
  LineLeaf: () => LineLeaf,
  LineNode: () => LineNode,
  LogLevel: () => LogLevel2,
  Msg: () => Msg,
  OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent,
  Project: () => Project3,
  ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent,
  ProjectKind: () => ProjectKind,
  ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent,
  ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent,
  ProjectLoadingStartEvent: () => ProjectLoadingStartEvent,
  ProjectReferenceProjectLoadKind: () => ProjectReferenceProjectLoadKind,
  ProjectService: () => ProjectService3,
  ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent,
  ScriptInfo: () => ScriptInfo,
  ScriptVersionCache: () => ScriptVersionCache,
  Session: () => Session3,
  TextStorage: () => TextStorage,
  ThrottledOperations: () => ThrottledOperations,
  TypingsCache: () => TypingsCache,
  allFilesAreJsOrDts: () => allFilesAreJsOrDts,
  allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts,
  asNormalizedPath: () => asNormalizedPath,
  convertCompilerOptions: () => convertCompilerOptions,
  convertFormatOptions: () => convertFormatOptions,
  convertScriptKindName: () => convertScriptKindName,
  convertTypeAcquisition: () => convertTypeAcquisition,
  convertUserPreferences: () => convertUserPreferences,
  convertWatchOptions: () => convertWatchOptions,
  countEachFileTypes: () => countEachFileTypes,
  createInstallTypingsRequest: () => createInstallTypingsRequest,
  createModuleSpecifierCache: () => createModuleSpecifierCache,
  createNormalizedPathMap: () => createNormalizedPathMap,
  createPackageJsonCache: () => createPackageJsonCache,
  createSortedArray: () => createSortedArray2,
  emptyArray: () => emptyArray2,
  findArgument: () => findArgument,
  forEachResolvedProjectReferenceProject: () => forEachResolvedProjectReferenceProject,
  formatDiagnosticToProtocol: () => formatDiagnosticToProtocol,
  formatMessage: () => formatMessage2,
  getBaseConfigFileName: () => getBaseConfigFileName,
  getLocationInNewDocument: () => getLocationInNewDocument,
  hasArgument: () => hasArgument,
  hasNoTypeScriptSource: () => hasNoTypeScriptSource,
  indent: () => indent2,
  isConfigFile: () => isConfigFile,
  isConfiguredProject: () => isConfiguredProject,
  isDynamicFileName: () => isDynamicFileName,
  isExternalProject: () => isExternalProject,
  isInferredProject: () => isInferredProject,
  isInferredProjectName: () => isInferredProjectName,
  makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName,
  makeAuxiliaryProjectName: () => makeAuxiliaryProjectName,
  makeInferredProjectName: () => makeInferredProjectName,
  maxFileSize: () => maxFileSize,
  maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles,
  normalizedPathToPath: () => normalizedPathToPath,
  nowString: () => nowString,
  nullCancellationToken: () => nullCancellationToken,
  nullTypingsInstaller: () => nullTypingsInstaller,
  projectContainsInfoDirectly: () => projectContainsInfoDirectly,
  protocol: () => ts_server_protocol_exports,
  removeSorted: () => removeSorted,
  stringifyIndented: () => stringifyIndented,
  toEvent: () => toEvent,
  toNormalizedPath: () => toNormalizedPath,
  tryConvertScriptKindName: () => tryConvertScriptKindName,
  typingsInstaller: () => ts_server_typingsInstaller_exports,
  updateProjectIfDirty: () => updateProjectIfDirty
});

// src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts
var ts_server_typingsInstaller_exports = {};
__export(ts_server_typingsInstaller_exports, {
  TypingsInstaller: () => TypingsInstaller,
  getNpmCommandForInstallation: () => getNpmCommandForInstallation,
  installNpmPackages: () => installNpmPackages,
  typingsName: () => typingsName
});

// src/typingsInstallerCore/typingsInstaller.ts
var nullLog = {
  isEnabled: () => false,
  writeLine: noop
};
function typingToFileName(cachePath, packageName, installTypingHost, log) {
  try {
    const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: 2 /* Node10 */ }, installTypingHost);
    return result.resolvedModule && result.resolvedModule.resolvedFileName;
  } catch (e) {
    if (log.isEnabled()) {
      log.writeLine(`Failed to resolve ${packageName} in folder '${cachePath}': ${e.message}`);
    }
    return void 0;
  }
}
function installNpmPackages(npmPath, tsVersion, packageNames, install) {
  let hasError = false;
  for (let remaining = packageNames.length; remaining > 0; ) {
    const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
    remaining = result.remaining;
    hasError = install(result.command) || hasError;
  }
  return hasError;
}
function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
  const sliceStart = packageNames.length - remaining;
  let command, toSlice = remaining;
  while (true) {
    command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`;
    if (command.length < 8e3) {
      break;
    }
    toSlice = toSlice - Math.floor(toSlice / 2);
  }
  return { command, remaining: remaining - toSlice };
}
var TypingsInstaller = class {
  constructor(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log = nullLog) {
    this.installTypingHost = installTypingHost;
    this.globalCachePath = globalCachePath;
    this.safeListPath = safeListPath;
    this.typesMapLocation = typesMapLocation;
    this.throttleLimit = throttleLimit;
    this.log = log;
    this.packageNameToTypingLocation = /* @__PURE__ */ new Map();
    this.missingTypingsSet = /* @__PURE__ */ new Set();
    this.knownCachesSet = /* @__PURE__ */ new Set();
    this.projectWatchers = /* @__PURE__ */ new Map();
    /** @internal */
    this.pendingRunRequests = [];
    this.installRunCount = 1;
    this.inFlightRequestCount = 0;
    this.latestDistTag = "latest";
    const isLoggingEnabled = this.log.isEnabled();
    if (isLoggingEnabled) {
      this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`);
    }
    this.processCacheLocation(this.globalCachePath);
  }
  closeProject(req) {
    this.closeWatchers(req.projectName);
  }
  closeWatchers(projectName) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Closing file watchers for project '${projectName}'`);
    }
    const watchers = this.projectWatchers.get(projectName);
    if (!watchers) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`No watchers are registered for project '${projectName}'`);
      }
      return;
    }
    this.projectWatchers.delete(projectName);
    this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] });
    if (this.log.isEnabled()) {
      this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`);
    }
  }
  install(req) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Got install request ${JSON.stringify(req)}`);
    }
    if (req.cachePath) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`Request specifies cache path '${req.cachePath}', loading cached information...`);
      }
      this.processCacheLocation(req.cachePath);
    }
    if (this.safeList === void 0) {
      this.initializeSafeList();
    }
    const discoverTypingsResult = ts_JsTyping_exports.discoverTypings(
      this.installTypingHost,
      this.log.isEnabled() ? (s) => this.log.writeLine(s) : void 0,
      req.fileNames,
      req.projectRootPath,
      this.safeList,
      this.packageNameToTypingLocation,
      req.typeAcquisition,
      req.unresolvedImports,
      this.typesRegistry,
      req.compilerOptions
    );
    if (this.log.isEnabled()) {
      this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`);
    }
    this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch);
    if (discoverTypingsResult.newTypingNames.length) {
      this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
    } else {
      this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
      if (this.log.isEnabled()) {
        this.log.writeLine(`No new typings were requested as a result of typings discovery`);
      }
    }
  }
  initializeSafeList() {
    if (this.typesMapLocation) {
      const safeListFromMap = ts_JsTyping_exports.loadTypesMap(this.installTypingHost, this.typesMapLocation);
      if (safeListFromMap) {
        this.log.writeLine(`Loaded safelist from types map file '${this.typesMapLocation}'`);
        this.safeList = safeListFromMap;
        return;
      }
      this.log.writeLine(`Failed to load safelist from types map file '${this.typesMapLocation}'`);
    }
    this.safeList = ts_JsTyping_exports.loadSafeList(this.installTypingHost, this.safeListPath);
  }
  processCacheLocation(cacheLocation) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Processing cache location '${cacheLocation}'`);
    }
    if (this.knownCachesSet.has(cacheLocation)) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`Cache location was already processed...`);
      }
      return;
    }
    const packageJson = combinePaths(cacheLocation, "package.json");
    const packageLockJson = combinePaths(cacheLocation, "package-lock.json");
    if (this.log.isEnabled()) {
      this.log.writeLine(`Trying to find '${packageJson}'...`);
    }
    if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
      const npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson));
      const npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson));
      if (this.log.isEnabled()) {
        this.log.writeLine(`Loaded content of '${packageJson}': ${JSON.stringify(npmConfig)}`);
        this.log.writeLine(`Loaded content of '${packageLockJson}'`);
      }
      if (npmConfig.devDependencies && npmLock.dependencies) {
        for (const key in npmConfig.devDependencies) {
          if (!hasProperty(npmLock.dependencies, key)) {
            continue;
          }
          const packageName = getBaseFileName(key);
          if (!packageName) {
            continue;
          }
          const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
          if (!typingFile) {
            this.missingTypingsSet.add(packageName);
            continue;
          }
          const existingTypingFile = this.packageNameToTypingLocation.get(packageName);
          if (existingTypingFile) {
            if (existingTypingFile.typingLocation === typingFile) {
              continue;
            }
            if (this.log.isEnabled()) {
              this.log.writeLine(`New typing for package ${packageName} from '${typingFile}' conflicts with existing typing file '${existingTypingFile}'`);
            }
          }
          if (this.log.isEnabled()) {
            this.log.writeLine(`Adding entry into typings cache: '${packageName}' => '${typingFile}'`);
          }
          const info = getProperty(npmLock.dependencies, key);
          const version2 = info && info.version;
          if (!version2) {
            continue;
          }
          const newTyping = { typingLocation: typingFile, version: new Version(version2) };
          this.packageNameToTypingLocation.set(packageName, newTyping);
        }
      }
    }
    if (this.log.isEnabled()) {
      this.log.writeLine(`Finished processing cache location '${cacheLocation}'`);
    }
    this.knownCachesSet.add(cacheLocation);
  }
  filterTypings(typingsToInstall) {
    return mapDefined(typingsToInstall, (typing) => {
      const typingKey = mangleScopedPackageName(typing);
      if (this.missingTypingsSet.has(typingKey)) {
        if (this.log.isEnabled())
          this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`);
        return void 0;
      }
      const validationResult = ts_JsTyping_exports.validatePackageName(typing);
      if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) {
        this.missingTypingsSet.add(typingKey);
        if (this.log.isEnabled())
          this.log.writeLine(ts_JsTyping_exports.renderPackageNameValidationFailure(validationResult, typing));
        return void 0;
      }
      if (!this.typesRegistry.has(typingKey)) {
        if (this.log.isEnabled())
          this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`);
        return void 0;
      }
      if (this.packageNameToTypingLocation.get(typingKey) && ts_JsTyping_exports.isTypingUpToDate(this.packageNameToTypingLocation.get(typingKey), this.typesRegistry.get(typingKey))) {
        if (this.log.isEnabled())
          this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`);
        return void 0;
      }
      return typingKey;
    });
  }
  ensurePackageDirectoryExists(directory) {
    const npmConfigPath = combinePaths(directory, "package.json");
    if (this.log.isEnabled()) {
      this.log.writeLine(`Npm config file: ${npmConfigPath}`);
    }
    if (!this.installTypingHost.fileExists(npmConfigPath)) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`Npm config file: '${npmConfigPath}' is missing, creating new one...`);
      }
      this.ensureDirectoryExists(directory, this.installTypingHost);
      this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
    }
  }
  installTypings(req, cachePath, currentlyCachedTypings, typingsToInstall) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`);
    }
    const filteredTypings = this.filterTypings(typingsToInstall);
    if (filteredTypings.length === 0) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`All typings are known to be missing or invalid - no need to install more typings`);
      }
      this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
      return;
    }
    this.ensurePackageDirectoryExists(cachePath);
    const requestId = this.installRunCount;
    this.installRunCount++;
    this.sendResponse({
      kind: EventBeginInstallTypes,
      eventId: requestId,
      typingsInstallerVersion: version,
      projectName: req.projectName
    });
    const scopedTypings = filteredTypings.map(typingsName);
    this.installTypingsAsync(requestId, scopedTypings, cachePath, (ok) => {
      try {
        if (!ok) {
          if (this.log.isEnabled()) {
            this.log.writeLine(`install request failed, marking packages as missing to prevent repeated requests: ${JSON.stringify(filteredTypings)}`);
          }
          for (const typing of filteredTypings) {
            this.missingTypingsSet.add(typing);
          }
          return;
        }
        if (this.log.isEnabled()) {
          this.log.writeLine(`Installed typings ${JSON.stringify(scopedTypings)}`);
        }
        const installedTypingFiles = [];
        for (const packageName of filteredTypings) {
          const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost, this.log);
          if (!typingFile) {
            this.missingTypingsSet.add(packageName);
            continue;
          }
          const distTags = this.typesRegistry.get(packageName);
          const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]);
          const newTyping = { typingLocation: typingFile, version: newVersion };
          this.packageNameToTypingLocation.set(packageName, newTyping);
          installedTypingFiles.push(typingFile);
        }
        if (this.log.isEnabled()) {
          this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`);
        }
        this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
      } finally {
        const response = {
          kind: EventEndInstallTypes,
          eventId: requestId,
          projectName: req.projectName,
          packagesToInstall: scopedTypings,
          installSuccess: ok,
          typingsInstallerVersion: version
        };
        this.sendResponse(response);
      }
    });
  }
  ensureDirectoryExists(directory, host) {
    const directoryName = getDirectoryPath(directory);
    if (!host.directoryExists(directoryName)) {
      this.ensureDirectoryExists(directoryName, host);
    }
    if (!host.directoryExists(directory)) {
      host.createDirectory(directory);
    }
  }
  watchFiles(projectName, files) {
    if (!files.length) {
      this.closeWatchers(projectName);
      return;
    }
    const existing = this.projectWatchers.get(projectName);
    const newSet = new Set(files);
    if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) {
      this.projectWatchers.set(projectName, newSet);
      this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files });
    } else {
      this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 });
    }
  }
  createSetTypings(request, typings) {
    return {
      projectName: request.projectName,
      typeAcquisition: request.typeAcquisition,
      compilerOptions: request.compilerOptions,
      typings,
      unresolvedImports: request.unresolvedImports,
      kind: ActionSet
    };
  }
  installTypingsAsync(requestId, packageNames, cwd, onRequestCompleted) {
    this.pendingRunRequests.unshift({ requestId, packageNames, cwd, onRequestCompleted });
    this.executeWithThrottling();
  }
  executeWithThrottling() {
    while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
      this.inFlightRequestCount++;
      const request = this.pendingRunRequests.pop();
      this.installWorker(request.requestId, request.packageNames, request.cwd, (ok) => {
        this.inFlightRequestCount--;
        request.onRequestCompleted(ok);
        this.executeWithThrottling();
      });
    }
  }
};
function typingsName(packageName) {
  return `@types/${packageName}@ts${versionMajorMinor}`;
}

// src/server/utilitiesPublic.ts
var LogLevel2 = /* @__PURE__ */ ((LogLevel3) => {
  LogLevel3[LogLevel3["terse"] = 0] = "terse";
  LogLevel3[LogLevel3["normal"] = 1] = "normal";
  LogLevel3[LogLevel3["requestTime"] = 2] = "requestTime";
  LogLevel3[LogLevel3["verbose"] = 3] = "verbose";
  return LogLevel3;
})(LogLevel2 || {});
var emptyArray2 = createSortedArray2();
var Msg = /* @__PURE__ */ ((Msg2) => {
  Msg2["Err"] = "Err";
  Msg2["Info"] = "Info";
  Msg2["Perf"] = "Perf";
  return Msg2;
})(Msg || {});
function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) {
  return {
    projectName: project.getProjectName(),
    fileNames: project.getFileNames(
      /*excludeFilesFromExternalLibraries*/
      true,
      /*excludeConfigFiles*/
      true
    ).concat(project.getExcludedFiles()),
    compilerOptions: project.getCompilationSettings(),
    typeAcquisition,
    unresolvedImports,
    projectRootPath: project.getCurrentDirectory(),
    cachePath,
    kind: "discover"
  };
}
var Errors;
((Errors2) => {
  function ThrowNoProject() {
    throw new Error("No Project.");
  }
  Errors2.ThrowNoProject = ThrowNoProject;
  function ThrowProjectLanguageServiceDisabled() {
    throw new Error("The project's language service is disabled.");
  }
  Errors2.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled;
  function ThrowProjectDoesNotContainDocument(fileName, project) {
    throw new Error(`Project '${project.getProjectName()}' does not contain document '${fileName}'`);
  }
  Errors2.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument;
})(Errors || (Errors = {}));
function toNormalizedPath(fileName) {
  return normalizePath(fileName);
}
function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) {
  const f = isRootedDiskPath(normalizedPath) ? normalizedPath : getNormalizedAbsolutePath(normalizedPath, currentDirectory);
  return getCanonicalFileName(f);
}
function asNormalizedPath(fileName) {
  return fileName;
}
function createNormalizedPathMap() {
  const map2 = /* @__PURE__ */ new Map();
  return {
    get(path) {
      return map2.get(path);
    },
    set(path, value) {
      map2.set(path, value);
    },
    contains(path) {
      return map2.has(path);
    },
    remove(path) {
      map2.delete(path);
    }
  };
}
function isInferredProjectName(name) {
  return /dev\/null\/inferredProject\d+\*/.test(name);
}
function makeInferredProjectName(counter) {
  return `/dev/null/inferredProject${counter}*`;
}
function makeAutoImportProviderProjectName(counter) {
  return `/dev/null/autoImportProviderProject${counter}*`;
}
function makeAuxiliaryProjectName(counter) {
  return `/dev/null/auxiliaryProject${counter}*`;
}
function createSortedArray2() {
  return [];
}

// src/server/utilities.ts
var ThrottledOperations = class {
  constructor(host, logger) {
    this.host = host;
    this.pendingTimeouts = /* @__PURE__ */ new Map();
    this.logger = logger.hasLevel(3 /* verbose */) ? logger : void 0;
  }
  /**
   * Wait `number` milliseconds and then invoke `cb`.  If, while waiting, schedule
   * is called again with the same `operationId`, cancel this operation in favor
   * of the new one.  (Note that the amount of time the canceled operation had been
   * waiting does not affect the amount of time that the new operation waits.)
   */
  schedule(operationId, delay, cb) {
    const pendingTimeout = this.pendingTimeouts.get(operationId);
    if (pendingTimeout) {
      this.host.clearTimeout(pendingTimeout);
    }
    this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, operationId, this, cb));
    if (this.logger) {
      this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`);
    }
  }
  cancel(operationId) {
    const pendingTimeout = this.pendingTimeouts.get(operationId);
    if (!pendingTimeout)
      return false;
    this.host.clearTimeout(pendingTimeout);
    return this.pendingTimeouts.delete(operationId);
  }
  static run(operationId, self, cb) {
    var _a, _b;
    (_a = perfLogger) == null ? void 0 : _a.logStartScheduledOperation(operationId);
    self.pendingTimeouts.delete(operationId);
    if (self.logger) {
      self.logger.info(`Running: ${operationId}`);
    }
    cb();
    (_b = perfLogger) == null ? void 0 : _b.logStopScheduledOperation();
  }
};
var GcTimer = class {
  constructor(host, delay, logger) {
    this.host = host;
    this.delay = delay;
    this.logger = logger;
  }
  scheduleCollect() {
    if (!this.host.gc || this.timerId !== void 0) {
      return;
    }
    this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this);
  }
  static run(self) {
    var _a, _b;
    self.timerId = void 0;
    (_a = perfLogger) == null ? void 0 : _a.logStartScheduledOperation("GC collect");
    const log = self.logger.hasLevel(2 /* requestTime */);
    const before = log && self.host.getMemoryUsage();
    self.host.gc();
    if (log) {
      const after = self.host.getMemoryUsage();
      self.logger.perftrc(`GC::before ${before}, after ${after}`);
    }
    (_b = perfLogger) == null ? void 0 : _b.logStopScheduledOperation();
  }
};
function getBaseConfigFileName(configFilePath) {
  const base = getBaseFileName(configFilePath);
  return base === "tsconfig.json" || base === "jsconfig.json" ? base : void 0;
}
function removeSorted(array, remove, compare) {
  if (!array || array.length === 0) {
    return;
  }
  if (array[0] === remove) {
    array.splice(0, 1);
    return;
  }
  const removeIndex = binarySearch(array, remove, identity, compare);
  if (removeIndex >= 0) {
    array.splice(removeIndex, 1);
  }
}
var indentStr = "\n    ";
function indent2(str) {
  return indentStr + str.replace(/\n/g, indentStr);
}
function stringifyIndented(json) {
  return indentStr + JSON.stringify(json);
}

// src/server/_namespaces/ts.server.protocol.ts
var ts_server_protocol_exports = {};
__export(ts_server_protocol_exports, {
  ClassificationType: () => ClassificationType2,
  CommandTypes: () => CommandTypes,
  CompletionTriggerKind: () => CompletionTriggerKind2,
  IndentStyle: () => IndentStyle2,
  JsxEmit: () => JsxEmit2,
  ModuleKind: () => ModuleKind2,
  ModuleResolutionKind: () => ModuleResolutionKind2,
  NewLineKind: () => NewLineKind2,
  OrganizeImportsMode: () => OrganizeImportsMode2,
  PollingWatchKind: () => PollingWatchKind2,
  ScriptTarget: () => ScriptTarget10,
  SemicolonPreference: () => SemicolonPreference2,
  WatchDirectoryKind: () => WatchDirectoryKind2,
  WatchFileKind: () => WatchFileKind2
});

// src/server/protocol.ts
var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => {
  CommandTypes2["JsxClosingTag"] = "jsxClosingTag";
  CommandTypes2["LinkedEditingRange"] = "linkedEditingRange";
  CommandTypes2["Brace"] = "brace";
  CommandTypes2["BraceFull"] = "brace-full";
  CommandTypes2["BraceCompletion"] = "braceCompletion";
  CommandTypes2["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment";
  CommandTypes2["Change"] = "change";
  CommandTypes2["Close"] = "close";
  CommandTypes2["Completions"] = "completions";
  CommandTypes2["CompletionInfo"] = "completionInfo";
  CommandTypes2["CompletionsFull"] = "completions-full";
  CommandTypes2["CompletionDetails"] = "completionEntryDetails";
  CommandTypes2["CompletionDetailsFull"] = "completionEntryDetails-full";
  CommandTypes2["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList";
  CommandTypes2["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile";
  CommandTypes2["Configure"] = "configure";
  CommandTypes2["Definition"] = "definition";
  CommandTypes2["DefinitionFull"] = "definition-full";
  CommandTypes2["DefinitionAndBoundSpan"] = "definitionAndBoundSpan";
  CommandTypes2["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full";
  CommandTypes2["Implementation"] = "implementation";
  CommandTypes2["ImplementationFull"] = "implementation-full";
  CommandTypes2["EmitOutput"] = "emit-output";
  CommandTypes2["Exit"] = "exit";
  CommandTypes2["FileReferences"] = "fileReferences";
  CommandTypes2["FileReferencesFull"] = "fileReferences-full";
  CommandTypes2["Format"] = "format";
  CommandTypes2["Formatonkey"] = "formatonkey";
  CommandTypes2["FormatFull"] = "format-full";
  CommandTypes2["FormatonkeyFull"] = "formatonkey-full";
  CommandTypes2["FormatRangeFull"] = "formatRange-full";
  CommandTypes2["Geterr"] = "geterr";
  CommandTypes2["GeterrForProject"] = "geterrForProject";
  CommandTypes2["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync";
  CommandTypes2["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
  CommandTypes2["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
  CommandTypes2["NavBar"] = "navbar";
  CommandTypes2["NavBarFull"] = "navbar-full";
  CommandTypes2["Navto"] = "navto";
  CommandTypes2["NavtoFull"] = "navto-full";
  CommandTypes2["NavTree"] = "navtree";
  CommandTypes2["NavTreeFull"] = "navtree-full";
  CommandTypes2["DocumentHighlights"] = "documentHighlights";
  CommandTypes2["DocumentHighlightsFull"] = "documentHighlights-full";
  CommandTypes2["Open"] = "open";
  CommandTypes2["Quickinfo"] = "quickinfo";
  CommandTypes2["QuickinfoFull"] = "quickinfo-full";
  CommandTypes2["References"] = "references";
  CommandTypes2["ReferencesFull"] = "references-full";
  CommandTypes2["Reload"] = "reload";
  CommandTypes2["Rename"] = "rename";
  CommandTypes2["RenameInfoFull"] = "rename-full";
  CommandTypes2["RenameLocationsFull"] = "renameLocations-full";
  CommandTypes2["Saveto"] = "saveto";
  CommandTypes2["SignatureHelp"] = "signatureHelp";
  CommandTypes2["SignatureHelpFull"] = "signatureHelp-full";
  CommandTypes2["FindSourceDefinition"] = "findSourceDefinition";
  CommandTypes2["Status"] = "status";
  CommandTypes2["TypeDefinition"] = "typeDefinition";
  CommandTypes2["ProjectInfo"] = "projectInfo";
  CommandTypes2["ReloadProjects"] = "reloadProjects";
  CommandTypes2["Unknown"] = "unknown";
  CommandTypes2["OpenExternalProject"] = "openExternalProject";
  CommandTypes2["OpenExternalProjects"] = "openExternalProjects";
  CommandTypes2["CloseExternalProject"] = "closeExternalProject";
  CommandTypes2["SynchronizeProjectList"] = "synchronizeProjectList";
  CommandTypes2["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
  CommandTypes2["UpdateOpen"] = "updateOpen";
  CommandTypes2["EncodedSyntacticClassificationsFull"] = "encodedSyntacticClassifications-full";
  CommandTypes2["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
  CommandTypes2["Cleanup"] = "cleanup";
  CommandTypes2["GetOutliningSpans"] = "getOutliningSpans";
  CommandTypes2["GetOutliningSpansFull"] = "outliningSpans";
  CommandTypes2["TodoComments"] = "todoComments";
  CommandTypes2["Indentation"] = "indentation";
  CommandTypes2["DocCommentTemplate"] = "docCommentTemplate";
  CommandTypes2["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full";
  CommandTypes2["NameOrDottedNameSpan"] = "nameOrDottedNameSpan";
  CommandTypes2["BreakpointStatement"] = "breakpointStatement";
  CommandTypes2["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects";
  CommandTypes2["GetCodeFixes"] = "getCodeFixes";
  CommandTypes2["GetCodeFixesFull"] = "getCodeFixes-full";
  CommandTypes2["GetCombinedCodeFix"] = "getCombinedCodeFix";
  CommandTypes2["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full";
  CommandTypes2["ApplyCodeActionCommand"] = "applyCodeActionCommand";
  CommandTypes2["GetSupportedCodeFixes"] = "getSupportedCodeFixes";
  CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors";
  CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor";
  CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions";
  CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full";
  CommandTypes2["OrganizeImports"] = "organizeImports";
  CommandTypes2["OrganizeImportsFull"] = "organizeImports-full";
  CommandTypes2["GetEditsForFileRename"] = "getEditsForFileRename";
  CommandTypes2["GetEditsForFileRenameFull"] = "getEditsForFileRename-full";
  CommandTypes2["ConfigurePlugin"] = "configurePlugin";
  CommandTypes2["SelectionRange"] = "selectionRange";
  CommandTypes2["SelectionRangeFull"] = "selectionRange-full";
  CommandTypes2["ToggleLineComment"] = "toggleLineComment";
  CommandTypes2["ToggleLineCommentFull"] = "toggleLineComment-full";
  CommandTypes2["ToggleMultilineComment"] = "toggleMultilineComment";
  CommandTypes2["ToggleMultilineCommentFull"] = "toggleMultilineComment-full";
  CommandTypes2["CommentSelection"] = "commentSelection";
  CommandTypes2["CommentSelectionFull"] = "commentSelection-full";
  CommandTypes2["UncommentSelection"] = "uncommentSelection";
  CommandTypes2["UncommentSelectionFull"] = "uncommentSelection-full";
  CommandTypes2["PrepareCallHierarchy"] = "prepareCallHierarchy";
  CommandTypes2["ProvideCallHierarchyIncomingCalls"] = "provideCallHierarchyIncomingCalls";
  CommandTypes2["ProvideCallHierarchyOutgoingCalls"] = "provideCallHierarchyOutgoingCalls";
  CommandTypes2["ProvideInlayHints"] = "provideInlayHints";
  return CommandTypes2;
})(CommandTypes || {});
var OrganizeImportsMode2 = /* @__PURE__ */ ((OrganizeImportsMode3) => {
  OrganizeImportsMode3["All"] = "All";
  OrganizeImportsMode3["SortAndCombine"] = "SortAndCombine";
  OrganizeImportsMode3["RemoveUnused"] = "RemoveUnused";
  return OrganizeImportsMode3;
})(OrganizeImportsMode2 || {});
var WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => {
  WatchFileKind3["FixedPollingInterval"] = "FixedPollingInterval";
  WatchFileKind3["PriorityPollingInterval"] = "PriorityPollingInterval";
  WatchFileKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling";
  WatchFileKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling";
  WatchFileKind3["UseFsEvents"] = "UseFsEvents";
  WatchFileKind3["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory";
  return WatchFileKind3;
})(WatchFileKind2 || {});
var WatchDirectoryKind2 = /* @__PURE__ */ ((WatchDirectoryKind3) => {
  WatchDirectoryKind3["UseFsEvents"] = "UseFsEvents";
  WatchDirectoryKind3["FixedPollingInterval"] = "FixedPollingInterval";
  WatchDirectoryKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling";
  WatchDirectoryKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling";
  return WatchDirectoryKind3;
})(WatchDirectoryKind2 || {});
var PollingWatchKind2 = /* @__PURE__ */ ((PollingWatchKind3) => {
  PollingWatchKind3["FixedInterval"] = "FixedInterval";
  PollingWatchKind3["PriorityInterval"] = "PriorityInterval";
  PollingWatchKind3["DynamicPriority"] = "DynamicPriority";
  PollingWatchKind3["FixedChunkSize"] = "FixedChunkSize";
  return PollingWatchKind3;
})(PollingWatchKind2 || {});
var CompletionTriggerKind2 = /* @__PURE__ */ ((CompletionTriggerKind4) => {
  CompletionTriggerKind4[CompletionTriggerKind4["Invoked"] = 1] = "Invoked";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter";
  CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions";
  return CompletionTriggerKind4;
})(CompletionTriggerKind2 || {});
var IndentStyle2 = /* @__PURE__ */ ((IndentStyle3) => {
  IndentStyle3["None"] = "None";
  IndentStyle3["Block"] = "Block";
  IndentStyle3["Smart"] = "Smart";
  return IndentStyle3;
})(IndentStyle2 || {});
var SemicolonPreference2 = /* @__PURE__ */ ((SemicolonPreference3) => {
  SemicolonPreference3["Ignore"] = "ignore";
  SemicolonPreference3["Insert"] = "insert";
  SemicolonPreference3["Remove"] = "remove";
  return SemicolonPreference3;
})(SemicolonPreference2 || {});
var JsxEmit2 = /* @__PURE__ */ ((JsxEmit3) => {
  JsxEmit3["None"] = "None";
  JsxEmit3["Preserve"] = "Preserve";
  JsxEmit3["ReactNative"] = "ReactNative";
  JsxEmit3["React"] = "React";
  return JsxEmit3;
})(JsxEmit2 || {});
var ModuleKind2 = /* @__PURE__ */ ((ModuleKind3) => {
  ModuleKind3["None"] = "None";
  ModuleKind3["CommonJS"] = "CommonJS";
  ModuleKind3["AMD"] = "AMD";
  ModuleKind3["UMD"] = "UMD";
  ModuleKind3["System"] = "System";
  ModuleKind3["ES6"] = "ES6";
  ModuleKind3["ES2015"] = "ES2015";
  ModuleKind3["ESNext"] = "ESNext";
  return ModuleKind3;
})(ModuleKind2 || {});
var ModuleResolutionKind2 = /* @__PURE__ */ ((ModuleResolutionKind3) => {
  ModuleResolutionKind3["Classic"] = "Classic";
  ModuleResolutionKind3["Node"] = "Node";
  return ModuleResolutionKind3;
})(ModuleResolutionKind2 || {});
var NewLineKind2 = /* @__PURE__ */ ((NewLineKind3) => {
  NewLineKind3["Crlf"] = "Crlf";
  NewLineKind3["Lf"] = "Lf";
  return NewLineKind3;
})(NewLineKind2 || {});
var ScriptTarget10 = /* @__PURE__ */ ((ScriptTarget11) => {
  ScriptTarget11["ES3"] = "ES3";
  ScriptTarget11["ES5"] = "ES5";
  ScriptTarget11["ES6"] = "ES6";
  ScriptTarget11["ES2015"] = "ES2015";
  ScriptTarget11["ES2016"] = "ES2016";
  ScriptTarget11["ES2017"] = "ES2017";
  ScriptTarget11["ES2018"] = "ES2018";
  ScriptTarget11["ES2019"] = "ES2019";
  ScriptTarget11["ES2020"] = "ES2020";
  ScriptTarget11["ES2021"] = "ES2021";
  ScriptTarget11["ES2022"] = "ES2022";
  ScriptTarget11["ESNext"] = "ESNext";
  return ScriptTarget11;
})(ScriptTarget10 || {});
var ClassificationType2 = /* @__PURE__ */ ((ClassificationType3) => {
  ClassificationType3[ClassificationType3["comment"] = 1] = "comment";
  ClassificationType3[ClassificationType3["identifier"] = 2] = "identifier";
  ClassificationType3[ClassificationType3["keyword"] = 3] = "keyword";
  ClassificationType3[ClassificationType3["numericLiteral"] = 4] = "numericLiteral";
  ClassificationType3[ClassificationType3["operator"] = 5] = "operator";
  ClassificationType3[ClassificationType3["stringLiteral"] = 6] = "stringLiteral";
  ClassificationType3[ClassificationType3["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
  ClassificationType3[ClassificationType3["whiteSpace"] = 8] = "whiteSpace";
  ClassificationType3[ClassificationType3["text"] = 9] = "text";
  ClassificationType3[ClassificationType3["punctuation"] = 10] = "punctuation";
  ClassificationType3[ClassificationType3["className"] = 11] = "className";
  ClassificationType3[ClassificationType3["enumName"] = 12] = "enumName";
  ClassificationType3[ClassificationType3["interfaceName"] = 13] = "interfaceName";
  ClassificationType3[ClassificationType3["moduleName"] = 14] = "moduleName";
  ClassificationType3[ClassificationType3["typeParameterName"] = 15] = "typeParameterName";
  ClassificationType3[ClassificationType3["typeAliasName"] = 16] = "typeAliasName";
  ClassificationType3[ClassificationType3["parameterName"] = 17] = "parameterName";
  ClassificationType3[ClassificationType3["docCommentTagName"] = 18] = "docCommentTagName";
  ClassificationType3[ClassificationType3["jsxOpenTagName"] = 19] = "jsxOpenTagName";
  ClassificationType3[ClassificationType3["jsxCloseTagName"] = 20] = "jsxCloseTagName";
  ClassificationType3[ClassificationType3["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
  ClassificationType3[ClassificationType3["jsxAttribute"] = 22] = "jsxAttribute";
  ClassificationType3[ClassificationType3["jsxText"] = 23] = "jsxText";
  ClassificationType3[ClassificationType3["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
  ClassificationType3[ClassificationType3["bigintLiteral"] = 25] = "bigintLiteral";
  return ClassificationType3;
})(ClassificationType2 || {});

// src/server/scriptInfo.ts
var TextStorage = class {
  constructor(host, info, initialVersion) {
    this.host = host;
    this.info = info;
    /**
     * True if the text is for the file thats open in the editor
     */
    this.isOpen = false;
    /**
     * True if the text present is the text from the file on the disk
     */
    this.ownFileText = false;
    /**
     * True when reloading contents of file from the disk is pending
     */
    this.pendingReloadFromDisk = false;
    this.version = initialVersion || 0;
  }
  getVersion() {
    return this.svc ? `SVC-${this.version}-${this.svc.getSnapshotVersion()}` : `Text-${this.version}`;
  }
  hasScriptVersionCache_TestOnly() {
    return this.svc !== void 0;
  }
  resetSourceMapInfo() {
    this.info.sourceFileLike = void 0;
    this.info.closeSourceMapFileWatcher();
    this.info.sourceMapFilePath = void 0;
    this.info.declarationInfoPath = void 0;
    this.info.sourceInfos = void 0;
    this.info.documentPositionMapper = void 0;
  }
  /** Public for testing */
  useText(newText) {
    this.svc = void 0;
    this.text = newText;
    this.textSnapshot = void 0;
    this.lineMap = void 0;
    this.fileSize = void 0;
    this.resetSourceMapInfo();
    this.version++;
  }
  edit(start2, end, newText) {
    this.switchToScriptVersionCache().edit(start2, end - start2, newText);
    this.ownFileText = false;
    this.text = void 0;
    this.textSnapshot = void 0;
    this.lineMap = void 0;
    this.fileSize = void 0;
    this.resetSourceMapInfo();
  }
  /**
   * Set the contents as newText
   * returns true if text changed
   */
  reload(newText) {
    Debug.assert(newText !== void 0);
    this.pendingReloadFromDisk = false;
    if (!this.text && this.svc) {
      this.text = getSnapshotText(this.svc.getSnapshot());
    }
    if (this.text !== newText) {
      this.useText(newText);
      this.ownFileText = false;
      return true;
    }
    return false;
  }
  /**
   * Reads the contents from tempFile(if supplied) or own file and sets it as contents
   * returns true if text changed
   */
  reloadWithFileText(tempFileName) {
    const { text: newText, fileSize } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { text: "", fileSize: void 0 };
    const reloaded = this.reload(newText);
    this.fileSize = fileSize;
    this.ownFileText = !tempFileName || tempFileName === this.info.fileName;
    return reloaded;
  }
  /**
   * Schedule reload from the disk if its not already scheduled and its not own text
   * returns true when scheduling reload
   */
  scheduleReloadIfNeeded() {
    return !this.pendingReloadFromDisk && !this.ownFileText ? this.pendingReloadFromDisk = true : false;
  }
  delayReloadFromFileIntoText() {
    this.pendingReloadFromDisk = true;
  }
  /**
   * For telemetry purposes, we would like to be able to report the size of the file.
   * However, we do not want telemetry to require extra file I/O so we report a size
   * that may be stale (e.g. may not reflect change made on disk since the last reload).
   * NB: Will read from disk if the file contents have never been loaded because
   * telemetry falsely indicating size 0 would be counter-productive.
   */
  getTelemetryFileSize() {
    return !!this.fileSize ? this.fileSize : !!this.text ? this.text.length : !!this.svc ? this.svc.getSnapshot().getLength() : this.getSnapshot().getLength();
  }
  getSnapshot() {
    var _a;
    return ((_a = this.tryUseScriptVersionCache()) == null ? void 0 : _a.getSnapshot()) || (this.textSnapshot ?? (this.textSnapshot = ScriptSnapshot.fromString(Debug.checkDefined(this.text))));
  }
  getAbsolutePositionAndLineText(oneBasedLine) {
    const svc = this.tryUseScriptVersionCache();
    if (svc)
      return svc.getAbsolutePositionAndLineText(oneBasedLine);
    const lineMap = this.getLineMap();
    return oneBasedLine <= lineMap.length ? {
      absolutePosition: lineMap[oneBasedLine - 1],
      lineText: this.text.substring(lineMap[oneBasedLine - 1], lineMap[oneBasedLine])
    } : {
      absolutePosition: this.text.length,
      lineText: void 0
    };
  }
  /**
   *  @param line 0 based index
   */
  lineToTextSpan(line) {
    const svc = this.tryUseScriptVersionCache();
    if (svc)
      return svc.lineToTextSpan(line);
    const lineMap = this.getLineMap();
    const start2 = lineMap[line];
    const end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length;
    return createTextSpanFromBounds(start2, end);
  }
  /**
   * @param line 1 based index
   * @param offset 1 based index
   */
  lineOffsetToPosition(line, offset, allowEdits) {
    const svc = this.tryUseScriptVersionCache();
    return svc ? svc.lineOffsetToPosition(line, offset) : computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits);
  }
  positionToLineOffset(position) {
    const svc = this.tryUseScriptVersionCache();
    if (svc)
      return svc.positionToLineOffset(position);
    const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position);
    return { line: line + 1, offset: character + 1 };
  }
  getFileTextAndSize(tempFileName) {
    let text;
    const fileName = tempFileName || this.info.fileName;
    const getText = () => text === void 0 ? text = this.host.readFile(fileName) || "" : text;
    if (!hasTSFileExtension(this.info.fileName)) {
      const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
      if (fileSize > maxFileSize) {
        Debug.assert(!!this.info.containingProjects.length);
        const service = this.info.containingProjects[0].projectService;
        service.logger.info(`Skipped loading contents of large file ${fileName} for info ${this.info.fileName}: fileSize: ${fileSize}`);
        this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize);
        return { text: "", fileSize };
      }
    }
    return { text: getText() };
  }
  /** @internal */
  switchToScriptVersionCache() {
    if (!this.svc || this.pendingReloadFromDisk) {
      this.svc = ScriptVersionCache.fromString(this.getOrLoadText());
      this.textSnapshot = void 0;
      this.version++;
    }
    return this.svc;
  }
  tryUseScriptVersionCache() {
    if (!this.svc || this.pendingReloadFromDisk) {
      this.getOrLoadText();
    }
    if (this.isOpen) {
      if (!this.svc && !this.textSnapshot) {
        this.svc = ScriptVersionCache.fromString(Debug.checkDefined(this.text));
        this.textSnapshot = void 0;
      }
      return this.svc;
    }
    return this.svc;
  }
  getOrLoadText() {
    if (this.text === void 0 || this.pendingReloadFromDisk) {
      Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk");
      this.reloadWithFileText();
    }
    return this.text;
  }
  getLineMap() {
    Debug.assert(!this.svc, "ScriptVersionCache should not be set");
    return this.lineMap || (this.lineMap = computeLineStarts(Debug.checkDefined(this.text)));
  }
  getLineInfo() {
    const svc = this.tryUseScriptVersionCache();
    if (svc) {
      return {
        getLineCount: () => svc.getLineCount(),
        getLineText: (line) => svc.getAbsolutePositionAndLineText(line + 1).lineText
      };
    }
    const lineMap = this.getLineMap();
    return getLineInfo(this.text, lineMap);
  }
};
function isDynamicFileName(fileName) {
  return fileName[0] === "^" || (stringContains(fileName, "walkThroughSnippet:/") || stringContains(fileName, "untitled:/")) && getBaseFileName(fileName)[0] === "^" || stringContains(fileName, ":^") && !stringContains(fileName, directorySeparator);
}
var ScriptInfo = class {
  constructor(host, fileName, scriptKind, hasMixedContent, path, initialVersion) {
    this.host = host;
    this.fileName = fileName;
    this.scriptKind = scriptKind;
    this.hasMixedContent = hasMixedContent;
    this.path = path;
    /**
     * All projects that include this file
     */
    this.containingProjects = [];
    this.isDynamic = isDynamicFileName(fileName);
    this.textStorage = new TextStorage(host, this, initialVersion);
    if (hasMixedContent || this.isDynamic) {
      this.realpath = this.path;
    }
    this.scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName);
  }
  /** @internal */
  isDynamicOrHasMixedContent() {
    return this.hasMixedContent || this.isDynamic;
  }
  isScriptOpen() {
    return this.textStorage.isOpen;
  }
  open(newText) {
    this.textStorage.isOpen = true;
    if (newText !== void 0 && this.textStorage.reload(newText)) {
      this.markContainingProjectsAsDirty();
    }
  }
  close(fileExists = true) {
    this.textStorage.isOpen = false;
    if (fileExists && this.textStorage.scheduleReloadIfNeeded()) {
      this.markContainingProjectsAsDirty();
    }
  }
  getSnapshot() {
    return this.textStorage.getSnapshot();
  }
  ensureRealPath() {
    if (this.realpath === void 0) {
      this.realpath = this.path;
      if (this.host.realpath) {
        Debug.assert(!!this.containingProjects.length);
        const project = this.containingProjects[0];
        const realpath = this.host.realpath(this.path);
        if (realpath) {
          this.realpath = project.toPath(realpath);
          if (this.realpath !== this.path) {
            project.projectService.realpathToScriptInfos.add(this.realpath, this);
          }
        }
      }
    }
  }
  /** @internal */
  getRealpathIfDifferent() {
    return this.realpath && this.realpath !== this.path ? this.realpath : void 0;
  }
  /**
   * @internal
   * Does not compute realpath; uses precomputed result. Use `ensureRealPath`
   * first if a definite result is needed.
   */
  isSymlink() {
    return this.realpath && this.realpath !== this.path;
  }
  getFormatCodeSettings() {
    return this.formatSettings;
  }
  getPreferences() {
    return this.preferences;
  }
  attachToProject(project) {
    const isNew = !this.isAttached(project);
    if (isNew) {
      this.containingProjects.push(project);
      if (!project.getCompilerOptions().preserveSymlinks) {
        this.ensureRealPath();
      }
      project.onFileAddedOrRemoved(this.isSymlink());
    }
    return isNew;
  }
  isAttached(project) {
    switch (this.containingProjects.length) {
      case 0:
        return false;
      case 1:
        return this.containingProjects[0] === project;
      case 2:
        return this.containingProjects[0] === project || this.containingProjects[1] === project;
      default:
        return contains(this.containingProjects, project);
    }
  }
  detachFromProject(project) {
    switch (this.containingProjects.length) {
      case 0:
        return;
      case 1:
        if (this.containingProjects[0] === project) {
          project.onFileAddedOrRemoved(this.isSymlink());
          this.containingProjects.pop();
        }
        break;
      case 2:
        if (this.containingProjects[0] === project) {
          project.onFileAddedOrRemoved(this.isSymlink());
          this.containingProjects[0] = this.containingProjects.pop();
        } else if (this.containingProjects[1] === project) {
          project.onFileAddedOrRemoved(this.isSymlink());
          this.containingProjects.pop();
        }
        break;
      default:
        if (unorderedRemoveItem(this.containingProjects, project)) {
          project.onFileAddedOrRemoved(this.isSymlink());
        }
        break;
    }
  }
  detachAllProjects() {
    for (const p of this.containingProjects) {
      if (isConfiguredProject(p)) {
        p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, 2 /* Deleted */);
      }
      const existingRoot = p.getRootFilesMap().get(this.path);
      p.removeFile(
        this,
        /*fileExists*/
        false,
        /*detachFromProject*/
        false
      );
      p.onFileAddedOrRemoved(this.isSymlink());
      if (existingRoot && !isInferredProject(p)) {
        p.addMissingFileRoot(existingRoot.fileName);
      }
    }
    clear(this.containingProjects);
  }
  getDefaultProject() {
    switch (this.containingProjects.length) {
      case 0:
        return Errors.ThrowNoProject();
      case 1:
        return ensurePrimaryProjectKind(this.containingProjects[0]);
      default:
        let firstExternalProject;
        let firstConfiguredProject;
        let firstInferredProject;
        let firstNonSourceOfProjectReferenceRedirect;
        let defaultConfiguredProject;
        for (let index = 0; index < this.containingProjects.length; index++) {
          const project = this.containingProjects[index];
          if (isConfiguredProject(project)) {
            if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) {
              if (defaultConfiguredProject === void 0 && index !== this.containingProjects.length - 1) {
                defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false;
              }
              if (defaultConfiguredProject === project)
                return project;
              if (!firstNonSourceOfProjectReferenceRedirect)
                firstNonSourceOfProjectReferenceRedirect = project;
            }
            if (!firstConfiguredProject)
              firstConfiguredProject = project;
          } else if (!firstExternalProject && isExternalProject(project)) {
            firstExternalProject = project;
          } else if (!firstInferredProject && isInferredProject(project)) {
            firstInferredProject = project;
          }
        }
        return ensurePrimaryProjectKind(defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstExternalProject || firstInferredProject);
    }
  }
  registerFileUpdate() {
    for (const p of this.containingProjects) {
      p.registerFileUpdate(this.path);
    }
  }
  setOptions(formatSettings, preferences) {
    if (formatSettings) {
      if (!this.formatSettings) {
        this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine);
        assign(this.formatSettings, formatSettings);
      } else {
        this.formatSettings = { ...this.formatSettings, ...formatSettings };
      }
    }
    if (preferences) {
      if (!this.preferences) {
        this.preferences = emptyOptions;
      }
      this.preferences = { ...this.preferences, ...preferences };
    }
  }
  getLatestVersion() {
    this.textStorage.getSnapshot();
    return this.textStorage.getVersion();
  }
  saveTo(fileName) {
    this.host.writeFile(fileName, getSnapshotText(this.textStorage.getSnapshot()));
  }
  /** @internal */
  delayReloadNonMixedContentFile() {
    Debug.assert(!this.isDynamicOrHasMixedContent());
    this.textStorage.delayReloadFromFileIntoText();
    this.markContainingProjectsAsDirty();
  }
  reloadFromFile(tempFileName) {
    if (this.textStorage.reloadWithFileText(tempFileName)) {
      this.markContainingProjectsAsDirty();
      return true;
    }
    return false;
  }
  editContent(start2, end, newText) {
    this.textStorage.edit(start2, end, newText);
    this.markContainingProjectsAsDirty();
  }
  markContainingProjectsAsDirty() {
    for (const p of this.containingProjects) {
      p.markFileAsDirty(this.path);
    }
  }
  isOrphan() {
    return !forEach(this.containingProjects, (p) => !p.isOrphan());
  }
  /** @internal */
  isContainedByBackgroundProject() {
    return some(
      this.containingProjects,
      (p) => p.projectKind === 3 /* AutoImportProvider */ || p.projectKind === 4 /* Auxiliary */
    );
  }
  /**
   *  @param line 1 based index
   */
  lineToTextSpan(line) {
    return this.textStorage.lineToTextSpan(line);
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  lineOffsetToPosition(line, offset, allowEdits) {
    return this.textStorage.lineOffsetToPosition(line, offset, allowEdits);
  }
  positionToLineOffset(position) {
    failIfInvalidPosition(position);
    const location = this.textStorage.positionToLineOffset(position);
    failIfInvalidLocation(location);
    return location;
  }
  isJavaScript() {
    return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */;
  }
  /** @internal */
  closeSourceMapFileWatcher() {
    if (this.sourceMapFilePath && !isString(this.sourceMapFilePath)) {
      closeFileWatcherOf(this.sourceMapFilePath);
      this.sourceMapFilePath = void 0;
    }
  }
};
function ensurePrimaryProjectKind(project) {
  if (!project || project.projectKind === 3 /* AutoImportProvider */ || project.projectKind === 4 /* Auxiliary */) {
    return Errors.ThrowNoProject();
  }
  return project;
}
function failIfInvalidPosition(position) {
  Debug.assert(typeof position === "number", `Expected position ${position} to be a number.`);
  Debug.assert(position >= 0, `Expected position to be non-negative.`);
}
function failIfInvalidLocation(location) {
  Debug.assert(typeof location.line === "number", `Expected line ${location.line} to be a number.`);
  Debug.assert(typeof location.offset === "number", `Expected offset ${location.offset} to be a number.`);
  Debug.assert(location.line > 0, `Expected line to be non-${location.line === 0 ? "zero" : "negative"}`);
  Debug.assert(location.offset > 0, `Expected offset to be non-${location.offset === 0 ? "zero" : "negative"}`);
}

// src/server/typingsCache.ts
var nullTypingsInstaller = {
  isKnownTypesPackageName: returnFalse,
  // Should never be called because we never provide a types registry.
  installPackage: notImplemented,
  enqueueInstallTypingsRequest: noop,
  attach: noop,
  onProjectClosed: noop,
  globalTypingsCacheLocation: void 0
  // TODO: GH#18217
};
function setIsEqualTo(arr1, arr2) {
  if (arr1 === arr2) {
    return true;
  }
  if ((arr1 || emptyArray2).length === 0 && (arr2 || emptyArray2).length === 0) {
    return true;
  }
  const set = /* @__PURE__ */ new Map();
  let unique = 0;
  for (const v of arr1) {
    if (set.get(v) !== true) {
      set.set(v, true);
      unique++;
    }
  }
  for (const v of arr2) {
    const isSet = set.get(v);
    if (isSet === void 0) {
      return false;
    }
    if (isSet === true) {
      set.set(v, false);
      unique--;
    }
  }
  return unique === 0;
}
function typeAcquisitionChanged(opt1, opt2) {
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
}
function compilerOptionsChanged(opt1, opt2) {
  return getAllowJSCompilerOption(opt1) !== getAllowJSCompilerOption(opt2);
}
function unresolvedImportsChanged(imports1, imports2) {
  if (imports1 === imports2) {
    return false;
  }
  return !arrayIsEqualTo(imports1, imports2);
}
var TypingsCache = class {
  constructor(installer) {
    this.installer = installer;
    this.perProjectCache = /* @__PURE__ */ new Map();
  }
  isKnownTypesPackageName(name) {
    return this.installer.isKnownTypesPackageName(name);
  }
  installPackage(options) {
    return this.installer.installPackage(options);
  }
  enqueueInstallTypingsForProject(project, unresolvedImports, forceRefresh) {
    const typeAcquisition = project.getTypeAcquisition();
    if (!typeAcquisition || !typeAcquisition.enable) {
      return;
    }
    const entry = this.perProjectCache.get(project.getProjectName());
    if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) {
      this.perProjectCache.set(project.getProjectName(), {
        compilerOptions: project.getCompilationSettings(),
        typeAcquisition,
        typings: entry ? entry.typings : emptyArray2,
        unresolvedImports,
        poisoned: true
      });
      this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
    }
  }
  updateTypingsForProject(projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) {
    const typings = sort(newTypings);
    this.perProjectCache.set(projectName, {
      compilerOptions,
      typeAcquisition,
      typings,
      unresolvedImports,
      poisoned: false
    });
    return !typeAcquisition || !typeAcquisition.enable ? emptyArray2 : typings;
  }
  onProjectClosed(project) {
    this.perProjectCache.delete(project.getProjectName());
    this.installer.onProjectClosed(project);
  }
};

// src/server/project.ts
var ProjectKind = /* @__PURE__ */ ((ProjectKind2) => {
  ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred";
  ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured";
  ProjectKind2[ProjectKind2["External"] = 2] = "External";
  ProjectKind2[ProjectKind2["AutoImportProvider"] = 3] = "AutoImportProvider";
  ProjectKind2[ProjectKind2["Auxiliary"] = 4] = "Auxiliary";
  return ProjectKind2;
})(ProjectKind || {});
function countEachFileTypes(infos, includeSizes = false) {
  const result = {
    js: 0,
    jsSize: 0,
    jsx: 0,
    jsxSize: 0,
    ts: 0,
    tsSize: 0,
    tsx: 0,
    tsxSize: 0,
    dts: 0,
    dtsSize: 0,
    deferred: 0,
    deferredSize: 0
  };
  for (const info of infos) {
    const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0;
    switch (info.scriptKind) {
      case 1 /* JS */:
        result.js += 1;
        result.jsSize += fileSize;
        break;
      case 2 /* JSX */:
        result.jsx += 1;
        result.jsxSize += fileSize;
        break;
      case 3 /* TS */:
        if (isDeclarationFileName(info.fileName)) {
          result.dts += 1;
          result.dtsSize += fileSize;
        } else {
          result.ts += 1;
          result.tsSize += fileSize;
        }
        break;
      case 4 /* TSX */:
        result.tsx += 1;
        result.tsxSize += fileSize;
        break;
      case 7 /* Deferred */:
        result.deferred += 1;
        result.deferredSize += fileSize;
        break;
    }
  }
  return result;
}
function hasOneOrMoreJsAndNoTsFiles(project) {
  const counts2 = countEachFileTypes(project.getScriptInfos());
  return counts2.js > 0 && counts2.ts === 0 && counts2.tsx === 0;
}
function allRootFilesAreJsOrDts(project) {
  const counts2 = countEachFileTypes(project.getRootScriptInfos());
  return counts2.ts === 0 && counts2.tsx === 0;
}
function allFilesAreJsOrDts(project) {
  const counts2 = countEachFileTypes(project.getScriptInfos());
  return counts2.ts === 0 && counts2.tsx === 0;
}
function hasNoTypeScriptSource(fileNames) {
  return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */));
}
function isGeneratedFileWatcher(watch) {
  return watch.generatedFilePath !== void 0;
}
var Project3 = class {
  /** @internal */
  constructor(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) {
    this.projectKind = projectKind;
    this.projectService = projectService;
    this.documentRegistry = documentRegistry;
    this.compilerOptions = compilerOptions;
    this.compileOnSaveEnabled = compileOnSaveEnabled;
    this.watchOptions = watchOptions;
    this.rootFiles = [];
    this.rootFilesMap = /* @__PURE__ */ new Map();
    /** @internal */
    this.plugins = [];
    /**
     * This is map from files to unresolved imports in it
     * Maop does not contain entries for files that do not have unresolved imports
     * This helps in containing the set of files to invalidate
     *
     * @internal
     */
    this.cachedUnresolvedImportsPerFile = /* @__PURE__ */ new Map();
    /** @internal */
    this.hasAddedorRemovedFiles = false;
    /** @internal */
    this.hasAddedOrRemovedSymlinks = false;
    /**
     * Last version that was reported.
     */
    this.lastReportedVersion = 0;
    /**
     * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one)
     * This property is changed in 'updateGraph' based on the set of files in program
     */
    this.projectProgramVersion = 0;
    /**
     * Current version of the project state. It is changed when:
     * - new root file was added/removed
     * - edit happen in some file that is currently included in the project.
     * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project
     */
    this.projectStateVersion = 0;
    this.isInitialLoadPending = returnFalse;
    /** @internal */
    this.dirty = false;
    /** @internal */
    this.typingFiles = emptyArray2;
    /** @internal */
    this.moduleSpecifierCache = createModuleSpecifierCache(this);
    /** @internal */
    this.createHash = maybeBind(this.projectService.host, this.projectService.host.createHash);
    /** @internal */
    this.globalCacheResolutionModuleName = ts_JsTyping_exports.nonRelativeModuleNameForTypingCache;
    this.projectName = projectName;
    this.directoryStructureHost = directoryStructureHost;
    this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory);
    this.getCanonicalFileName = this.projectService.toCanonicalFileName;
    this.cancellationToken = new ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds);
    if (!this.compilerOptions) {
      this.compilerOptions = getDefaultCompilerOptions2();
      this.compilerOptions.allowNonTsExtensions = true;
      this.compilerOptions.allowJs = true;
    } else if (hasExplicitListOfFiles || getAllowJSCompilerOption(this.compilerOptions) || this.projectService.hasDeferredExtension()) {
      this.compilerOptions.allowNonTsExtensions = true;
    }
    switch (projectService.serverMode) {
      case 0 /* Semantic */:
        this.languageServiceEnabled = true;
        break;
      case 1 /* PartialSemantic */:
        this.languageServiceEnabled = true;
        this.compilerOptions.noResolve = true;
        this.compilerOptions.types = [];
        break;
      case 2 /* Syntactic */:
        this.languageServiceEnabled = false;
        this.compilerOptions.noResolve = true;
        this.compilerOptions.types = [];
        break;
      default:
        Debug.assertNever(projectService.serverMode);
    }
    this.setInternalCompilerOptionsForEmittingJsFiles();
    const host = this.projectService.host;
    if (this.projectService.logger.loggingEnabled()) {
      this.trace = (s) => this.writeLog(s);
    } else if (host.trace) {
      this.trace = (s) => host.trace(s);
    }
    this.realpath = maybeBind(host, host.realpath);
    this.resolutionCache = createResolutionCache(
      this,
      this.currentDirectory,
      /*logChangesWhenResolvingModule*/
      true
    );
    this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.serverMode);
    if (lastFileExceededProgramSize) {
      this.disableLanguageService(lastFileExceededProgramSize);
    }
    this.markAsDirty();
    if (projectKind !== 3 /* AutoImportProvider */) {
      this.projectService.pendingEnsureProjectForOpenFiles = true;
    }
  }
  /** @internal */
  getResolvedProjectReferenceToRedirect(_fileName) {
    return void 0;
  }
  isNonTsProject() {
    updateProjectIfDirty(this);
    return allFilesAreJsOrDts(this);
  }
  isJsOnlyProject() {
    updateProjectIfDirty(this);
    return hasOneOrMoreJsAndNoTsFiles(this);
  }
  static resolveModule(moduleName, initialDir, host, log) {
    return Project3.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule;
  }
  /** @internal */
  static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) {
    Debug.assertIsDefined(host.require);
    let errorLogs;
    let resolvedModule;
    for (const initialDir of searchPaths) {
      const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules")));
      log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`);
      const result = host.require(resolvedPath, pluginConfigEntry.name);
      if (!result.error) {
        resolvedModule = result.module;
        break;
      }
      const err = result.error.stack || result.error.message || JSON.stringify(result.error);
      (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`);
    }
    return { pluginConfigEntry, resolvedModule, errorLogs };
  }
  /** @internal */
  static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) {
    Debug.assertIsDefined(host.importPlugin);
    let errorLogs;
    let resolvedModule;
    for (const initialDir of searchPaths) {
      const resolvedPath = combinePaths(initialDir, "node_modules");
      log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`);
      let result;
      try {
        result = await host.importPlugin(resolvedPath, pluginConfigEntry.name);
      } catch (e) {
        result = { module: void 0, error: e };
      }
      if (!result.error) {
        resolvedModule = result.module;
        break;
      }
      const err = result.error.stack || result.error.message || JSON.stringify(result.error);
      (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`);
    }
    return { pluginConfigEntry, resolvedModule, errorLogs };
  }
  isKnownTypesPackageName(name) {
    return this.typingsCache.isKnownTypesPackageName(name);
  }
  installPackage(options) {
    return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) });
  }
  /** @internal */
  getGlobalTypingsCacheLocation() {
    return this.getGlobalCache();
  }
  get typingsCache() {
    return this.projectService.typingsCache;
  }
  /** @internal */
  getSymlinkCache() {
    if (!this.symlinks) {
      this.symlinks = createSymlinkCache(this.getCurrentDirectory(), this.getCanonicalFileName);
    }
    if (this.program && !this.symlinks.hasProcessedResolutions()) {
      this.symlinks.setSymlinksFromResolutions(
        this.program.getSourceFiles(),
        this.program.getAutomaticTypeDirectiveResolutions()
      );
    }
    return this.symlinks;
  }
  // Method of LanguageServiceHost
  getCompilationSettings() {
    return this.compilerOptions;
  }
  // Method to support public API
  getCompilerOptions() {
    return this.getCompilationSettings();
  }
  getNewLine() {
    return this.projectService.host.newLine;
  }
  getProjectVersion() {
    return this.projectStateVersion.toString();
  }
  getProjectReferences() {
    return void 0;
  }
  getScriptFileNames() {
    if (!this.rootFiles) {
      return emptyArray;
    }
    let result;
    this.rootFilesMap.forEach((value) => {
      if (this.languageServiceEnabled || value.info && value.info.isScriptOpen()) {
        (result || (result = [])).push(value.fileName);
      }
    });
    return addRange(result, this.typingFiles) || emptyArray;
  }
  getOrCreateScriptInfoAndAttachToProject(fileName) {
    const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileName, this.currentDirectory, this.directoryStructureHost);
    if (scriptInfo) {
      const existingValue = this.rootFilesMap.get(scriptInfo.path);
      if (existingValue && existingValue.info !== scriptInfo) {
        this.rootFiles.push(scriptInfo);
        existingValue.info = scriptInfo;
      }
      scriptInfo.attachToProject(this);
    }
    return scriptInfo;
  }
  getScriptKind(fileName) {
    const info = this.getOrCreateScriptInfoAndAttachToProject(fileName);
    return info && info.scriptKind;
  }
  getScriptVersion(filename) {
    const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(filename, this.currentDirectory, this.directoryStructureHost);
    return info && info.getLatestVersion();
  }
  getScriptSnapshot(filename) {
    const scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename);
    if (scriptInfo) {
      return scriptInfo.getSnapshot();
    }
  }
  getCancellationToken() {
    return this.cancellationToken;
  }
  getCurrentDirectory() {
    return this.currentDirectory;
  }
  getDefaultLibFileName() {
    const nodeModuleBinDir = getDirectoryPath(normalizePath(this.projectService.getExecutingFilePath()));
    return combinePaths(nodeModuleBinDir, getDefaultLibFileName(this.compilerOptions));
  }
  useCaseSensitiveFileNames() {
    return this.projectService.host.useCaseSensitiveFileNames;
  }
  readDirectory(path, extensions, exclude, include, depth) {
    return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth);
  }
  readFile(fileName) {
    return this.projectService.host.readFile(fileName);
  }
  writeFile(fileName, content) {
    return this.projectService.host.writeFile(fileName, content);
  }
  fileExists(file) {
    const path = this.toPath(file);
    return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file);
  }
  /** @internal */
  resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) {
    return this.resolutionCache.resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames);
  }
  getModuleResolutionCache() {
    return this.resolutionCache.getModuleResolutionCache();
  }
  /** @internal */
  resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) {
    return this.resolutionCache.resolveTypeReferenceDirectiveReferences(
      typeDirectiveReferences,
      containingFile,
      redirectedReference,
      options,
      containingSourceFile,
      reusedNames
    );
  }
  /** @internal */
  resolveLibrary(libraryName, resolveFrom, options, libFileName) {
    return this.resolutionCache.resolveLibrary(libraryName, resolveFrom, options, libFileName);
  }
  directoryExists(path) {
    return this.directoryStructureHost.directoryExists(path);
  }
  getDirectories(path) {
    return this.directoryStructureHost.getDirectories(path);
  }
  /** @internal */
  getCachedDirectoryStructureHost() {
    return void 0;
  }
  /** @internal */
  toPath(fileName) {
    return toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName);
  }
  /** @internal */
  watchDirectoryOfFailedLookupLocation(directory, cb, flags) {
    return this.projectService.watchFactory.watchDirectory(
      directory,
      cb,
      flags,
      this.projectService.getWatchOptions(this),
      WatchType.FailedLookupLocations,
      this
    );
  }
  /** @internal */
  watchAffectingFileLocation(file, cb) {
    return this.projectService.watchFactory.watchFile(
      file,
      cb,
      2e3 /* High */,
      this.projectService.getWatchOptions(this),
      WatchType.AffectingFileLocation,
      this
    );
  }
  /** @internal */
  clearInvalidateResolutionOfFailedLookupTimer() {
    return this.projectService.throttledOperations.cancel(`${this.getProjectName()}FailedLookupInvalidation`);
  }
  /** @internal */
  scheduleInvalidateResolutionsOfFailedLookupLocations() {
    this.projectService.throttledOperations.schedule(
      `${this.getProjectName()}FailedLookupInvalidation`,
      /*delay*/
      1e3,
      () => {
        if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
          this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
        }
      }
    );
  }
  /** @internal */
  invalidateResolutionsOfFailedLookupLocations() {
    if (this.clearInvalidateResolutionOfFailedLookupTimer() && this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
      this.markAsDirty();
      this.projectService.delayEnsureProjectForOpenFiles();
    }
  }
  /** @internal */
  onInvalidatedResolution() {
    this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
  }
  /** @internal */
  watchTypeRootsDirectory(directory, cb, flags) {
    return this.projectService.watchFactory.watchDirectory(
      directory,
      cb,
      flags,
      this.projectService.getWatchOptions(this),
      WatchType.TypeRoots,
      this
    );
  }
  /** @internal */
  hasChangedAutomaticTypeDirectiveNames() {
    return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames();
  }
  /** @internal */
  onChangedAutomaticTypeDirectiveNames() {
    this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
  }
  /** @internal */
  getGlobalCache() {
    return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : void 0;
  }
  /** @internal */
  fileIsOpen(filePath) {
    return this.projectService.openFiles.has(filePath);
  }
  /** @internal */
  writeLog(s) {
    this.projectService.logger.info(s);
  }
  log(s) {
    this.writeLog(s);
  }
  error(s) {
    this.projectService.logger.msg(s, "Err" /* Err */);
  }
  setInternalCompilerOptionsForEmittingJsFiles() {
    if (this.projectKind === 0 /* Inferred */ || this.projectKind === 2 /* External */) {
      this.compilerOptions.noEmitForJsFiles = true;
    }
  }
  /**
   * Get the errors that dont have any file name associated
   */
  getGlobalProjectErrors() {
    return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2;
  }
  /**
   * Get all the project errors
   */
  getAllProjectErrors() {
    return this.projectErrors || emptyArray2;
  }
  setProjectErrors(projectErrors) {
    this.projectErrors = projectErrors;
  }
  getLanguageService(ensureSynchronized = true) {
    if (ensureSynchronized) {
      updateProjectIfDirty(this);
    }
    return this.languageService;
  }
  /** @internal */
  getSourceMapper() {
    return this.getLanguageService().getSourceMapper();
  }
  /** @internal */
  clearSourceMapperCache() {
    this.languageService.clearSourceMapperCache();
  }
  /** @internal */
  getDocumentPositionMapper(generatedFileName, sourceFileName) {
    return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName);
  }
  /** @internal */
  getSourceFileLike(fileName) {
    return this.projectService.getSourceFileLike(fileName, this);
  }
  /** @internal */
  shouldEmitFile(scriptInfo) {
    return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent() && !this.program.isSourceOfProjectReferenceRedirect(scriptInfo.path);
  }
  getCompileOnSaveAffectedFileList(scriptInfo) {
    if (!this.languageServiceEnabled) {
      return [];
    }
    updateProjectIfDirty(this);
    this.builderState = BuilderState.create(
      this.program,
      this.builderState,
      /*disableUseFileVersionAsSignature*/
      true
    );
    return mapDefined(
      BuilderState.getFilesAffectedBy(
        this.builderState,
        this.program,
        scriptInfo.path,
        this.cancellationToken,
        this.projectService.host
      ),
      (sourceFile) => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : void 0
    );
  }
  /**
   * Returns true if emit was conducted
   */
  emitFile(scriptInfo, writeFile2) {
    if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) {
      return { emitSkipped: true, diagnostics: emptyArray2 };
    }
    const { emitSkipped, diagnostics, outputFiles } = this.getLanguageService().getEmitOutput(scriptInfo.fileName);
    if (!emitSkipped) {
      for (const outputFile of outputFiles) {
        const outputFileAbsoluteFileName = getNormalizedAbsolutePath(outputFile.name, this.currentDirectory);
        writeFile2(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark);
      }
      if (this.builderState && getEmitDeclarations(this.compilerOptions)) {
        const dtsFiles = outputFiles.filter((f) => isDeclarationFileName(f.name));
        if (dtsFiles.length === 1) {
          const sourceFile = this.program.getSourceFile(scriptInfo.fileName);
          const signature = this.projectService.host.createHash ? this.projectService.host.createHash(dtsFiles[0].text) : generateDjb2Hash(dtsFiles[0].text);
          BuilderState.updateSignatureOfFile(this.builderState, signature, sourceFile.resolvedPath);
        }
      }
    }
    return { emitSkipped, diagnostics };
  }
  enableLanguageService() {
    if (this.languageServiceEnabled || this.projectService.serverMode === 2 /* Syntactic */) {
      return;
    }
    this.languageServiceEnabled = true;
    this.lastFileExceededProgramSize = void 0;
    this.projectService.onUpdateLanguageServiceStateForProject(
      this,
      /*languageServiceEnabled*/
      true
    );
  }
  disableLanguageService(lastFileExceededProgramSize) {
    if (!this.languageServiceEnabled) {
      return;
    }
    Debug.assert(this.projectService.serverMode !== 2 /* Syntactic */);
    this.languageService.cleanupSemanticCache();
    this.languageServiceEnabled = false;
    this.lastFileExceededProgramSize = lastFileExceededProgramSize;
    this.builderState = void 0;
    if (this.autoImportProviderHost) {
      this.autoImportProviderHost.close();
    }
    this.autoImportProviderHost = void 0;
    this.resolutionCache.closeTypeRootsWatch();
    this.clearGeneratedFileWatch();
    this.projectService.onUpdateLanguageServiceStateForProject(
      this,
      /*languageServiceEnabled*/
      false
    );
  }
  getProjectName() {
    return this.projectName;
  }
  removeLocalTypingsFromTypeAcquisition(newTypeAcquisition) {
    if (!newTypeAcquisition || !newTypeAcquisition.include) {
      return newTypeAcquisition;
    }
    return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) };
  }
  getExternalFiles() {
    return sort(flatMap(this.plugins, (plugin) => {
      if (typeof plugin.module.getExternalFiles !== "function")
        return;
      try {
        return plugin.module.getExternalFiles(this);
      } catch (e) {
        this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`);
        if (e.stack) {
          this.projectService.logger.info(e.stack);
        }
      }
    }));
  }
  getSourceFile(path) {
    if (!this.program) {
      return void 0;
    }
    return this.program.getSourceFileByPath(path);
  }
  /** @internal */
  getSourceFileOrConfigFile(path) {
    const options = this.program.getCompilerOptions();
    return path === options.configFilePath ? options.configFile : this.getSourceFile(path);
  }
  close() {
    this.projectService.typingsCache.onProjectClosed(this);
    this.closeWatchingTypingLocations();
    if (this.program) {
      for (const f of this.program.getSourceFiles()) {
        this.detachScriptInfoIfNotRoot(f.fileName);
      }
      this.program.forEachResolvedProjectReference((ref) => this.detachScriptInfoFromProject(ref.sourceFile.fileName));
    }
    forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile));
    for (const root of this.rootFiles) {
      root.detachFromProject(this);
    }
    this.projectService.pendingEnsureProjectForOpenFiles = true;
    this.rootFiles = void 0;
    this.rootFilesMap = void 0;
    this.externalFiles = void 0;
    this.program = void 0;
    this.builderState = void 0;
    this.resolutionCache.clear();
    this.resolutionCache = void 0;
    this.cachedUnresolvedImportsPerFile = void 0;
    this.moduleSpecifierCache = void 0;
    this.directoryStructureHost = void 0;
    this.exportMapCache = void 0;
    this.projectErrors = void 0;
    this.plugins.length = 0;
    if (this.missingFilesMap) {
      clearMap(this.missingFilesMap, closeFileWatcher);
      this.missingFilesMap = void 0;
    }
    this.clearGeneratedFileWatch();
    this.clearInvalidateResolutionOfFailedLookupTimer();
    if (this.autoImportProviderHost) {
      this.autoImportProviderHost.close();
    }
    this.autoImportProviderHost = void 0;
    if (this.noDtsResolutionProject) {
      this.noDtsResolutionProject.close();
    }
    this.noDtsResolutionProject = void 0;
    this.languageService.dispose();
    this.languageService = void 0;
  }
  detachScriptInfoIfNotRoot(uncheckedFilename) {
    const info = this.projectService.getScriptInfo(uncheckedFilename);
    if (info && !this.isRoot(info)) {
      info.detachFromProject(this);
    }
  }
  isClosed() {
    return this.rootFiles === void 0;
  }
  hasRoots() {
    return this.rootFiles && this.rootFiles.length > 0;
  }
  /** @internal */
  isOrphan() {
    return false;
  }
  getRootFiles() {
    return this.rootFiles && this.rootFiles.map((info) => info.fileName);
  }
  /** @internal */
  getRootFilesMap() {
    return this.rootFilesMap;
  }
  getRootScriptInfos() {
    return this.rootFiles;
  }
  getScriptInfos() {
    if (!this.languageServiceEnabled) {
      return this.rootFiles;
    }
    return map(this.program.getSourceFiles(), (sourceFile) => {
      const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath);
      Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`);
      return scriptInfo;
    });
  }
  getExcludedFiles() {
    return emptyArray2;
  }
  getFileNames(excludeFilesFromExternalLibraries, excludeConfigFiles) {
    if (!this.program) {
      return [];
    }
    if (!this.languageServiceEnabled) {
      let rootFiles = this.getRootFiles();
      if (this.compilerOptions) {
        const defaultLibrary = getDefaultLibFilePath(this.compilerOptions);
        if (defaultLibrary) {
          (rootFiles || (rootFiles = [])).push(asNormalizedPath(defaultLibrary));
        }
      }
      return rootFiles;
    }
    const result = [];
    for (const f of this.program.getSourceFiles()) {
      if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) {
        continue;
      }
      result.push(asNormalizedPath(f.fileName));
    }
    if (!excludeConfigFiles) {
      const configFile = this.program.getCompilerOptions().configFile;
      if (configFile) {
        result.push(asNormalizedPath(configFile.fileName));
        if (configFile.extendedSourceFiles) {
          for (const f of configFile.extendedSourceFiles) {
            result.push(asNormalizedPath(f));
          }
        }
      }
    }
    return result;
  }
  /** @internal */
  getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo) {
    return this.getFileNames().map((fileName) => ({
      fileName,
      isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName)
    }));
  }
  hasConfigFile(configFilePath) {
    if (this.program && this.languageServiceEnabled) {
      const configFile = this.program.getCompilerOptions().configFile;
      if (configFile) {
        if (configFilePath === asNormalizedPath(configFile.fileName)) {
          return true;
        }
        if (configFile.extendedSourceFiles) {
          for (const f of configFile.extendedSourceFiles) {
            if (configFilePath === asNormalizedPath(f)) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
  containsScriptInfo(info) {
    if (this.isRoot(info))
      return true;
    if (!this.program)
      return false;
    const file = this.program.getSourceFileByPath(info.path);
    return !!file && file.resolvedPath === info.path;
  }
  containsFile(filename, requireOpen) {
    const info = this.projectService.getScriptInfoForNormalizedPath(filename);
    if (info && (info.isScriptOpen() || !requireOpen)) {
      return this.containsScriptInfo(info);
    }
    return false;
  }
  isRoot(info) {
    var _a;
    return this.rootFilesMap && ((_a = this.rootFilesMap.get(info.path)) == null ? void 0 : _a.info) === info;
  }
  // add a root file to project
  addRoot(info, fileName) {
    Debug.assert(!this.isRoot(info));
    this.rootFiles.push(info);
    this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info });
    info.attachToProject(this);
    this.markAsDirty();
  }
  // add a root file that doesnt exist on host
  addMissingFileRoot(fileName) {
    const path = this.projectService.toPath(fileName);
    this.rootFilesMap.set(path, { fileName });
    this.markAsDirty();
  }
  removeFile(info, fileExists, detachFromProject) {
    if (this.isRoot(info)) {
      this.removeRoot(info);
    }
    if (fileExists) {
      this.resolutionCache.removeResolutionsOfFile(info.path);
    } else {
      this.resolutionCache.invalidateResolutionOfFile(info.path);
    }
    this.cachedUnresolvedImportsPerFile.delete(info.path);
    if (detachFromProject) {
      info.detachFromProject(this);
    }
    this.markAsDirty();
  }
  registerFileUpdate(fileName) {
    (this.updatedFileNames || (this.updatedFileNames = /* @__PURE__ */ new Set())).add(fileName);
  }
  /** @internal */
  markFileAsDirty(changedFile) {
    this.markAsDirty();
    if (this.exportMapCache && !this.exportMapCache.isEmpty()) {
      (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = /* @__PURE__ */ new Set())).add(changedFile);
    }
  }
  markAsDirty() {
    if (!this.dirty) {
      this.projectStateVersion++;
      this.dirty = true;
    }
  }
  /** @internal */
  onAutoImportProviderSettingsChanged() {
    var _a;
    if (this.autoImportProviderHost === false) {
      this.autoImportProviderHost = void 0;
    } else {
      (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty();
    }
  }
  /** @internal */
  onPackageJsonChange(packageJsonPath) {
    var _a;
    if ((_a = this.packageJsonsForAutoImport) == null ? void 0 : _a.has(packageJsonPath)) {
      this.moduleSpecifierCache.clear();
      if (this.autoImportProviderHost) {
        this.autoImportProviderHost.markAsDirty();
      }
    }
  }
  /** @internal */
  onFileAddedOrRemoved(isSymlink) {
    this.hasAddedorRemovedFiles = true;
    if (isSymlink) {
      this.hasAddedOrRemovedSymlinks = true;
    }
  }
  /** @internal */
  onDiscoveredSymlink() {
    this.hasAddedOrRemovedSymlinks = true;
  }
  /**
   * Updates set of files that contribute to this project
   * @returns: true if set of files in the project stays the same and false - otherwise.
   */
  updateGraph() {
    var _a, _b, _c, _d, _e;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] });
    (_b = perfLogger) == null ? void 0 : _b.logStartUpdateGraph();
    this.resolutionCache.startRecordingFilesWithChangedResolutions();
    const hasNewProgram = this.updateGraphWorker();
    const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles;
    this.hasAddedorRemovedFiles = false;
    this.hasAddedOrRemovedSymlinks = false;
    const changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray2;
    for (const file of changedFiles) {
      this.cachedUnresolvedImportsPerFile.delete(file);
    }
    if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) {
      if (hasNewProgram || changedFiles.length) {
        this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile);
      }
      this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles);
    } else {
      this.lastCachedUnresolvedImportsList = void 0;
    }
    const isFirstProgramLoad = this.projectProgramVersion === 0 && hasNewProgram;
    if (hasNewProgram) {
      this.projectProgramVersion++;
    }
    if (hasAddedorRemovedFiles) {
      if (!this.autoImportProviderHost)
        this.autoImportProviderHost = void 0;
      (_c = this.autoImportProviderHost) == null ? void 0 : _c.markAsDirty();
    }
    if (isFirstProgramLoad) {
      this.getPackageJsonAutoImportProvider();
    }
    (_d = perfLogger) == null ? void 0 : _d.logStopUpdateGraph();
    (_e = tracing) == null ? void 0 : _e.pop();
    return !hasNewProgram;
  }
  /** @internal */
  updateTypingFiles(typingFiles) {
    if (enumerateInsertsAndDeletes(
      typingFiles,
      this.typingFiles,
      getStringComparer(!this.useCaseSensitiveFileNames()),
      /*inserted*/
      noop,
      (removed) => this.detachScriptInfoFromProject(removed)
    )) {
      this.typingFiles = typingFiles;
      this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile);
      this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
    }
  }
  /** @internal */
  closeWatchingTypingLocations() {
    if (this.typingWatchers)
      clearMap(this.typingWatchers, closeFileWatcher);
    this.typingWatchers = void 0;
  }
  /** @internal */
  onTypingInstallerWatchInvoke() {
    this.typingWatchers.isInvoked = true;
    this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate });
  }
  /** @internal */
  watchTypingLocations(files) {
    if (!files) {
      this.typingWatchers.isInvoked = false;
      return;
    }
    if (!files.length) {
      this.closeWatchingTypingLocations();
      return;
    }
    const toRemove = new Map(this.typingWatchers);
    if (!this.typingWatchers)
      this.typingWatchers = /* @__PURE__ */ new Map();
    this.typingWatchers.isInvoked = false;
    const createProjectWatcher = (path, typingsWatcherType) => {
      const canonicalPath = this.toPath(path);
      toRemove.delete(canonicalPath);
      if (!this.typingWatchers.has(canonicalPath)) {
        this.typingWatchers.set(
          canonicalPath,
          typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile(
            path,
            () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`),
            2e3 /* High */,
            this.projectService.getWatchOptions(this),
            WatchType.TypingInstallerLocationFile,
            this
          ) : this.projectService.watchFactory.watchDirectory(
            path,
            (f) => {
              if (this.typingWatchers.isInvoked)
                return this.writeLog(`TypingWatchers already invoked`);
              if (!fileExtensionIs(f, ".json" /* Json */))
                return this.writeLog(`Ignoring files that are not *.json`);
              if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation, "package.json"), !this.useCaseSensitiveFileNames()))
                return this.writeLog(`Ignoring package.json change at global typings location`);
              this.onTypingInstallerWatchInvoke();
            },
            1 /* Recursive */,
            this.projectService.getWatchOptions(this),
            WatchType.TypingInstallerLocationDirectory,
            this
          )
        );
      }
    };
    for (const file of files) {
      const basename = getBaseFileName(file);
      if (basename === "package.json" || basename === "bower.json") {
        createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
        continue;
      }
      if (containsPath(this.currentDirectory, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) {
        const subDirectory = file.indexOf(directorySeparator, this.currentDirectory.length + 1);
        if (subDirectory !== -1) {
          createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
        } else {
          createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
        }
        continue;
      }
      if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) {
        createProjectWatcher(this.projectService.typingsInstaller.globalTypingsCacheLocation, "DirectoryWatcher" /* DirectoryWatcher */);
        continue;
      }
      createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
    }
    toRemove.forEach((watch, path) => {
      watch.close();
      this.typingWatchers.delete(path);
    });
  }
  /** @internal */
  getCurrentProgram() {
    return this.program;
  }
  removeExistingTypings(include) {
    const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost);
    return include.filter((i) => existing.indexOf(i) < 0);
  }
  updateGraphWorker() {
    var _a, _b;
    const oldProgram = this.languageService.getCurrentProgram();
    Debug.assert(!this.isClosed(), "Called update graph worker of closed project");
    this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`);
    const start2 = timestamp();
    const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse);
    this.hasInvalidatedResolutions = hasInvalidatedResolutions;
    this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions;
    this.resolutionCache.startCachingPerDirectoryResolution();
    this.program = this.languageService.getProgram();
    this.dirty = false;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "finishCachingPerDirectoryResolution");
    this.resolutionCache.finishCachingPerDirectoryResolution(this.program, oldProgram);
    (_b = tracing) == null ? void 0 : _b.pop();
    Debug.assert(oldProgram === void 0 || this.program !== void 0);
    let hasNewProgram = false;
    if (this.program && (!oldProgram || this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */)) {
      hasNewProgram = true;
      if (oldProgram) {
        for (const f of oldProgram.getSourceFiles()) {
          const newFile = this.program.getSourceFileByPath(f.resolvedPath);
          if (!newFile || f.resolvedPath === f.path && newFile.resolvedPath !== f.path) {
            this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path));
          }
        }
        oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => {
          if (!this.program.getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) {
            this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName);
          }
        });
      }
      updateMissingFilePathsWatch(
        this.program,
        this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */ new Map()),
        // Watch the missing files
        (missingFilePath) => this.addMissingFileWatcher(missingFilePath)
      );
      if (this.generatedFilesMap) {
        const outPath = outFile(this.compilerOptions);
        if (isGeneratedFileWatcher(this.generatedFilesMap)) {
          if (!outPath || !this.isValidGeneratedFileWatcher(
            removeFileExtension(outPath) + ".d.ts" /* Dts */,
            this.generatedFilesMap
          )) {
            this.clearGeneratedFileWatch();
          }
        } else {
          if (outPath) {
            this.clearGeneratedFileWatch();
          } else {
            this.generatedFilesMap.forEach((watcher, source) => {
              const sourceFile = this.program.getSourceFileByPath(source);
              if (!sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher(
                getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.currentDirectory, this.program.getCommonSourceDirectory(), this.getCanonicalFileName),
                watcher
              )) {
                closeFileWatcherOf(watcher);
                this.generatedFilesMap.delete(source);
              }
            });
          }
        }
      }
      if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) {
        this.resolutionCache.updateTypeRootsWatch();
      }
    }
    if (this.exportMapCache && !this.exportMapCache.isEmpty()) {
      this.exportMapCache.releaseSymbols();
      if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) {
        this.exportMapCache.clear();
      } else if (this.changedFilesForExportMapCache && oldProgram && this.program) {
        forEachKey(this.changedFilesForExportMapCache, (fileName) => {
          const oldSourceFile = oldProgram.getSourceFileByPath(fileName);
          const sourceFile = this.program.getSourceFileByPath(fileName);
          if (!oldSourceFile || !sourceFile) {
            this.exportMapCache.clear();
            return true;
          }
          return this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!this.getTypeAcquisition().enable);
        });
      }
    }
    if (this.changedFilesForExportMapCache) {
      this.changedFilesForExportMapCache.clear();
    }
    if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) {
      this.symlinks = void 0;
      this.moduleSpecifierCache.clear();
    }
    const oldExternalFiles = this.externalFiles || emptyArray2;
    this.externalFiles = this.getExternalFiles();
    enumerateInsertsAndDeletes(
      this.externalFiles,
      oldExternalFiles,
      getStringComparer(!this.useCaseSensitiveFileNames()),
      // Ensure a ScriptInfo is created for new external files. This is performed indirectly
      // by the host for files in the program when the program is retrieved above but
      // the program doesn't contain external files so this must be done explicitly.
      (inserted) => {
        const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, this.currentDirectory, this.directoryStructureHost);
        scriptInfo == null ? void 0 : scriptInfo.attachToProject(this);
      },
      (removed) => this.detachScriptInfoFromProject(removed)
    );
    const elapsed = timestamp() - start2;
    this.sendPerformanceEvent("UpdateGraph", elapsed);
    this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} Version: ${this.getProjectVersion()} structureChanged: ${hasNewProgram}${this.program ? ` structureIsReused:: ${StructureIsReused[this.program.structureIsReused]}` : ""} Elapsed: ${elapsed}ms`);
    if (this.projectService.logger.isTestLogger) {
      if (this.program !== oldProgram) {
        this.print(
          /*writeProjectFileNames*/
          true,
          this.hasAddedorRemovedFiles,
          /*writeFileVersionAndText*/
          true
        );
      } else {
        this.writeLog(`Same program as before`);
      }
    } else if (this.hasAddedorRemovedFiles) {
      this.print(
        /*writeProjectFileNames*/
        true,
        /*writeFileExplaination*/
        true,
        /*writeFileVersionAndText*/
        false
      );
    } else if (this.program !== oldProgram) {
      this.writeLog(`Different program with same set of files`);
    }
    return hasNewProgram;
  }
  /** @internal */
  sendPerformanceEvent(kind, durationMs) {
    this.projectService.sendPerformanceEvent(kind, durationMs);
  }
  detachScriptInfoFromProject(uncheckedFileName, noRemoveResolution) {
    const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName);
    if (scriptInfoToDetach) {
      scriptInfoToDetach.detachFromProject(this);
      if (!noRemoveResolution) {
        this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path);
      }
    }
  }
  addMissingFileWatcher(missingFilePath) {
    var _a;
    if (isConfiguredProject(this)) {
      const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath);
      if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(this.canonicalConfigFilePath))
        return noopFileWatcher;
    }
    const fileWatcher = this.projectService.watchFactory.watchFile(
      missingFilePath,
      (fileName, eventKind) => {
        if (isConfiguredProject(this)) {
          this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind);
        }
        if (eventKind === 0 /* Created */ && this.missingFilesMap.has(missingFilePath)) {
          this.missingFilesMap.delete(missingFilePath);
          fileWatcher.close();
          this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
        }
      },
      500 /* Medium */,
      this.projectService.getWatchOptions(this),
      WatchType.MissingFile,
      this
    );
    return fileWatcher;
  }
  isWatchedMissingFile(path) {
    return !!this.missingFilesMap && this.missingFilesMap.has(path);
  }
  /** @internal */
  addGeneratedFileWatch(generatedFile, sourceFile) {
    if (outFile(this.compilerOptions)) {
      if (!this.generatedFilesMap) {
        this.generatedFilesMap = this.createGeneratedFileWatcher(generatedFile);
      }
    } else {
      const path = this.toPath(sourceFile);
      if (this.generatedFilesMap) {
        if (isGeneratedFileWatcher(this.generatedFilesMap)) {
          Debug.fail(`${this.projectName} Expected to not have --out watcher for generated file with options: ${JSON.stringify(this.compilerOptions)}`);
          return;
        }
        if (this.generatedFilesMap.has(path))
          return;
      } else {
        this.generatedFilesMap = /* @__PURE__ */ new Map();
      }
      this.generatedFilesMap.set(path, this.createGeneratedFileWatcher(generatedFile));
    }
  }
  createGeneratedFileWatcher(generatedFile) {
    return {
      generatedFilePath: this.toPath(generatedFile),
      watcher: this.projectService.watchFactory.watchFile(
        generatedFile,
        () => {
          this.clearSourceMapperCache();
          this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
        },
        2e3 /* High */,
        this.projectService.getWatchOptions(this),
        WatchType.MissingGeneratedFile,
        this
      )
    };
  }
  isValidGeneratedFileWatcher(generateFile, watcher) {
    return this.toPath(generateFile) === watcher.generatedFilePath;
  }
  clearGeneratedFileWatch() {
    if (this.generatedFilesMap) {
      if (isGeneratedFileWatcher(this.generatedFilesMap)) {
        closeFileWatcherOf(this.generatedFilesMap);
      } else {
        clearMap(this.generatedFilesMap, closeFileWatcherOf);
      }
      this.generatedFilesMap = void 0;
    }
  }
  getScriptInfoForNormalizedPath(fileName) {
    const scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName));
    if (scriptInfo && !scriptInfo.isAttached(this)) {
      return Errors.ThrowProjectDoesNotContainDocument(fileName, this);
    }
    return scriptInfo;
  }
  getScriptInfo(uncheckedFileName) {
    return this.projectService.getScriptInfo(uncheckedFileName);
  }
  filesToString(writeProjectFileNames) {
    return this.filesToStringWorker(
      writeProjectFileNames,
      /*writeFileExplaination*/
      true,
      /*writeFileVersionAndText*/
      false
    );
  }
  /** @internal */
  filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) {
    if (this.isInitialLoadPending())
      return "	Files (0) InitialLoadPending\n";
    if (!this.program)
      return "	Files (0) NoProgram\n";
    const sourceFiles = this.program.getSourceFiles();
    let strBuilder = `	Files (${sourceFiles.length})
`;
    if (writeProjectFileNames) {
      for (const file of sourceFiles) {
        strBuilder += `	${file.fileName}${writeFileVersionAndText ? ` ${file.version} ${JSON.stringify(file.text)}` : ""}
`;
      }
      if (writeFileExplaination) {
        strBuilder += "\n\n";
        explainFiles(this.program, (s) => strBuilder += `	${s}
`);
      }
    }
    return strBuilder;
  }
  /** @internal */
  print(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) {
    this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`);
    this.writeLog(this.filesToStringWorker(
      writeProjectFileNames && this.projectService.logger.hasLevel(3 /* verbose */),
      writeFileExplaination && this.projectService.logger.hasLevel(3 /* verbose */),
      writeFileVersionAndText && this.projectService.logger.hasLevel(3 /* verbose */)
    ));
    this.writeLog("-----------------------------------------------");
    if (this.autoImportProviderHost) {
      this.autoImportProviderHost.print(
        /*writeProjectFileNames*/
        false,
        /*writeFileExplaination*/
        false,
        /*writeFileVersionAndText*/
        false
      );
    }
  }
  setCompilerOptions(compilerOptions) {
    var _a;
    if (compilerOptions) {
      compilerOptions.allowNonTsExtensions = true;
      const oldOptions = this.compilerOptions;
      this.compilerOptions = compilerOptions;
      this.setInternalCompilerOptionsForEmittingJsFiles();
      (_a = this.noDtsResolutionProject) == null ? void 0 : _a.setCompilerOptions(this.getCompilerOptionsForNoDtsResolutionProject());
      if (changesAffectModuleResolution(oldOptions, compilerOptions)) {
        this.cachedUnresolvedImportsPerFile.clear();
        this.lastCachedUnresolvedImportsList = void 0;
        this.resolutionCache.onChangesAffectModuleResolution();
        this.moduleSpecifierCache.clear();
      }
      this.markAsDirty();
    }
  }
  /** @internal */
  setWatchOptions(watchOptions) {
    this.watchOptions = watchOptions;
  }
  /** @internal */
  getWatchOptions() {
    return this.watchOptions;
  }
  setTypeAcquisition(newTypeAcquisition) {
    if (newTypeAcquisition) {
      this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition);
    }
  }
  getTypeAcquisition() {
    return this.typeAcquisition || {};
  }
  /** @internal */
  getChangesSinceVersion(lastKnownVersion, includeProjectReferenceRedirectInfo) {
    const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo ? (files) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]) => ({
      fileName,
      isSourceOfProjectReferenceRedirect
    })) : (files) => arrayFrom(files.keys());
    if (!this.isInitialLoadPending()) {
      updateProjectIfDirty(this);
    }
    const info = {
      projectName: this.getProjectName(),
      version: this.projectProgramVersion,
      isInferred: isInferredProject(this),
      options: this.getCompilationSettings(),
      languageServiceDisabled: !this.languageServiceEnabled,
      lastFileExceededProgramSize: this.lastFileExceededProgramSize
    };
    const updatedFileNames = this.updatedFileNames;
    this.updatedFileNames = void 0;
    if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
      if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) {
        return { info, projectErrors: this.getGlobalProjectErrors() };
      }
      const lastReportedFileNames = this.lastReportedFileNames;
      const externalFiles = this.getExternalFiles().map((f) => ({
        fileName: toNormalizedPath(f),
        isSourceOfProjectReferenceRedirect: false
      }));
      const currentFiles = arrayToMap(
        this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles),
        (info2) => info2.fileName,
        (info2) => info2.isSourceOfProjectReferenceRedirect
      );
      const added = /* @__PURE__ */ new Map();
      const removed = /* @__PURE__ */ new Map();
      const updated = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : [];
      const updatedRedirects = [];
      forEachEntry(currentFiles, (isSourceOfProjectReferenceRedirect, fileName) => {
        if (!lastReportedFileNames.has(fileName)) {
          added.set(fileName, isSourceOfProjectReferenceRedirect);
        } else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)) {
          updatedRedirects.push({
            fileName,
            isSourceOfProjectReferenceRedirect
          });
        }
      });
      forEachEntry(lastReportedFileNames, (isSourceOfProjectReferenceRedirect, fileName) => {
        if (!currentFiles.has(fileName)) {
          removed.set(fileName, isSourceOfProjectReferenceRedirect);
        }
      });
      this.lastReportedFileNames = currentFiles;
      this.lastReportedVersion = this.projectProgramVersion;
      return {
        info,
        changes: {
          added: includeProjectReferenceRedirectInfoIfRequested(added),
          removed: includeProjectReferenceRedirectInfoIfRequested(removed),
          updated: includeProjectReferenceRedirectInfo ? updated.map((fileName) => ({
            fileName,
            isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName)
          })) : updated,
          updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects : void 0
        },
        projectErrors: this.getGlobalProjectErrors()
      };
    } else {
      const projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo);
      const externalFiles = this.getExternalFiles().map((f) => ({
        fileName: toNormalizedPath(f),
        isSourceOfProjectReferenceRedirect: false
      }));
      const allFiles = projectFileNames.concat(externalFiles);
      this.lastReportedFileNames = arrayToMap(
        allFiles,
        (info2) => info2.fileName,
        (info2) => info2.isSourceOfProjectReferenceRedirect
      );
      this.lastReportedVersion = this.projectProgramVersion;
      return {
        info,
        files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map((f) => f.fileName),
        projectErrors: this.getGlobalProjectErrors()
      };
    }
  }
  // remove a root file from project
  removeRoot(info) {
    orderedRemoveItem(this.rootFiles, info);
    this.rootFilesMap.delete(info.path);
  }
  /** @internal */
  isSourceOfProjectReferenceRedirect(fileName) {
    return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName);
  }
  /** @internal */
  getGlobalPluginSearchPaths() {
    return [
      ...this.projectService.pluginProbeLocations,
      // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
      combinePaths(this.projectService.getExecutingFilePath(), "../../..")
    ];
  }
  enableGlobalPlugins(options) {
    if (!this.projectService.globalPlugins.length)
      return;
    const host = this.projectService.host;
    if (!host.require && !host.importPlugin) {
      this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
      return;
    }
    const searchPaths = this.getGlobalPluginSearchPaths();
    for (const globalPluginName of this.projectService.globalPlugins) {
      if (!globalPluginName)
        continue;
      if (options.plugins && options.plugins.some((p) => p.name === globalPluginName))
        continue;
      this.projectService.logger.info(`Loading global plugin ${globalPluginName}`);
      this.enablePlugin({ name: globalPluginName, global: true }, searchPaths);
    }
  }
  enablePlugin(pluginConfigEntry, searchPaths) {
    this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths);
  }
  /** @internal */
  enableProxy(pluginModuleFactory, configEntry) {
    try {
      if (typeof pluginModuleFactory !== "function") {
        this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did not expose a proper factory function`);
        return;
      }
      const info = {
        config: configEntry,
        project: this,
        languageService: this.languageService,
        languageServiceHost: this,
        serverHost: this.projectService.host,
        session: this.projectService.session
      };
      const pluginModule = pluginModuleFactory({ typescript: ts_exports2 });
      const newLS = pluginModule.create(info);
      for (const k of Object.keys(this.languageService)) {
        if (!(k in newLS)) {
          this.projectService.logger.info(`Plugin activation warning: Missing proxied method ${k} in created LS. Patching.`);
          newLS[k] = this.languageService[k];
        }
      }
      this.projectService.logger.info(`Plugin validation succeeded`);
      this.languageService = newLS;
      this.plugins.push({ name: configEntry.name, module: pluginModule });
    } catch (e) {
      this.projectService.logger.info(`Plugin activation failed: ${e}`);
    }
  }
  /** @internal */
  onPluginConfigurationChanged(pluginName, configuration) {
    this.plugins.filter((plugin) => plugin.name === pluginName).forEach((plugin) => {
      if (plugin.module.onConfigurationChanged) {
        plugin.module.onConfigurationChanged(configuration);
      }
    });
  }
  /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
  refreshDiagnostics() {
    this.projectService.sendProjectsUpdatedInBackgroundEvent();
  }
  /** @internal */
  getPackageJsonsVisibleToFile(fileName, rootDir) {
    if (this.projectService.serverMode !== 0 /* Semantic */)
      return emptyArray2;
    return this.projectService.getPackageJsonsVisibleToFile(fileName, rootDir);
  }
  /** @internal */
  getNearestAncestorDirectoryWithPackageJson(fileName) {
    return this.projectService.getNearestAncestorDirectoryWithPackageJson(fileName);
  }
  /** @internal */
  getPackageJsonsForAutoImport(rootDir) {
    const packageJsons = this.getPackageJsonsVisibleToFile(combinePaths(this.currentDirectory, inferredTypesContainingFile), rootDir);
    this.packageJsonsForAutoImport = new Set(packageJsons.map((p) => p.fileName));
    return packageJsons;
  }
  /** @internal */
  getPackageJsonCache() {
    return this.projectService.packageJsonCache;
  }
  /** @internal */
  getCachedExportInfoMap() {
    return this.exportMapCache || (this.exportMapCache = createCacheableExportInfoMap(this));
  }
  /** @internal */
  clearCachedExportInfoMap() {
    var _a;
    (_a = this.exportMapCache) == null ? void 0 : _a.clear();
  }
  /** @internal */
  getModuleSpecifierCache() {
    return this.moduleSpecifierCache;
  }
  /** @internal */
  includePackageJsonAutoImports() {
    if (this.projectService.includePackageJsonAutoImports() === 0 /* Off */ || !this.languageServiceEnabled || isInsideNodeModules(this.currentDirectory) || !this.isDefaultProjectForOpenFiles()) {
      return 0 /* Off */;
    }
    return this.projectService.includePackageJsonAutoImports();
  }
  /** @internal */
  getModuleResolutionHostForAutoImportProvider() {
    var _a, _b;
    if (this.program) {
      return {
        fileExists: this.program.fileExists,
        directoryExists: this.program.directoryExists,
        realpath: this.program.realpath || ((_a = this.projectService.host.realpath) == null ? void 0 : _a.bind(this.projectService.host)),
        getCurrentDirectory: this.getCurrentDirectory.bind(this),
        readFile: this.projectService.host.readFile.bind(this.projectService.host),
        getDirectories: this.projectService.host.getDirectories.bind(this.projectService.host),
        trace: (_b = this.projectService.host.trace) == null ? void 0 : _b.bind(this.projectService.host),
        useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames()
      };
    }
    return this.projectService.host;
  }
  /** @internal */
  getPackageJsonAutoImportProvider() {
    var _a, _b, _c;
    if (this.autoImportProviderHost === false) {
      return void 0;
    }
    if (this.projectService.serverMode !== 0 /* Semantic */) {
      this.autoImportProviderHost = false;
      return void 0;
    }
    if (this.autoImportProviderHost) {
      updateProjectIfDirty(this.autoImportProviderHost);
      if (this.autoImportProviderHost.isEmpty()) {
        this.autoImportProviderHost.close();
        this.autoImportProviderHost = void 0;
        return void 0;
      }
      return this.autoImportProviderHost.getCurrentProgram();
    }
    const dependencySelection = this.includePackageJsonAutoImports();
    if (dependencySelection) {
      (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider");
      const start2 = timestamp();
      this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getModuleResolutionHostForAutoImportProvider(), this.documentRegistry);
      if (this.autoImportProviderHost) {
        updateProjectIfDirty(this.autoImportProviderHost);
        this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start2);
        (_b = tracing) == null ? void 0 : _b.pop();
        return this.autoImportProviderHost.getCurrentProgram();
      }
      (_c = tracing) == null ? void 0 : _c.pop();
    }
  }
  /** @internal */
  isDefaultProjectForOpenFiles() {
    return !!forEachEntry(
      this.projectService.openFiles,
      (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this
    );
  }
  /** @internal */
  watchNodeModulesForPackageJsonChanges(directoryPath) {
    return this.projectService.watchPackageJsonsInNodeModules(this.toPath(directoryPath), this);
  }
  /** @internal */
  getIncompleteCompletionsCache() {
    return this.projectService.getIncompleteCompletionsCache();
  }
  /** @internal */
  getNoDtsResolutionProject(rootFileNames) {
    Debug.assert(this.projectService.serverMode === 0 /* Semantic */);
    if (!this.noDtsResolutionProject) {
      this.noDtsResolutionProject = new AuxiliaryProject(this.projectService, this.documentRegistry, this.getCompilerOptionsForNoDtsResolutionProject(), this.currentDirectory);
    }
    enumerateInsertsAndDeletes(
      rootFileNames.map(toNormalizedPath),
      this.noDtsResolutionProject.getRootFiles(),
      getStringComparer(!this.useCaseSensitiveFileNames()),
      (pathToAdd) => {
        const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(
          pathToAdd,
          this.currentDirectory,
          this.noDtsResolutionProject.directoryStructureHost
        );
        if (info) {
          this.noDtsResolutionProject.addRoot(info, pathToAdd);
        }
      },
      (pathToRemove) => {
        const info = this.noDtsResolutionProject.getScriptInfo(pathToRemove);
        if (info) {
          this.noDtsResolutionProject.removeRoot(info);
        }
      }
    );
    return this.noDtsResolutionProject;
  }
  /** @internal */
  getCompilerOptionsForNoDtsResolutionProject() {
    return {
      ...this.getCompilerOptions(),
      noDtsResolution: true,
      allowJs: true,
      maxNodeModuleJsDepth: 3,
      diagnostics: false,
      skipLibCheck: true,
      sourceMap: false,
      types: emptyArray,
      lib: emptyArray,
      noLib: true
    };
  }
};
function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) {
  var _a, _b;
  const sourceFiles = program.getSourceFiles();
  (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length });
  const ambientModules = program.getTypeChecker().getAmbientModules().map((mod) => stripQuotes(mod.getName()));
  const result = sortAndDeduplicate(flatMap(sourceFiles, (sourceFile) => extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile)));
  (_b = tracing) == null ? void 0 : _b.pop();
  return result;
}
function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnresolvedImportsPerFile) {
  return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => {
    if (!file.resolvedModules)
      return emptyArray2;
    let unresolvedImports;
    file.resolvedModules.forEach(({ resolvedModule }, name) => {
      if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && !ambientModules.some((m) => m === name)) {
        unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName);
      }
    });
    return unresolvedImports || emptyArray2;
  });
}
var InferredProject2 = class extends Project3 {
  /** @internal */
  constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) {
    super(
      projectService.newInferredProjectName(),
      0 /* Inferred */,
      projectService,
      documentRegistry,
      // TODO: GH#18217
      /*files*/
      void 0,
      /*lastFileExceededProgramSize*/
      void 0,
      compilerOptions,
      /*compileOnSaveEnabled*/
      false,
      watchOptions,
      projectService.host,
      currentDirectory
    );
    this._isJsInferredProject = false;
    this.typeAcquisition = typeAcquisition;
    this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath);
    if (!projectRootPath && !projectService.useSingleInferredProject) {
      this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory);
    }
    this.enableGlobalPlugins(this.getCompilerOptions());
  }
  toggleJsInferredProject(isJsInferredProject) {
    if (isJsInferredProject !== this._isJsInferredProject) {
      this._isJsInferredProject = isJsInferredProject;
      this.setCompilerOptions();
    }
  }
  setCompilerOptions(options) {
    if (!options && !this.getCompilationSettings()) {
      return;
    }
    const newOptions = cloneCompilerOptions(options || this.getCompilationSettings());
    if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") {
      newOptions.maxNodeModuleJsDepth = 2;
    } else if (!this._isJsInferredProject) {
      newOptions.maxNodeModuleJsDepth = void 0;
    }
    newOptions.allowJs = true;
    super.setCompilerOptions(newOptions);
  }
  addRoot(info) {
    Debug.assert(info.isScriptOpen());
    this.projectService.startWatchingConfigFilesForInferredProjectRoot(info);
    if (!this._isJsInferredProject && info.isJavaScript()) {
      this.toggleJsInferredProject(
        /*isJsInferredProject*/
        true
      );
    } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) {
      this.toggleJsInferredProject(
        /*isJsInferredProject*/
        false
      );
    }
    super.addRoot(info);
  }
  removeRoot(info) {
    this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info);
    super.removeRoot(info);
    if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) {
      if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) {
        this.toggleJsInferredProject(
          /*isJsInferredProject*/
          false
        );
      }
    }
  }
  /** @internal */
  isOrphan() {
    return !this.hasRoots();
  }
  isProjectWithSingleRoot() {
    return !this.projectRootPath && !this.projectService.useSingleInferredProject || this.getRootScriptInfos().length === 1;
  }
  close() {
    forEach(this.getRootScriptInfos(), (info) => this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info));
    super.close();
  }
  getTypeAcquisition() {
    return this.typeAcquisition || {
      enable: allRootFilesAreJsOrDts(this),
      include: emptyArray,
      exclude: emptyArray
    };
  }
};
var AuxiliaryProject = class extends Project3 {
  constructor(projectService, documentRegistry, compilerOptions, currentDirectory) {
    super(
      projectService.newAuxiliaryProjectName(),
      4 /* Auxiliary */,
      projectService,
      documentRegistry,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      compilerOptions,
      /*compileOnSaveEnabled*/
      false,
      /*watchOptions*/
      void 0,
      projectService.host,
      currentDirectory
    );
  }
  isOrphan() {
    return true;
  }
  /** @internal */
  scheduleInvalidateResolutionsOfFailedLookupLocations() {
    return;
  }
};
var _AutoImportProviderProject = class extends Project3 {
  /** @internal */
  constructor(hostProject, initialRootNames, documentRegistry, compilerOptions) {
    super(
      hostProject.projectService.newAutoImportProviderProjectName(),
      3 /* AutoImportProvider */,
      hostProject.projectService,
      documentRegistry,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      compilerOptions,
      /*compileOnSaveEnabled*/
      false,
      hostProject.getWatchOptions(),
      hostProject.projectService.host,
      hostProject.currentDirectory
    );
    this.hostProject = hostProject;
    this.rootFileNames = initialRootNames;
    this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect);
    this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine);
  }
  /** @internal */
  static getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions) {
    var _a, _b;
    if (!dependencySelection) {
      return emptyArray;
    }
    const program = hostProject.getCurrentProgram();
    if (!program) {
      return emptyArray;
    }
    const start2 = timestamp();
    let dependencyNames;
    let rootNames;
    const rootFileName = combinePaths(hostProject.currentDirectory, inferredTypesContainingFile);
    const packageJsons = hostProject.getPackageJsonsForAutoImport(combinePaths(hostProject.currentDirectory, rootFileName));
    for (const packageJson of packageJsons) {
      (_a = packageJson.dependencies) == null ? void 0 : _a.forEach((_, dependenyName) => addDependency(dependenyName));
      (_b = packageJson.peerDependencies) == null ? void 0 : _b.forEach((_, dependencyName) => addDependency(dependencyName));
    }
    let dependenciesAdded = 0;
    if (dependencyNames) {
      const symlinkCache = hostProject.getSymlinkCache();
      for (const name of arrayFrom(dependencyNames.keys())) {
        if (dependencySelection === 2 /* Auto */ && dependenciesAdded > this.maxDependencies) {
          hostProject.log(`AutoImportProviderProject: attempted to add more than ${this.maxDependencies} dependencies. Aborting.`);
          return emptyArray;
        }
        const packageJson = resolvePackageNameToPackageJson(
          name,
          hostProject.currentDirectory,
          compilerOptions,
          moduleResolutionHost,
          program.getModuleResolutionCache()
        );
        if (packageJson) {
          const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache);
          if (entrypoints) {
            rootNames = concatenate(rootNames, entrypoints);
            dependenciesAdded += entrypoints.length ? 1 : 0;
            continue;
          }
        }
        const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], (directory) => {
          if (directory) {
            const typesPackageJson = resolvePackageNameToPackageJson(
              `@types/${name}`,
              directory,
              compilerOptions,
              moduleResolutionHost,
              program.getModuleResolutionCache()
            );
            if (typesPackageJson) {
              const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache);
              rootNames = concatenate(rootNames, entrypoints);
              dependenciesAdded += (entrypoints == null ? void 0 : entrypoints.length) ? 1 : 0;
              return true;
            }
          }
        });
        if (done)
          continue;
        if (packageJson && compilerOptions.allowJs && compilerOptions.maxNodeModuleJsDepth) {
          const entrypoints = getRootNamesFromPackageJson(
            packageJson,
            program,
            symlinkCache,
            /*resolveJs*/
            true
          );
          rootNames = concatenate(rootNames, entrypoints);
          dependenciesAdded += (entrypoints == null ? void 0 : entrypoints.length) ? 1 : 0;
        }
      }
    }
    if (rootNames == null ? void 0 : rootNames.length) {
      hostProject.log(`AutoImportProviderProject: found ${rootNames.length} root files in ${dependenciesAdded} dependencies in ${timestamp() - start2} ms`);
    }
    return rootNames || emptyArray;
    function addDependency(dependency) {
      if (!startsWith(dependency, "@types/")) {
        (dependencyNames || (dependencyNames = /* @__PURE__ */ new Set())).add(dependency);
      }
    }
    function getRootNamesFromPackageJson(packageJson, program2, symlinkCache, resolveJs) {
      var _a2;
      const entrypoints = getEntrypointsFromPackageJsonInfo(
        packageJson,
        compilerOptions,
        moduleResolutionHost,
        program2.getModuleResolutionCache(),
        resolveJs
      );
      if (entrypoints) {
        const real = (_a2 = moduleResolutionHost.realpath) == null ? void 0 : _a2.call(moduleResolutionHost, packageJson.packageDirectory);
        const isSymlink = real && real !== packageJson.packageDirectory;
        if (isSymlink) {
          symlinkCache.setSymlinkedDirectory(packageJson.packageDirectory, {
            real,
            realPath: hostProject.toPath(real)
          });
        }
        return mapDefined(entrypoints, (entrypoint) => {
          const resolvedFileName = isSymlink ? entrypoint.replace(packageJson.packageDirectory, real) : entrypoint;
          if (!program2.getSourceFile(resolvedFileName) && !(isSymlink && program2.getSourceFile(entrypoint))) {
            return resolvedFileName;
          }
        });
      }
    }
  }
  /** @internal */
  static create(dependencySelection, hostProject, moduleResolutionHost, documentRegistry) {
    if (dependencySelection === 0 /* Off */) {
      return void 0;
    }
    const compilerOptions = {
      ...hostProject.getCompilerOptions(),
      ...this.compilerOptionsOverrides
    };
    const rootNames = this.getRootFileNames(dependencySelection, hostProject, moduleResolutionHost, compilerOptions);
    if (!rootNames.length) {
      return void 0;
    }
    return new _AutoImportProviderProject(hostProject, rootNames, documentRegistry, compilerOptions);
  }
  /** @internal */
  isEmpty() {
    return !some(this.rootFileNames);
  }
  isOrphan() {
    return true;
  }
  updateGraph() {
    let rootFileNames = this.rootFileNames;
    if (!rootFileNames) {
      rootFileNames = _AutoImportProviderProject.getRootFileNames(
        this.hostProject.includePackageJsonAutoImports(),
        this.hostProject,
        this.hostProject.getModuleResolutionHostForAutoImportProvider(),
        this.getCompilationSettings()
      );
    }
    this.projectService.setFileNamesOfAutoImportProviderProject(this, rootFileNames);
    this.rootFileNames = rootFileNames;
    const oldProgram = this.getCurrentProgram();
    const hasSameSetOfFiles = super.updateGraph();
    if (oldProgram && oldProgram !== this.getCurrentProgram()) {
      this.hostProject.clearCachedExportInfoMap();
    }
    return hasSameSetOfFiles;
  }
  /** @internal */
  scheduleInvalidateResolutionsOfFailedLookupLocations() {
    return;
  }
  hasRoots() {
    var _a;
    return !!((_a = this.rootFileNames) == null ? void 0 : _a.length);
  }
  markAsDirty() {
    this.rootFileNames = void 0;
    super.markAsDirty();
  }
  getScriptFileNames() {
    return this.rootFileNames || emptyArray;
  }
  getLanguageService() {
    throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`.");
  }
  /** @internal */
  onAutoImportProviderSettingsChanged() {
    throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead.");
  }
  /** @internal */
  onPackageJsonChange() {
    throw new Error("package.json changes should be notified on an AutoImportProvider's host project");
  }
  getModuleResolutionHostForAutoImportProvider() {
    throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead.");
  }
  getProjectReferences() {
    return this.hostProject.getProjectReferences();
  }
  /** @internal */
  includePackageJsonAutoImports() {
    return 0 /* Off */;
  }
  getTypeAcquisition() {
    return { enable: false };
  }
  /** @internal */
  getSymlinkCache() {
    return this.hostProject.getSymlinkCache();
  }
  /** @internal */
  getModuleResolutionCache() {
    var _a;
    return (_a = this.hostProject.getCurrentProgram()) == null ? void 0 : _a.getModuleResolutionCache();
  }
};
var AutoImportProviderProject = _AutoImportProviderProject;
/** @internal */
AutoImportProviderProject.maxDependencies = 10;
/** @internal */
AutoImportProviderProject.compilerOptionsOverrides = {
  diagnostics: false,
  skipLibCheck: true,
  sourceMap: false,
  types: emptyArray,
  lib: emptyArray,
  noLib: true
};
var ConfiguredProject2 = class extends Project3 {
  /** @internal */
  constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost) {
    super(
      configFileName,
      1 /* Configured */,
      projectService,
      documentRegistry,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      /*compilerOptions*/
      {},
      /*compileOnSaveEnabled*/
      false,
      /*watchOptions*/
      void 0,
      cachedDirectoryStructureHost,
      getDirectoryPath(configFileName)
    );
    this.canonicalConfigFilePath = canonicalConfigFilePath;
    /** @internal */
    this.openFileWatchTriggered = /* @__PURE__ */ new Map();
    /** @internal */
    this.canConfigFileJsonReportNoInputFiles = false;
    /** Ref count to the project when opened from external project */
    this.externalProjectRefCount = 0;
    /** @internal */
    this.isInitialLoadPending = returnTrue;
    /** @internal */
    this.sendLoadingProjectFinish = false;
  }
  /** @internal */
  setCompilerHost(host) {
    this.compilerHost = host;
  }
  /** @internal */
  getCompilerHost() {
    return this.compilerHost;
  }
  /** @internal */
  useSourceOfProjectReferenceRedirect() {
    return this.languageServiceEnabled;
  }
  /** @internal */
  getParsedCommandLine(fileName) {
    const configFileName = asNormalizedPath(normalizePath(fileName));
    const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName));
    let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo) {
      this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) });
    }
    this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this);
    if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) {
      this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this);
    }
    return configFileExistenceInfo.exists ? configFileExistenceInfo.config.parsedCommandLine : void 0;
  }
  /** @internal */
  onReleaseParsedCommandLine(fileName) {
    this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName)))));
  }
  /** @internal */
  releaseParsedConfig(canonicalConfigFilePath) {
    this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this);
    this.projectService.releaseParsedConfig(canonicalConfigFilePath, this);
  }
  /**
   * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
   * @returns: true if set of files in the project stays the same and false - otherwise.
   */
  updateGraph() {
    const isInitialLoad = this.isInitialLoadPending();
    this.isInitialLoadPending = returnFalse;
    const reloadLevel = this.pendingReload;
    this.pendingReload = 0 /* None */;
    let result;
    switch (reloadLevel) {
      case 1 /* Partial */:
        this.openFileWatchTriggered.clear();
        result = this.projectService.reloadFileNamesOfConfiguredProject(this);
        break;
      case 2 /* Full */:
        this.openFileWatchTriggered.clear();
        const reason = Debug.checkDefined(this.pendingReloadReason);
        this.pendingReloadReason = void 0;
        this.projectService.reloadConfiguredProject(
          this,
          reason,
          isInitialLoad,
          /*clearSemanticCache*/
          false
        );
        result = true;
        break;
      default:
        result = super.updateGraph();
    }
    this.compilerHost = void 0;
    this.projectService.sendProjectLoadingFinishEvent(this);
    this.projectService.sendProjectTelemetry(this);
    return result;
  }
  /** @internal */
  getCachedDirectoryStructureHost() {
    return this.directoryStructureHost;
  }
  getConfigFilePath() {
    return asNormalizedPath(this.getProjectName());
  }
  getProjectReferences() {
    return this.projectReferences;
  }
  updateReferences(refs) {
    this.projectReferences = refs;
    this.potentialProjectReferences = void 0;
  }
  /** @internal */
  setPotentialProjectReference(canonicalConfigPath) {
    Debug.assert(this.isInitialLoadPending());
    (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */ new Set())).add(canonicalConfigPath);
  }
  /** @internal */
  getResolvedProjectReferenceToRedirect(fileName) {
    const program = this.getCurrentProgram();
    return program && program.getResolvedProjectReferenceToRedirect(fileName);
  }
  /** @internal */
  forEachResolvedProjectReference(cb) {
    var _a;
    return (_a = this.getCurrentProgram()) == null ? void 0 : _a.forEachResolvedProjectReference(cb);
  }
  /** @internal */
  enablePluginsWithOptions(options) {
    var _a;
    this.plugins.length = 0;
    if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length)
      return;
    const host = this.projectService.host;
    if (!host.require && !host.importPlugin) {
      this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
      return;
    }
    const searchPaths = this.getGlobalPluginSearchPaths();
    if (this.projectService.allowLocalPluginLoads) {
      const local = getDirectoryPath(this.canonicalConfigFilePath);
      this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`);
      searchPaths.unshift(local);
    }
    if (options.plugins) {
      for (const pluginConfigEntry of options.plugins) {
        this.enablePlugin(pluginConfigEntry, searchPaths);
      }
    }
    return this.enableGlobalPlugins(options);
  }
  /**
   * Get the errors that dont have any file name associated
   */
  getGlobalProjectErrors() {
    return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2;
  }
  /**
   * Get all the project errors
   */
  getAllProjectErrors() {
    return this.projectErrors || emptyArray2;
  }
  setProjectErrors(projectErrors) {
    this.projectErrors = projectErrors;
  }
  close() {
    this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.releaseParsedConfig(canonicalConfigFilePath));
    this.projectErrors = void 0;
    this.openFileWatchTriggered.clear();
    this.compilerHost = void 0;
    super.close();
  }
  /** @internal */
  addExternalProjectReference() {
    this.externalProjectRefCount++;
  }
  /** @internal */
  deleteExternalProjectReference() {
    this.externalProjectRefCount--;
  }
  /** @internal */
  isSolution() {
    return this.getRootFilesMap().size === 0 && !this.canConfigFileJsonReportNoInputFiles;
  }
  /**
   * Find the configured project from the project references in project which contains the info directly
   *
   * @internal
   */
  getDefaultChildProjectFromProjectWithReferences(info) {
    return forEachResolvedProjectReferenceProject(
      this,
      info.path,
      (child) => projectContainsInfoDirectly(child, info) ? child : void 0,
      0 /* Find */
    );
  }
  /**
   * Returns true if the project is needed by any of the open script info/external project
   *
   * @internal
   */
  hasOpenRef() {
    var _a;
    if (!!this.externalProjectRefCount) {
      return true;
    }
    if (this.isClosed()) {
      return false;
    }
    const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(this.canonicalConfigFilePath);
    if (this.projectService.hasPendingProjectUpdate(this)) {
      return !!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.size);
    }
    return !!configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry(
      configFileExistenceInfo.openFilesImpactedByConfigFile,
      (_value, infoPath) => {
        const info = this.projectService.getScriptInfoForPath(infoPath);
        return this.containsScriptInfo(info) || !!forEachResolvedProjectReferenceProject(
          this,
          info.path,
          (child) => child.containsScriptInfo(info),
          0 /* Find */
        );
      }
    ) || false;
  }
  /** @internal */
  hasExternalProjectRef() {
    return !!this.externalProjectRefCount;
  }
  getEffectiveTypeRoots() {
    return getEffectiveTypeRoots(this.getCompilationSettings(), this) || [];
  }
  /** @internal */
  updateErrorOnNoInputFiles(fileNames) {
    updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles);
  }
};
var ExternalProject2 = class extends Project3 {
  /** @internal */
  constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) {
    super(
      externalProjectName,
      2 /* External */,
      projectService,
      documentRegistry,
      /*hasExplicitListOfFiles*/
      true,
      lastFileExceededProgramSize,
      compilerOptions,
      compileOnSaveEnabled,
      watchOptions,
      projectService.host,
      getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName))
    );
    this.externalProjectName = externalProjectName;
    this.compileOnSaveEnabled = compileOnSaveEnabled;
    this.excludedFiles = [];
    this.enableGlobalPlugins(this.getCompilerOptions());
  }
  updateGraph() {
    const result = super.updateGraph();
    this.projectService.sendProjectTelemetry(this);
    return result;
  }
  getExcludedFiles() {
    return this.excludedFiles;
  }
};
function isInferredProject(project) {
  return project.projectKind === 0 /* Inferred */;
}
function isConfiguredProject(project) {
  return project.projectKind === 1 /* Configured */;
}
function isExternalProject(project) {
  return project.projectKind === 2 /* External */;
}

// src/server/editorServices.ts
var maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
var maxFileSize = 4 * 1024 * 1024;
var ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
var ProjectLoadingStartEvent = "projectLoadingStart";
var ProjectLoadingFinishEvent = "projectLoadingFinish";
var LargeFileReferencedEvent = "largeFileReferenced";
var ConfigFileDiagEvent = "configFileDiag";
var ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
var ProjectInfoTelemetryEvent = "projectInfo";
var OpenFileInfoTelemetryEvent = "openFileInfo";
var ensureProjectForOpenFileSchedule = "*ensureProjectForOpenFiles*";
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) {
  const map2 = /* @__PURE__ */ new Map();
  for (const option of commandLineOptions) {
    if (typeof option.type === "object") {
      const optionMap = option.type;
      optionMap.forEach((value) => {
        Debug.assert(typeof value === "number");
      });
      map2.set(option.name, optionMap);
    }
  }
  return map2;
}
var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(optionDeclarations);
var watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(optionsForWatch);
var indentStyle = new Map(Object.entries({
  none: 0 /* None */,
  block: 1 /* Block */,
  smart: 2 /* Smart */
}));
var defaultTypeSafeList = {
  "jquery": {
    // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
    match: /jquery(-[\d\.]+)?(\.intellisense)?(\.min)?\.js$/i,
    types: ["jquery"]
  },
  "WinJS": {
    // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
    match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i,
    // If the winjs/base.js file is found..
    exclude: [["^", 1, "/.*"]],
    // ..then exclude all files under the winjs folder
    types: ["winjs"]
    // And fetch the @types package for WinJS
  },
  "Kendo": {
    // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
    match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i,
    exclude: [["^", 1, "/.*"]],
    types: ["kendo-ui"]
  },
  "Office Nuget": {
    // e.g. /scripts/Office/1/excel-15.debug.js
    match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i,
    // Office NuGet package is installed under a "1/office" folder
    exclude: [["^", 1, "/.*"]],
    // Exclude that whole folder if the file indicated above is found in it
    types: ["office"]
    // @types package to fetch instead
  },
  "References": {
    match: /^(.*\/_references\.js)$/i,
    exclude: [["^", 1, "$"]]
  }
};
function convertFormatOptions(protocolOptions) {
  if (isString(protocolOptions.indentStyle)) {
    protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
    Debug.assert(protocolOptions.indentStyle !== void 0);
  }
  return protocolOptions;
}
function convertCompilerOptions(protocolOptions) {
  compilerOptionConverters.forEach((mappedValues, id) => {
    const propertyValue = protocolOptions[id];
    if (isString(propertyValue)) {
      protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase());
    }
  });
  return protocolOptions;
}
function convertWatchOptions(protocolOptions, currentDirectory) {
  let watchOptions;
  let errors;
  optionsForWatch.forEach((option) => {
    const propertyValue = protocolOptions[option.name];
    if (propertyValue === void 0)
      return;
    const mappedValues = watchOptionsConverters.get(option.name);
    (watchOptions || (watchOptions = {}))[option.name] = mappedValues ? isString(propertyValue) ? mappedValues.get(propertyValue.toLowerCase()) : propertyValue : convertJsonOption(option, propertyValue, currentDirectory || "", errors || (errors = []));
  });
  return watchOptions && { watchOptions, errors };
}
function convertTypeAcquisition(protocolOptions) {
  let result;
  typeAcquisitionDeclarations.forEach((option) => {
    const propertyValue = protocolOptions[option.name];
    if (propertyValue === void 0)
      return;
    (result || (result = {}))[option.name] = propertyValue;
  });
  return result;
}
function tryConvertScriptKindName(scriptKindName) {
  return isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName;
}
function convertScriptKindName(scriptKindName) {
  switch (scriptKindName) {
    case "JS":
      return 1 /* JS */;
    case "JSX":
      return 2 /* JSX */;
    case "TS":
      return 3 /* TS */;
    case "TSX":
      return 4 /* TSX */;
    default:
      return 0 /* Unknown */;
  }
}
function convertUserPreferences(preferences) {
  const { lazyConfiguredProjectsFromExternalProject, ...userPreferences } = preferences;
  return userPreferences;
}
var fileNamePropertyReader = {
  getFileName: (x) => x,
  getScriptKind: (fileName, extraFileExtensions) => {
    let result;
    if (extraFileExtensions) {
      const fileExtension = getAnyExtensionFromPath(fileName);
      if (fileExtension) {
        some(extraFileExtensions, (info) => {
          if (info.extension === fileExtension) {
            result = info.scriptKind;
            return true;
          }
          return false;
        });
      }
    }
    return result;
  },
  hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, (ext) => ext.isMixedContent && fileExtensionIs(fileName, ext.extension))
};
var externalFilePropertyReader = {
  getFileName: (x) => x.fileName,
  getScriptKind: (x) => tryConvertScriptKindName(x.scriptKind),
  // TODO: GH#18217
  hasMixedContent: (x) => !!x.hasMixedContent
};
function findProjectByName(projectName, projects) {
  for (const proj of projects) {
    if (proj.getProjectName() === projectName) {
      return proj;
    }
  }
}
var noopConfigFileWatcher = { close: noop };
function isOpenScriptInfo(infoOrFileNameOrConfig) {
  return !!infoOrFileNameOrConfig.containingProjects;
}
function isAncestorConfigFileInfo(infoOrFileNameOrConfig) {
  return !!infoOrFileNameOrConfig.configFileInfo;
}
var ProjectReferenceProjectLoadKind = /* @__PURE__ */ ((ProjectReferenceProjectLoadKind2) => {
  ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["Find"] = 0] = "Find";
  ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreate"] = 1] = "FindCreate";
  ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreateLoad"] = 2] = "FindCreateLoad";
  return ProjectReferenceProjectLoadKind2;
})(ProjectReferenceProjectLoadKind || {});
function forEachResolvedProjectReferenceProject(project, fileName, cb, projectReferenceProjectLoadKind, reason) {
  var _a;
  const resolvedRefs = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences();
  if (!resolvedRefs)
    return void 0;
  let seenResolvedRefs;
  const possibleDefaultRef = fileName ? project.getResolvedProjectReferenceToRedirect(fileName) : void 0;
  if (possibleDefaultRef) {
    const configFileName = toNormalizedPath(possibleDefaultRef.sourceFile.fileName);
    const child = project.projectService.findConfiguredProjectByProjectName(configFileName);
    if (child) {
      const result = cb(child);
      if (result)
        return result;
    } else if (projectReferenceProjectLoadKind !== 0 /* Find */) {
      seenResolvedRefs = /* @__PURE__ */ new Map();
      const result = forEachResolvedProjectReferenceProjectWorker(
        resolvedRefs,
        project.getCompilerOptions(),
        (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : void 0,
        projectReferenceProjectLoadKind,
        project.projectService,
        seenResolvedRefs
      );
      if (result)
        return result;
      seenResolvedRefs.clear();
    }
  }
  return forEachResolvedProjectReferenceProjectWorker(
    resolvedRefs,
    project.getCompilerOptions(),
    (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : void 0,
    projectReferenceProjectLoadKind,
    project.projectService,
    seenResolvedRefs
  );
  function callback(ref, loadKind) {
    const configFileName = toNormalizedPath(ref.sourceFile.fileName);
    const child = project.projectService.findConfiguredProjectByProjectName(configFileName) || (loadKind === 0 /* Find */ ? void 0 : loadKind === 1 /* FindCreate */ ? project.projectService.createConfiguredProject(configFileName) : loadKind === 2 /* FindCreateLoad */ ? project.projectService.createAndLoadConfiguredProject(configFileName, reason) : Debug.assertNever(loadKind));
    return child && cb(child);
  }
}
function forEachResolvedProjectReferenceProjectWorker(resolvedProjectReferences, parentOptions, cb, projectReferenceProjectLoadKind, projectService, seenResolvedRefs) {
  const loadKind = parentOptions.disableReferencedProjectLoad ? 0 /* Find */ : projectReferenceProjectLoadKind;
  return forEach(resolvedProjectReferences, (ref) => {
    if (!ref)
      return void 0;
    const configFileName = toNormalizedPath(ref.sourceFile.fileName);
    const canonicalPath = projectService.toCanonicalFileName(configFileName);
    const seenValue = seenResolvedRefs == null ? void 0 : seenResolvedRefs.get(canonicalPath);
    if (seenValue !== void 0 && seenValue >= loadKind) {
      return void 0;
    }
    const result = cb(ref, loadKind);
    if (result) {
      return result;
    }
    (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Map())).set(canonicalPath, loadKind);
    return ref.references && forEachResolvedProjectReferenceProjectWorker(ref.references, ref.commandLine.options, cb, loadKind, projectService, seenResolvedRefs);
  });
}
function forEachPotentialProjectReference(project, cb) {
  return project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb);
}
function forEachAnyProjectReferenceKind(project, cb, cbProjectRef, cbPotentialProjectRef) {
  return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.isInitialLoadPending() ? forEachPotentialProjectReference(project, cbPotentialProjectRef) : forEach(project.getProjectReferences(), cbProjectRef);
}
function callbackRefProject(project, cb, refPath) {
  const refProject = refPath && project.projectService.configuredProjects.get(refPath);
  return refProject && cb(refProject);
}
function forEachReferencedProject(project, cb) {
  return forEachAnyProjectReferenceKind(
    project,
    (resolvedRef) => callbackRefProject(project, cb, resolvedRef.sourceFile.path),
    (projectRef) => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))),
    (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef)
  );
}
function getDetailWatchInfo(watchType, project) {
  return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`;
}
function isScriptInfoWatchedFromNodeModules(info) {
  return !info.isScriptOpen() && info.mTime !== void 0;
}
function projectContainsInfoDirectly(project, info) {
  return project.containsScriptInfo(info) && !project.isSourceOfProjectReferenceRedirect(info.path);
}
function updateProjectIfDirty(project) {
  project.invalidateResolutionsOfFailedLookupLocations();
  return project.dirty && project.updateGraph();
}
function setProjectOptionsUsed(project) {
  if (isConfiguredProject(project)) {
    project.projectOptions = true;
  }
}
function createProjectNameFactoryWithCounter(nameFactory) {
  let nextId = 1;
  return () => nameFactory(nextId++);
}
var _ProjectService = class {
  constructor(opts) {
    /**
     * Container of all known scripts
     *
     * @internal
     */
    this.filenameToScriptInfo = /* @__PURE__ */ new Map();
    this.nodeModulesWatchers = /* @__PURE__ */ new Map();
    /**
     * Contains all the deleted script info's version information so that
     * it does not reset when creating script info again
     * (and could have potentially collided with version where contents mismatch)
     */
    this.filenameToScriptInfoVersion = /* @__PURE__ */ new Map();
    // Set of all '.js' files ever opened.
    this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Map();
    /**
     * maps external project file name to list of config files that were the part of this project
     */
    this.externalProjectToConfiguredProjectMap = /* @__PURE__ */ new Map();
    /**
     * external projects (configuration and list of root files is not controlled by tsserver)
     */
    this.externalProjects = [];
    /**
     * projects built from openFileRoots
     */
    this.inferredProjects = [];
    /**
     * projects specified by a tsconfig.json file
     */
    this.configuredProjects = /* @__PURE__ */ new Map();
    /** @internal */
    this.newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName);
    /** @internal */
    this.newAutoImportProviderProjectName = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName);
    /** @internal */
    this.newAuxiliaryProjectName = createProjectNameFactoryWithCounter(makeAuxiliaryProjectName);
    /**
     * Open files: with value being project root path, and key being Path of the file that is open
     */
    this.openFiles = /* @__PURE__ */ new Map();
    /** @internal */
    this.configFileForOpenFiles = /* @__PURE__ */ new Map();
    /**
     * Map of open files that are opened without complete path but have projectRoot as current directory
     */
    this.openFilesWithNonRootedDiskPath = /* @__PURE__ */ new Map();
    this.compilerOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map();
    this.watchOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map();
    this.typeAcquisitionForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map();
    /**
     * Project size for configured or external projects
     */
    this.projectToSizeMap = /* @__PURE__ */ new Map();
    /**
     * This is a map of config file paths existence that doesnt need query to disk
     * - The entry can be present because there is inferred project that needs to watch addition of config file to directory
     *   In this case the exists could be true/false based on config file is present or not
     * - Or it is present if we have configured project open with config file at that location
     *   In this case the exists property is always true
     *
     *
     * @internal
     */
    this.configFileExistenceInfoCache = /* @__PURE__ */ new Map();
    this.safelist = defaultTypeSafeList;
    this.legacySafelist = /* @__PURE__ */ new Map();
    this.pendingProjectUpdates = /* @__PURE__ */ new Map();
    /** @internal */
    this.pendingEnsureProjectForOpenFiles = false;
    /** Tracks projects that we have already sent telemetry for. */
    this.seenProjects = /* @__PURE__ */ new Map();
    /** @internal */
    this.sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map();
    /** @internal */
    this.extendedConfigCache = /* @__PURE__ */ new Map();
    this.host = opts.host;
    this.logger = opts.logger;
    this.cancellationToken = opts.cancellationToken;
    this.useSingleInferredProject = opts.useSingleInferredProject;
    this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot;
    this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller;
    this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds;
    this.eventHandler = opts.eventHandler;
    this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents;
    this.globalPlugins = opts.globalPlugins || emptyArray2;
    this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray2;
    this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads;
    this.typesMapLocation = opts.typesMapLocation === void 0 ? combinePaths(getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation;
    this.session = opts.session;
    if (opts.serverMode !== void 0) {
      this.serverMode = opts.serverMode;
    } else {
      this.serverMode = 0 /* Semantic */;
    }
    if (this.host.realpath) {
      this.realpathToScriptInfos = createMultiMap();
    }
    this.currentDirectory = toNormalizedPath(this.host.getCurrentDirectory());
    this.toCanonicalFileName = createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
    this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation ? ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) : void 0;
    this.throttledOperations = new ThrottledOperations(this.host, this.logger);
    if (this.typesMapLocation) {
      this.loadTypesMap();
    } else {
      this.logger.info("No types map provided; using the default");
    }
    this.typingsInstaller.attach(this);
    this.typingsCache = new TypingsCache(this.typingsInstaller);
    this.hostConfiguration = {
      formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine),
      preferences: emptyOptions,
      hostInfo: "Unknown host",
      extraFileExtensions: []
    };
    this.documentRegistry = createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this);
    const watchLogLevel = this.logger.hasLevel(3 /* verbose */) ? 2 /* Verbose */ : this.logger.loggingEnabled() ? 1 /* TriggerOnly */ : 0 /* None */;
    const log = watchLogLevel !== 0 /* None */ ? (s) => this.logger.info(s) : noop;
    this.packageJsonCache = createPackageJsonCache(this);
    this.watchFactory = this.serverMode !== 0 /* Semantic */ ? {
      watchFile: returnNoopFileWatcher,
      watchDirectory: returnNoopFileWatcher
    } : getWatchFactory(this.host, watchLogLevel, log, getDetailWatchInfo);
  }
  toPath(fileName) {
    return toPath(fileName, this.currentDirectory, this.toCanonicalFileName);
  }
  /** @internal */
  getExecutingFilePath() {
    return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath());
  }
  /** @internal */
  getNormalizedAbsolutePath(fileName) {
    return getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory());
  }
  /** @internal */
  setDocument(key, path, sourceFile) {
    const info = Debug.checkDefined(this.getScriptInfoForPath(path));
    info.cacheSourceFile = { key, sourceFile };
  }
  /** @internal */
  getDocument(key, path) {
    const info = this.getScriptInfoForPath(path);
    return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : void 0;
  }
  /** @internal */
  ensureInferredProjectsUpToDate_TestOnly() {
    this.ensureProjectStructuresUptoDate();
  }
  /** @internal */
  getCompilerOptionsForInferredProjects() {
    return this.compilerOptionsForInferredProjects;
  }
  /** @internal */
  onUpdateLanguageServiceStateForProject(project, languageServiceEnabled) {
    if (!this.eventHandler) {
      return;
    }
    const event = {
      eventName: ProjectLanguageServiceStateEvent,
      data: { project, languageServiceEnabled }
    };
    this.eventHandler(event);
  }
  loadTypesMap() {
    try {
      const fileContent = this.host.readFile(this.typesMapLocation);
      if (fileContent === void 0) {
        this.logger.info(`Provided types map file "${this.typesMapLocation}" doesn't exist`);
        return;
      }
      const raw = JSON.parse(fileContent);
      for (const k of Object.keys(raw.typesMap)) {
        raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i");
      }
      this.safelist = raw.typesMap;
      for (const key in raw.simpleMap) {
        if (hasProperty(raw.simpleMap, key)) {
          this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase());
        }
      }
    } catch (e) {
      this.logger.info(`Error loading types map: ${e}`);
      this.safelist = defaultTypeSafeList;
      this.legacySafelist.clear();
    }
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  updateTypingsForProject(response) {
    const project = this.findProject(response.projectName);
    if (!project) {
      return;
    }
    switch (response.kind) {
      case ActionSet:
        project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings));
        return;
      case ActionInvalidate:
        this.typingsCache.enqueueInstallTypingsForProject(
          project,
          project.lastCachedUnresolvedImportsList,
          /*forceRefresh*/
          true
        );
        return;
    }
  }
  /** @internal */
  watchTypingLocations(response) {
    var _a;
    (_a = this.findProject(response.projectName)) == null ? void 0 : _a.watchTypingLocations(response.files);
  }
  /** @internal */
  delayEnsureProjectForOpenFiles() {
    if (!this.openFiles.size)
      return;
    this.pendingEnsureProjectForOpenFiles = true;
    this.throttledOperations.schedule(
      ensureProjectForOpenFileSchedule,
      /*delay*/
      2500,
      () => {
        if (this.pendingProjectUpdates.size !== 0) {
          this.delayEnsureProjectForOpenFiles();
        } else {
          if (this.pendingEnsureProjectForOpenFiles) {
            this.ensureProjectForOpenFiles();
            this.sendProjectsUpdatedInBackgroundEvent();
          }
        }
      }
    );
  }
  delayUpdateProjectGraph(project) {
    project.markAsDirty();
    if (project.projectKind !== 3 /* AutoImportProvider */ && project.projectKind !== 4 /* Auxiliary */) {
      const projectName = project.getProjectName();
      this.pendingProjectUpdates.set(projectName, project);
      this.throttledOperations.schedule(
        projectName,
        /*delay*/
        250,
        () => {
          if (this.pendingProjectUpdates.delete(projectName)) {
            updateProjectIfDirty(project);
          }
        }
      );
    }
  }
  /** @internal */
  hasPendingProjectUpdate(project) {
    return this.pendingProjectUpdates.has(project.getProjectName());
  }
  /** @internal */
  sendProjectsUpdatedInBackgroundEvent() {
    if (!this.eventHandler) {
      return;
    }
    const event = {
      eventName: ProjectsUpdatedInBackgroundEvent,
      data: {
        openFiles: arrayFrom(this.openFiles.keys(), (path) => this.getScriptInfoForPath(path).fileName)
      }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendLargeFileReferencedEvent(file, fileSize) {
    if (!this.eventHandler) {
      return;
    }
    const event = {
      eventName: LargeFileReferencedEvent,
      data: { file, fileSize, maxFileSize }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendProjectLoadingStartEvent(project, reason) {
    if (!this.eventHandler) {
      return;
    }
    project.sendLoadingProjectFinish = true;
    const event = {
      eventName: ProjectLoadingStartEvent,
      data: { project, reason }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendProjectLoadingFinishEvent(project) {
    if (!this.eventHandler || !project.sendLoadingProjectFinish) {
      return;
    }
    project.sendLoadingProjectFinish = false;
    const event = {
      eventName: ProjectLoadingFinishEvent,
      data: { project }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendPerformanceEvent(kind, durationMs) {
    if (this.performanceEventHandler) {
      this.performanceEventHandler({ kind, durationMs });
    }
  }
  /** @internal */
  delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project) {
    this.delayUpdateProjectGraph(project);
    this.delayEnsureProjectForOpenFiles();
  }
  delayUpdateProjectGraphs(projects, clearSourceMapperCache) {
    if (projects.length) {
      for (const project of projects) {
        if (clearSourceMapperCache)
          project.clearSourceMapperCache();
        this.delayUpdateProjectGraph(project);
      }
      this.delayEnsureProjectForOpenFiles();
    }
  }
  setCompilerOptionsForInferredProjects(projectCompilerOptions, projectRootPath) {
    Debug.assert(projectRootPath === void 0 || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled");
    const compilerOptions = convertCompilerOptions(projectCompilerOptions);
    const watchOptions = convertWatchOptions(projectCompilerOptions, projectRootPath);
    const typeAcquisition = convertTypeAcquisition(projectCompilerOptions);
    compilerOptions.allowNonTsExtensions = true;
    const canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath);
    if (canonicalProjectRootPath) {
      this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions);
      this.watchOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, watchOptions || false);
      this.typeAcquisitionForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, typeAcquisition);
    } else {
      this.compilerOptionsForInferredProjects = compilerOptions;
      this.watchOptionsForInferredProjects = watchOptions;
      this.typeAcquisitionForInferredProjects = typeAcquisition;
    }
    for (const project of this.inferredProjects) {
      if (canonicalProjectRootPath ? project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) {
        project.setCompilerOptions(compilerOptions);
        project.setTypeAcquisition(typeAcquisition);
        project.setWatchOptions(watchOptions == null ? void 0 : watchOptions.watchOptions);
        project.setProjectErrors(watchOptions == null ? void 0 : watchOptions.errors);
        project.compileOnSaveEnabled = compilerOptions.compileOnSave;
        project.markAsDirty();
        this.delayUpdateProjectGraph(project);
      }
    }
    this.delayEnsureProjectForOpenFiles();
  }
  findProject(projectName) {
    if (projectName === void 0) {
      return void 0;
    }
    if (isInferredProjectName(projectName)) {
      return findProjectByName(projectName, this.inferredProjects);
    }
    return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(toNormalizedPath(projectName));
  }
  /** @internal */
  forEachProject(cb) {
    this.externalProjects.forEach(cb);
    this.configuredProjects.forEach(cb);
    this.inferredProjects.forEach(cb);
  }
  /** @internal */
  forEachEnabledProject(cb) {
    this.forEachProject((project) => {
      if (!project.isOrphan() && project.languageServiceEnabled) {
        cb(project);
      }
    });
  }
  getDefaultProjectForFile(fileName, ensureProject) {
    return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
  }
  /** @internal */
  tryGetDefaultProjectForFile(fileNameOrScriptInfo) {
    const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
    return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : void 0;
  }
  /** @internal */
  ensureDefaultProjectForFile(fileNameOrScriptInfo) {
    return this.tryGetDefaultProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo);
  }
  doEnsureDefaultProjectForFile(fileNameOrScriptInfo) {
    this.ensureProjectStructuresUptoDate();
    const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
    return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), Errors.ThrowNoProject());
  }
  getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName) {
    this.ensureProjectStructuresUptoDate();
    return this.getScriptInfo(uncheckedFileName);
  }
  /**
   * Ensures the project structures are upto date
   * This means,
   * - we go through all the projects and update them if they are dirty
   * - if updates reflect some change in structure or there was pending request to ensure projects for open files
   *   ensure that each open script info has project
   */
  ensureProjectStructuresUptoDate() {
    let hasChanges = this.pendingEnsureProjectForOpenFiles;
    this.pendingProjectUpdates.clear();
    const updateGraph = (project) => {
      hasChanges = updateProjectIfDirty(project) || hasChanges;
    };
    this.externalProjects.forEach(updateGraph);
    this.configuredProjects.forEach(updateGraph);
    this.inferredProjects.forEach(updateGraph);
    if (hasChanges) {
      this.ensureProjectForOpenFiles();
    }
  }
  getFormatCodeOptions(file) {
    const info = this.getScriptInfoForNormalizedPath(file);
    return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions;
  }
  getPreferences(file) {
    const info = this.getScriptInfoForNormalizedPath(file);
    return { ...this.hostConfiguration.preferences, ...info && info.getPreferences() };
  }
  getHostFormatCodeOptions() {
    return this.hostConfiguration.formatCodeOptions;
  }
  getHostPreferences() {
    return this.hostConfiguration.preferences;
  }
  onSourceFileChanged(info, eventKind) {
    if (eventKind === 2 /* Deleted */) {
      this.handleDeletedFile(info);
    } else if (!info.isScriptOpen()) {
      info.delayReloadNonMixedContentFile();
      this.delayUpdateProjectGraphs(
        info.containingProjects,
        /*clearSourceMapperCache*/
        false
      );
      this.handleSourceMapProjects(info);
    }
  }
  handleSourceMapProjects(info) {
    if (info.sourceMapFilePath) {
      if (isString(info.sourceMapFilePath)) {
        const sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
        this.delayUpdateSourceInfoProjects(sourceMapFileInfo && sourceMapFileInfo.sourceInfos);
      } else {
        this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos);
      }
    }
    this.delayUpdateSourceInfoProjects(info.sourceInfos);
    if (info.declarationInfoPath) {
      this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath);
    }
  }
  delayUpdateSourceInfoProjects(sourceInfos) {
    if (sourceInfos) {
      sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path));
    }
  }
  delayUpdateProjectsOfScriptInfoPath(path) {
    const info = this.getScriptInfoForPath(path);
    if (info) {
      this.delayUpdateProjectGraphs(
        info.containingProjects,
        /*clearSourceMapperCache*/
        true
      );
    }
  }
  handleDeletedFile(info) {
    this.stopWatchingScriptInfo(info);
    if (!info.isScriptOpen()) {
      this.deleteScriptInfo(info);
      const containingProjects = info.containingProjects.slice();
      info.detachAllProjects();
      this.delayUpdateProjectGraphs(
        containingProjects,
        /*clearSourceMapperCache*/
        false
      );
      this.handleSourceMapProjects(info);
      info.closeSourceMapFileWatcher();
      if (info.declarationInfoPath) {
        const declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath);
        if (declarationInfo) {
          declarationInfo.sourceMapFilePath = void 0;
        }
      }
    }
  }
  /**
   * This is to watch whenever files are added or removed to the wildcard directories
   *
   * @internal
   */
  watchWildcardDirectory(directory, flags, configFileName, config) {
    return this.watchFactory.watchDirectory(
      directory,
      (fileOrDirectory) => {
        const fileOrDirectoryPath = this.toPath(fileOrDirectory);
        const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
        if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath))) {
          this.logger.info(`Config: ${configFileName} Detected new package.json: ${fileOrDirectory}`);
          this.onAddPackageJson(fileOrDirectoryPath);
        }
        const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName);
        if (isIgnoredFileFromWildCardWatching({
          watchedDirPath: directory,
          fileOrDirectory,
          fileOrDirectoryPath,
          configFileName,
          extraFileExtensions: this.hostConfiguration.extraFileExtensions,
          currentDirectory: this.currentDirectory,
          options: config.parsedCommandLine.options,
          program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames,
          useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames,
          writeLog: (s) => this.logger.info(s),
          toPath: (s) => this.toPath(s)
        }))
          return;
        if (config.reloadLevel !== 2 /* Full */)
          config.reloadLevel = 1 /* Partial */;
        config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => {
          if (!watchWildcardDirectories)
            return;
          const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath);
          if (!project)
            return;
          const reloadLevel = configuredProjectForConfig === project ? 1 /* Partial */ : 0 /* None */;
          if (project.pendingReload !== void 0 && project.pendingReload > reloadLevel)
            return;
          if (this.openFiles.has(fileOrDirectoryPath)) {
            const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath));
            if (info.isAttached(project)) {
              const loadLevelToSet = Math.max(reloadLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* None */);
              project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet);
            } else {
              project.pendingReload = reloadLevel;
              this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
            }
          } else {
            project.pendingReload = reloadLevel;
            this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
          }
        });
      },
      flags,
      this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions),
      WatchType.WildcardDirectory,
      configFileName
    );
  }
  /** @internal */
  delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, reloadReason) {
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config))
      return false;
    let scheduledAnyProjectUpdate = false;
    configFileExistenceInfo.config.reloadLevel = 2 /* Full */;
    configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => {
      const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath);
      if (!project)
        return;
      scheduledAnyProjectUpdate = true;
      if (projectCanonicalPath === canonicalConfigFilePath) {
        if (project.isInitialLoadPending())
          return;
        project.pendingReload = 2 /* Full */;
        project.pendingReloadReason = reloadReason;
        this.delayUpdateProjectGraph(project);
      } else {
        project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(this.toPath(canonicalConfigFilePath));
        this.delayUpdateProjectGraph(project);
      }
    });
    return scheduledAnyProjectUpdate;
  }
  /** @internal */
  onConfigFileChanged(canonicalConfigFilePath, eventKind) {
    var _a;
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (eventKind === 2 /* Deleted */) {
      configFileExistenceInfo.exists = false;
      const project = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(canonicalConfigFilePath)) ? this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) : void 0;
      if (project)
        this.removeProject(project);
    } else {
      configFileExistenceInfo.exists = true;
    }
    this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected");
    this.reloadConfiguredProjectForFiles(
      configFileExistenceInfo.openFilesImpactedByConfigFile,
      /*clearSemanticCache*/
      false,
      /*delayReload*/
      true,
      eventKind !== 2 /* Deleted */ ? identity : (
        // Reload open files if they are root of inferred project
        returnTrue
      ),
      // Reload all the open files impacted by config file
      "Change in config file detected"
    );
    this.delayEnsureProjectForOpenFiles();
  }
  removeProject(project) {
    this.logger.info("`remove Project::");
    project.print(
      /*writeProjectFileNames*/
      true,
      /*writeFileExplaination*/
      true,
      /*writeFileVersionAndText*/
      false
    );
    project.close();
    if (Debug.shouldAssert(1 /* Normal */)) {
      this.filenameToScriptInfo.forEach((info) => Debug.assert(
        !info.isAttached(project),
        "Found script Info still attached to project",
        () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify(
          arrayFrom(
            mapDefinedIterator(
              this.filenameToScriptInfo.values(),
              (info2) => info2.isAttached(project) ? {
                fileName: info2.fileName,
                projects: info2.containingProjects.map((p) => p.projectName),
                hasMixedContent: info2.hasMixedContent
              } : void 0
            )
          ),
          /*replacer*/
          void 0,
          " "
        )}`
      ));
    }
    this.pendingProjectUpdates.delete(project.getProjectName());
    switch (project.projectKind) {
      case 2 /* External */:
        unorderedRemoveItem(this.externalProjects, project);
        this.projectToSizeMap.delete(project.getProjectName());
        break;
      case 1 /* Configured */:
        this.configuredProjects.delete(project.canonicalConfigFilePath);
        this.projectToSizeMap.delete(project.canonicalConfigFilePath);
        break;
      case 0 /* Inferred */:
        unorderedRemoveItem(this.inferredProjects, project);
        break;
    }
  }
  /** @internal */
  assignOrphanScriptInfoToInferredProject(info, projectRootPath) {
    Debug.assert(info.isOrphan());
    const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || this.getOrCreateSingleInferredWithoutProjectRoot(
      info.isDynamic ? projectRootPath || this.currentDirectory : getDirectoryPath(
        isRootedDiskPath(info.fileName) ? info.fileName : getNormalizedAbsolutePath(
          info.fileName,
          projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory
        )
      )
    );
    project.addRoot(info);
    if (info.containingProjects[0] !== project) {
      info.detachFromProject(project);
      info.containingProjects.unshift(project);
    }
    project.updateGraph();
    if (!this.useSingleInferredProject && !project.projectRootPath) {
      for (const inferredProject of this.inferredProjects) {
        if (inferredProject === project || inferredProject.isOrphan()) {
          continue;
        }
        const roots = inferredProject.getRootScriptInfos();
        Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath);
        if (roots.length === 1 && forEach(roots[0].containingProjects, (p) => p !== roots[0].containingProjects[0] && !p.isOrphan())) {
          inferredProject.removeFile(
            roots[0],
            /*fileExists*/
            true,
            /*detachFromProject*/
            true
          );
        }
      }
    }
    return project;
  }
  assignOrphanScriptInfosToInferredProject() {
    this.openFiles.forEach((projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      if (info.isOrphan()) {
        this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
      }
    });
  }
  /**
   * Remove this file from the set of open, non-configured files.
   * @param info The file that has been closed or newly configured
   */
  closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) {
    const fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName);
    info.close(fileExists);
    this.stopWatchingConfigFilesForClosedScriptInfo(info);
    const canonicalFileName = this.toCanonicalFileName(info.fileName);
    if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) {
      this.openFilesWithNonRootedDiskPath.delete(canonicalFileName);
    }
    let ensureProjectsForOpenFiles = false;
    for (const p of info.containingProjects) {
      if (isConfiguredProject(p)) {
        if (info.hasMixedContent) {
          info.registerFileUpdate();
        }
        const reloadLevel = p.openFileWatchTriggered.get(info.path);
        if (reloadLevel !== void 0) {
          p.openFileWatchTriggered.delete(info.path);
          if (p.pendingReload !== void 0 && p.pendingReload < reloadLevel) {
            p.pendingReload = reloadLevel;
            p.markFileAsDirty(info.path);
          }
        }
      } else if (isInferredProject(p) && p.isRoot(info)) {
        if (p.isProjectWithSingleRoot()) {
          ensureProjectsForOpenFiles = true;
        }
        p.removeFile(
          info,
          fileExists,
          /*detachFromProject*/
          true
        );
      }
      if (!p.languageServiceEnabled) {
        p.markAsDirty();
      }
    }
    this.openFiles.delete(info.path);
    this.configFileForOpenFiles.delete(info.path);
    if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
      this.assignOrphanScriptInfosToInferredProject();
    }
    if (fileExists) {
      this.watchClosedScriptInfo(info);
    } else {
      this.handleDeletedFile(info);
    }
    return ensureProjectsForOpenFiles;
  }
  deleteScriptInfo(info) {
    this.filenameToScriptInfo.delete(info.path);
    this.filenameToScriptInfoVersion.set(info.path, info.textStorage.version);
    const realpath = info.getRealpathIfDifferent();
    if (realpath) {
      this.realpathToScriptInfos.remove(realpath, info);
    }
  }
  configFileExists(configFileName, canonicalConfigFilePath, info) {
    var _a;
    let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (configFileExistenceInfo) {
      if (isOpenScriptInfo(info) && !((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path))) {
        (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false);
      }
      return configFileExistenceInfo.exists;
    }
    const exists = this.host.fileExists(configFileName);
    let openFilesImpactedByConfigFile;
    if (isOpenScriptInfo(info)) {
      (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false);
    }
    configFileExistenceInfo = { exists, openFilesImpactedByConfigFile };
    this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
    return exists;
  }
  /** @internal */
  createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, forProject) {
    var _a, _b;
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) {
      configFileExistenceInfo.watcher = this.watchFactory.watchFile(
        configFileName,
        (_fileName, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind),
        2e3 /* High */,
        this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions),
        WatchType.ConfigFile,
        forProject
      );
    }
    const projects = configFileExistenceInfo.config.projects;
    projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false);
  }
  /**
   * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project
   */
  configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo) {
    return configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, identity);
  }
  /** @internal */
  releaseParsedConfig(canonicalConfigFilePath, forProject) {
    var _a, _b, _c;
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath)))
      return;
    if ((_b = configFileExistenceInfo.config) == null ? void 0 : _b.projects.size)
      return;
    configFileExistenceInfo.config = void 0;
    clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers);
    Debug.checkDefined(configFileExistenceInfo.watcher);
    if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) {
      if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
        if (!canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath)))) {
          configFileExistenceInfo.watcher.close();
          configFileExistenceInfo.watcher = noopConfigFileWatcher;
        }
      } else {
        configFileExistenceInfo.watcher.close();
        configFileExistenceInfo.watcher = void 0;
      }
    } else {
      configFileExistenceInfo.watcher.close();
      this.configFileExistenceInfoCache.delete(canonicalConfigFilePath);
    }
  }
  /**
   * Close the config file watcher in the cached ConfigFileExistenceInfo
   *   if there arent any open files that are root of inferred project and there is no parsed config held by any project
   *
   * @internal
   */
  closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo) {
    if (configFileExistenceInfo.watcher && !configFileExistenceInfo.config && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
      configFileExistenceInfo.watcher.close();
      configFileExistenceInfo.watcher = void 0;
    }
  }
  /**
   * This is called on file close, so that we stop watching the config file for this script info
   */
  stopWatchingConfigFilesForClosedScriptInfo(info) {
    Debug.assert(!info.isScriptOpen());
    this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => {
      var _a, _b, _c;
      const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
      if (configFileExistenceInfo) {
        const infoIsRootOfInferredProject = (_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.get(info.path);
        (_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.delete(info.path);
        if (infoIsRootOfInferredProject) {
          this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo);
        }
        if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) && !configFileExistenceInfo.config) {
          Debug.assert(!configFileExistenceInfo.watcher);
          this.configFileExistenceInfoCache.delete(canonicalConfigFilePath);
        }
      }
    });
  }
  /**
   * This is called by inferred project whenever script info is added as a root
   *
   * @internal
   */
  startWatchingConfigFilesForInferredProjectRoot(info) {
    Debug.assert(info.isScriptOpen());
    this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => {
      let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
      if (!configFileExistenceInfo) {
        configFileExistenceInfo = { exists: this.host.fileExists(configFileName) };
        this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
      }
      (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, true);
      configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath))) ? this.watchFactory.watchFile(
        configFileName,
        (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind),
        2e3 /* High */,
        this.hostConfiguration.watchOptions,
        WatchType.ConfigFileForInferredRoot
      ) : noopConfigFileWatcher);
    });
  }
  /**
   * This is called by inferred project whenever root script info is removed from it
   *
   * @internal
   */
  stopWatchingConfigFilesForInferredProjectRoot(info) {
    this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => {
      var _a;
      const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
      if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path)) {
        Debug.assert(info.isScriptOpen());
        configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
        this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo);
      }
    });
  }
  /**
   * This function tries to search for a tsconfig.json for the given file.
   * This is different from the method the compiler uses because
   * the compiler can assume it will always start searching in the
   * current directory (the directory in which tsc was invoked).
   * The server must start searching from the directory containing
   * the newly opened file.
   */
  forEachConfigFileLocation(info, action) {
    if (this.serverMode !== 0 /* Semantic */) {
      return void 0;
    }
    Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path));
    const projectRootPath = this.openFiles.get(info.path);
    const scriptInfo = Debug.checkDefined(this.getScriptInfo(info.path));
    if (scriptInfo.isDynamic)
      return void 0;
    let searchPath = asNormalizedPath(getDirectoryPath(info.fileName));
    const isSearchPathInProjectRoot = () => containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames);
    const anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
    let searchInDirectory = !isAncestorConfigFileInfo(info);
    do {
      if (searchInDirectory) {
        const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
        const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json"));
        let result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName);
        if (result)
          return tsconfigFileName;
        const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json"));
        result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName);
        if (result)
          return jsconfigFileName;
        if (isNodeModulesDirectory(canonicalSearchPath)) {
          break;
        }
      }
      const parentPath = asNormalizedPath(getDirectoryPath(searchPath));
      if (parentPath === searchPath)
        break;
      searchPath = parentPath;
      searchInDirectory = true;
    } while (anySearchPathOk || isSearchPathInProjectRoot());
    return void 0;
  }
  /** @internal */
  findDefaultConfiguredProject(info) {
    if (!info.isScriptOpen())
      return void 0;
    const configFileName = this.getConfigFileNameForFile(info);
    const project = configFileName && this.findConfiguredProjectByProjectName(configFileName);
    return project && projectContainsInfoDirectly(project, info) ? project : project == null ? void 0 : project.getDefaultChildProjectFromProjectWithReferences(info);
  }
  /**
   * This function tries to search for a tsconfig.json for the given file.
   * This is different from the method the compiler uses because
   * the compiler can assume it will always start searching in the
   * current directory (the directory in which tsc was invoked).
   * The server must start searching from the directory containing
   * the newly opened file.
   * If script info is passed in, it is asserted to be open script info
   * otherwise just file name
   */
  getConfigFileNameForFile(info) {
    if (isOpenScriptInfo(info)) {
      Debug.assert(info.isScriptOpen());
      const result = this.configFileForOpenFiles.get(info.path);
      if (result !== void 0)
        return result || void 0;
    }
    this.logger.info(`Search path: ${getDirectoryPath(info.fileName)}`);
    const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName2) => this.configFileExists(configFileName2, canonicalConfigFilePath, info));
    if (configFileName) {
      this.logger.info(`For info: ${info.fileName} :: Config file name: ${configFileName}`);
    } else {
      this.logger.info(`For info: ${info.fileName} :: No config files found.`);
    }
    if (isOpenScriptInfo(info)) {
      this.configFileForOpenFiles.set(info.path, configFileName || false);
    }
    return configFileName;
  }
  printProjects() {
    if (!this.logger.hasLevel(1 /* normal */)) {
      return;
    }
    this.logger.startGroup();
    this.externalProjects.forEach(printProjectWithoutFileNames);
    this.configuredProjects.forEach(printProjectWithoutFileNames);
    this.inferredProjects.forEach(printProjectWithoutFileNames);
    this.logger.info("Open files: ");
    this.openFiles.forEach((projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      this.logger.info(`	FileName: ${info.fileName} ProjectRootPath: ${projectRootPath}`);
      this.logger.info(`		Projects: ${info.containingProjects.map((p) => p.getProjectName())}`);
    });
    this.logger.endGroup();
  }
  /** @internal */
  findConfiguredProjectByProjectName(configFileName) {
    const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName));
    return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath);
  }
  getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) {
    return this.configuredProjects.get(canonicalConfigFilePath);
  }
  findExternalProjectByProjectName(projectFileName) {
    return findProjectByName(projectFileName, this.externalProjects);
  }
  /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */
  getFilenameForExceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader) {
    if (options && options.disableSizeLimit || !this.host.getFileSize) {
      return;
    }
    let availableSpace = maxProgramSizeForNonTsFiles;
    this.projectToSizeMap.set(name, 0);
    this.projectToSizeMap.forEach((val) => availableSpace -= val || 0);
    let totalNonTsFileSize = 0;
    for (const f of fileNames) {
      const fileName = propertyReader.getFileName(f);
      if (hasTSFileExtension(fileName)) {
        continue;
      }
      totalNonTsFileSize += this.host.getFileSize(fileName);
      if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
        const top5LargestFiles = fileNames.map((f2) => propertyReader.getFileName(f2)).filter((name2) => !hasTSFileExtension(name2)).map((name2) => ({ name: name2, size: this.host.getFileSize(name2) })).sort((a, b) => b.size - a.size).slice(0, 5);
        this.logger.info(`Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${top5LargestFiles.map((file) => `${file.name}:${file.size}`).join(", ")}`);
        return fileName;
      }
    }
    this.projectToSizeMap.set(name, totalNonTsFileSize);
  }
  createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles) {
    const compilerOptions = convertCompilerOptions(options);
    const watchOptionsAndErrors = convertWatchOptions(options, getDirectoryPath(normalizeSlashes(projectFileName)));
    const project = new ExternalProject2(
      projectFileName,
      this,
      this.documentRegistry,
      compilerOptions,
      /*lastFileExceededProgramSize*/
      this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader),
      options.compileOnSave === void 0 ? true : options.compileOnSave,
      /*projectFilePath*/
      void 0,
      watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions
    );
    project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors);
    project.excludedFiles = excludedFiles;
    this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
    this.externalProjects.push(project);
    return project;
  }
  /** @internal */
  sendProjectTelemetry(project) {
    if (this.seenProjects.has(project.projectName)) {
      setProjectOptionsUsed(project);
      return;
    }
    this.seenProjects.set(project.projectName, true);
    if (!this.eventHandler || !this.host.createSHA256Hash) {
      setProjectOptionsUsed(project);
      return;
    }
    const projectOptions = isConfiguredProject(project) ? project.projectOptions : void 0;
    setProjectOptionsUsed(project);
    const data = {
      projectId: this.host.createSHA256Hash(project.projectName),
      fileStats: countEachFileTypes(
        project.getScriptInfos(),
        /*includeSizes*/
        true
      ),
      compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
      typeAcquisition: convertTypeAcquisition2(project.getTypeAcquisition()),
      extends: projectOptions && projectOptions.configHasExtendsProperty,
      files: projectOptions && projectOptions.configHasFilesProperty,
      include: projectOptions && projectOptions.configHasIncludeProperty,
      exclude: projectOptions && projectOptions.configHasExcludeProperty,
      compileOnSave: project.compileOnSaveEnabled,
      configFileName: configFileName(),
      projectType: project instanceof ExternalProject2 ? "external" : "configured",
      languageServiceEnabled: project.languageServiceEnabled,
      version
    };
    this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data });
    function configFileName() {
      if (!isConfiguredProject(project)) {
        return "other";
      }
      return getBaseConfigFileName(project.getConfigFilePath()) || "other";
    }
    function convertTypeAcquisition2({ enable: enable2, include, exclude }) {
      return {
        enable: enable2,
        include: include !== void 0 && include.length !== 0,
        exclude: exclude !== void 0 && exclude.length !== 0
      };
    }
  }
  addFilesToNonInferredProject(project, files, propertyReader, typeAcquisition) {
    this.updateNonInferredProjectFiles(project, files, propertyReader);
    project.setTypeAcquisition(typeAcquisition);
  }
  /** @internal */
  createConfiguredProject(configFileName) {
    var _a;
    (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName });
    this.logger.info(`Creating configuration project ${configFileName}`);
    const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName));
    let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo) {
      this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true });
    } else {
      configFileExistenceInfo.exists = true;
    }
    if (!configFileExistenceInfo.config) {
      configFileExistenceInfo.config = {
        cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames),
        projects: /* @__PURE__ */ new Map(),
        reloadLevel: 2 /* Full */
      };
    }
    const project = new ConfiguredProject2(
      configFileName,
      canonicalConfigFilePath,
      this,
      this.documentRegistry,
      configFileExistenceInfo.config.cachedDirectoryStructureHost
    );
    this.configuredProjects.set(canonicalConfigFilePath, project);
    this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project);
    return project;
  }
  /** @internal */
  createConfiguredProjectWithDelayLoad(configFileName, reason) {
    const project = this.createConfiguredProject(configFileName);
    project.pendingReload = 2 /* Full */;
    project.pendingReloadReason = reason;
    return project;
  }
  /** @internal */
  createAndLoadConfiguredProject(configFileName, reason) {
    const project = this.createConfiguredProject(configFileName);
    this.loadConfiguredProject(project, reason);
    return project;
  }
  /** @internal */
  createLoadAndUpdateConfiguredProject(configFileName, reason) {
    const project = this.createAndLoadConfiguredProject(configFileName, reason);
    project.updateGraph();
    return project;
  }
  /**
   * Read the config file of the project, and update the project root file names.
   *
   * @internal
   */
  loadConfiguredProject(project, reason) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath });
    this.sendProjectLoadingStartEvent(project, reason);
    const configFilename = asNormalizedPath(normalizePath(project.getConfigFilePath()));
    const configFileExistenceInfo = this.ensureParsedConfigUptoDate(
      configFilename,
      project.canonicalConfigFilePath,
      this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath),
      project
    );
    const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine;
    Debug.assert(!!parsedCommandLine.fileNames);
    const compilerOptions = parsedCommandLine.options;
    if (!project.projectOptions) {
      project.projectOptions = {
        configHasExtendsProperty: parsedCommandLine.raw.extends !== void 0,
        configHasFilesProperty: parsedCommandLine.raw.files !== void 0,
        configHasIncludeProperty: parsedCommandLine.raw.include !== void 0,
        configHasExcludeProperty: parsedCommandLine.raw.exclude !== void 0
      };
    }
    project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw);
    project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics);
    project.updateReferences(parsedCommandLine.projectReferences);
    const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader);
    if (lastFileExceededProgramSize) {
      project.disableLanguageService(lastFileExceededProgramSize);
      this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.stopWatchingWildCards(canonicalConfigFilePath, project));
    } else {
      project.setCompilerOptions(compilerOptions);
      project.setWatchOptions(parsedCommandLine.watchOptions);
      project.enableLanguageService();
      this.watchWildcards(configFilename, configFileExistenceInfo, project);
    }
    project.enablePluginsWithOptions(compilerOptions);
    const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles());
    this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  /** @internal */
  ensureParsedConfigUptoDate(configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) {
    var _a, _b, _c;
    if (configFileExistenceInfo.config) {
      if (!configFileExistenceInfo.config.reloadLevel)
        return configFileExistenceInfo;
      if (configFileExistenceInfo.config.reloadLevel === 1 /* Partial */) {
        this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config);
        return configFileExistenceInfo;
      }
    }
    const cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.cachedDirectoryStructureHost) || createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames);
    const configFileContent = tryReadFile(configFilename, (fileName) => this.host.readFile(fileName));
    const configFile = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : "");
    const configFileErrors = configFile.parseDiagnostics;
    if (!isString(configFileContent))
      configFileErrors.push(configFileContent);
    const parsedCommandLine = parseJsonSourceFileConfigFileContent(
      configFile,
      cachedDirectoryStructureHost,
      getDirectoryPath(configFilename),
      /*existingOptions*/
      {},
      configFilename,
      /*resolutionStack*/
      [],
      this.hostConfiguration.extraFileExtensions,
      this.extendedConfigCache
    );
    if (parsedCommandLine.errors.length) {
      configFileErrors.push(...parsedCommandLine.errors);
    }
    this.logger.info(`Config: ${configFilename} : ${JSON.stringify(
      {
        rootNames: parsedCommandLine.fileNames,
        options: parsedCommandLine.options,
        watchOptions: parsedCommandLine.watchOptions,
        projectReferences: parsedCommandLine.projectReferences
      },
      /*replacer*/
      void 0,
      " "
    )}`);
    const oldCommandLine = (_b = configFileExistenceInfo.config) == null ? void 0 : _b.parsedCommandLine;
    if (!configFileExistenceInfo.config) {
      configFileExistenceInfo.config = { parsedCommandLine, cachedDirectoryStructureHost, projects: /* @__PURE__ */ new Map() };
    } else {
      configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine;
      configFileExistenceInfo.config.watchedDirectoriesStale = true;
      configFileExistenceInfo.config.reloadLevel = void 0;
    }
    if (!oldCommandLine && !isJsonEqual(
      // Old options
      this.getWatchOptionsFromProjectWatchOptions(
        /*projectOptions*/
        void 0
      ),
      // New options
      this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions)
    )) {
      (_c = configFileExistenceInfo.watcher) == null ? void 0 : _c.close();
      configFileExistenceInfo.watcher = void 0;
    }
    this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject);
    updateSharedExtendedConfigFileWatcher(
      canonicalConfigFilePath,
      parsedCommandLine.options,
      this.sharedExtendedConfigFileWatchers,
      (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile(
        extendedConfigFileName,
        () => {
          var _a2;
          cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, (fileName) => this.toPath(fileName));
          let ensureProjectsForOpenFiles = false;
          (_a2 = this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects.forEach((canonicalPath) => {
            ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles;
          });
          if (ensureProjectsForOpenFiles)
            this.delayEnsureProjectForOpenFiles();
        },
        2e3 /* High */,
        this.hostConfiguration.watchOptions,
        WatchType.ExtendedConfigFile,
        configFilename
      ),
      (fileName) => this.toPath(fileName)
    );
    return configFileExistenceInfo;
  }
  /** @internal */
  watchWildcards(configFileName, { exists, config }, forProject) {
    config.projects.set(forProject.canonicalConfigFilePath, true);
    if (exists) {
      if (config.watchedDirectories && !config.watchedDirectoriesStale)
        return;
      config.watchedDirectoriesStale = false;
      updateWatchingWildcardDirectories(
        config.watchedDirectories || (config.watchedDirectories = /* @__PURE__ */ new Map()),
        new Map(Object.entries(config.parsedCommandLine.wildcardDirectories)),
        // Create new directory watcher
        (directory, flags) => this.watchWildcardDirectory(directory, flags, configFileName, config)
      );
    } else {
      config.watchedDirectoriesStale = false;
      if (!config.watchedDirectories)
        return;
      clearMap(config.watchedDirectories, closeFileWatcherOf);
      config.watchedDirectories = void 0;
    }
  }
  /** @internal */
  stopWatchingWildCards(canonicalConfigFilePath, forProject) {
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo.config || !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) {
      return;
    }
    configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false);
    if (forEachEntry(configFileExistenceInfo.config.projects, identity))
      return;
    if (configFileExistenceInfo.config.watchedDirectories) {
      clearMap(configFileExistenceInfo.config.watchedDirectories, closeFileWatcherOf);
      configFileExistenceInfo.config.watchedDirectories = void 0;
    }
    configFileExistenceInfo.config.watchedDirectoriesStale = void 0;
  }
  updateNonInferredProjectFiles(project, files, propertyReader) {
    const projectRootFilesMap = project.getRootFilesMap();
    const newRootScriptInfoMap = /* @__PURE__ */ new Map();
    for (const f of files) {
      const newRootFile = propertyReader.getFileName(f);
      const fileName = toNormalizedPath(newRootFile);
      const isDynamic = isDynamicFileName(fileName);
      let path;
      if (!isDynamic && !project.fileExists(newRootFile)) {
        path = normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName);
        const existingValue = projectRootFilesMap.get(path);
        if (existingValue) {
          if (existingValue.info) {
            project.removeFile(
              existingValue.info,
              /*fileExists*/
              false,
              /*detachFromProject*/
              true
            );
            existingValue.info = void 0;
          }
          existingValue.fileName = fileName;
        } else {
          projectRootFilesMap.set(path, { fileName });
        }
      } else {
        const scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions);
        const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
        const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
          fileName,
          project.currentDirectory,
          scriptKind,
          hasMixedContent,
          project.directoryStructureHost
        ));
        path = scriptInfo.path;
        const existingValue = projectRootFilesMap.get(path);
        if (!existingValue || existingValue.info !== scriptInfo) {
          project.addRoot(scriptInfo, fileName);
          if (scriptInfo.isScriptOpen()) {
            this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo);
          }
        } else {
          existingValue.fileName = fileName;
        }
      }
      newRootScriptInfoMap.set(path, true);
    }
    if (projectRootFilesMap.size > newRootScriptInfoMap.size) {
      projectRootFilesMap.forEach((value, path) => {
        if (!newRootScriptInfoMap.has(path)) {
          if (value.info) {
            project.removeFile(
              value.info,
              project.fileExists(path),
              /*detachFromProject*/
              true
            );
          } else {
            projectRootFilesMap.delete(path);
          }
        }
      });
    }
    project.markAsDirty();
  }
  updateRootAndOptionsOfNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, watchOptions) {
    project.setCompilerOptions(newOptions);
    project.setWatchOptions(watchOptions);
    if (compileOnSave !== void 0) {
      project.compileOnSaveEnabled = compileOnSave;
    }
    this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition);
  }
  /**
   * Reload the file names from config file specs and update the project graph
   *
   * @internal
   */
  reloadFileNamesOfConfiguredProject(project) {
    const fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config);
    project.updateErrorOnNoInputFiles(fileNames);
    this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles()), fileNamePropertyReader);
    return project.updateGraph();
  }
  /** @internal */
  reloadFileNamesOfParsedConfig(configFileName, config) {
    if (config.reloadLevel === void 0)
      return config.parsedCommandLine.fileNames;
    Debug.assert(config.reloadLevel === 1 /* Partial */);
    const configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs;
    const fileNames = getFileNamesFromConfigSpecs(
      configFileSpecs,
      getDirectoryPath(configFileName),
      config.parsedCommandLine.options,
      config.cachedDirectoryStructureHost,
      this.hostConfiguration.extraFileExtensions
    );
    config.parsedCommandLine = { ...config.parsedCommandLine, fileNames };
    return fileNames;
  }
  /** @internal */
  setFileNamesOfAutoImportProviderProject(project, fileNames) {
    this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader);
  }
  /**
   * Read the config file of the project again by clearing the cache and update the project graph
   *
   * @internal
   */
  reloadConfiguredProject(project, reason, isInitialLoad, clearSemanticCache) {
    const host = project.getCachedDirectoryStructureHost();
    if (clearSemanticCache)
      this.clearSemanticCache(project);
    host.clearCache();
    const configFileName = project.getConfigFilePath();
    this.logger.info(`${isInitialLoad ? "Loading" : "Reloading"} configured project ${configFileName}`);
    this.loadConfiguredProject(project, reason);
    project.updateGraph();
    this.sendConfigFileDiagEvent(project, configFileName);
  }
  /** @internal */
  clearSemanticCache(project) {
    project.resolutionCache.clear();
    project.getLanguageService(
      /*ensureSynchronized*/
      false
    ).cleanupSemanticCache();
    project.markAsDirty();
  }
  sendConfigFileDiagEvent(project, triggerFile) {
    if (!this.eventHandler || this.suppressDiagnosticEvents) {
      return;
    }
    const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics();
    diagnostics.push(...project.getAllProjectErrors());
    this.eventHandler({
      eventName: ConfigFileDiagEvent,
      data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile }
    });
  }
  getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) {
    if (!this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root
    info.isDynamic && projectRootPath === void 0) {
      return void 0;
    }
    if (projectRootPath) {
      const canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath);
      for (const project of this.inferredProjects) {
        if (project.projectRootPath === canonicalProjectRootPath) {
          return project;
        }
      }
      return this.createInferredProject(
        projectRootPath,
        /*isSingleInferredProject*/
        false,
        projectRootPath
      );
    }
    let bestMatch;
    for (const project of this.inferredProjects) {
      if (!project.projectRootPath)
        continue;
      if (!containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames))
        continue;
      if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length)
        continue;
      bestMatch = project;
    }
    return bestMatch;
  }
  getOrCreateSingleInferredProjectIfEnabled() {
    if (!this.useSingleInferredProject) {
      return void 0;
    }
    if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === void 0) {
      return this.inferredProjects[0];
    }
    return this.createInferredProject(
      "",
      /*isSingleInferredProject*/
      true
    );
  }
  getOrCreateSingleInferredWithoutProjectRoot(currentDirectory) {
    Debug.assert(!this.useSingleInferredProject);
    const expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory));
    for (const inferredProject of this.inferredProjects) {
      if (!inferredProject.projectRootPath && inferredProject.isOrphan() && inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) {
        return inferredProject;
      }
    }
    return this.createInferredProject(currentDirectory);
  }
  createInferredProject(currentDirectory, isSingleInferredProject, projectRootPath) {
    const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects;
    let watchOptionsAndErrors;
    let typeAcquisition;
    if (projectRootPath) {
      watchOptionsAndErrors = this.watchOptionsForInferredProjectsPerProjectRoot.get(projectRootPath);
      typeAcquisition = this.typeAcquisitionForInferredProjectsPerProjectRoot.get(projectRootPath);
    }
    if (watchOptionsAndErrors === void 0) {
      watchOptionsAndErrors = this.watchOptionsForInferredProjects;
    }
    if (typeAcquisition === void 0) {
      typeAcquisition = this.typeAcquisitionForInferredProjects;
    }
    watchOptionsAndErrors = watchOptionsAndErrors || void 0;
    const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, typeAcquisition);
    project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors);
    if (isSingleInferredProject) {
      this.inferredProjects.unshift(project);
    } else {
      this.inferredProjects.push(project);
    }
    return project;
  }
  /** @internal */
  getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) {
    return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
      toNormalizedPath(uncheckedFileName),
      currentDirectory,
      /*scriptKind*/
      void 0,
      /*hasMixedContent*/
      void 0,
      hostToQueryFileExistsOn
    );
  }
  getScriptInfo(uncheckedFileName) {
    return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName));
  }
  /** @internal */
  getScriptInfoOrConfig(uncheckedFileName) {
    const path = toNormalizedPath(uncheckedFileName);
    const info = this.getScriptInfoForNormalizedPath(path);
    if (info)
      return info;
    const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
    return configProject && configProject.getCompilerOptions().configFile;
  }
  /** @internal */
  logErrorForScriptInfoNotFound(fileName) {
    const names = arrayFrom(this.filenameToScriptInfo.entries(), ([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName }));
    this.logger.msg(`Could not find file ${JSON.stringify(fileName)}.
All files are: ${JSON.stringify(names)}`, "Err" /* Err */);
  }
  /**
   * Returns the projects that contain script info through SymLink
   * Note that this does not return projects in info.containingProjects
   *
   * @internal
   */
  getSymlinkedProjects(info) {
    let projects;
    if (this.realpathToScriptInfos) {
      const realpath = info.getRealpathIfDifferent();
      if (realpath) {
        forEach(this.realpathToScriptInfos.get(realpath), combineProjects);
      }
      forEach(this.realpathToScriptInfos.get(info.path), combineProjects);
    }
    return projects;
    function combineProjects(toAddInfo) {
      if (toAddInfo !== info) {
        for (const project of toAddInfo.containingProjects) {
          if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && !info.isAttached(project)) {
            if (!projects) {
              projects = createMultiMap();
              projects.add(toAddInfo.path, project);
            } else if (!forEachEntry(projects, (projs, path) => path === toAddInfo.path ? false : contains(projs, project))) {
              projects.add(toAddInfo.path, project);
            }
          }
        }
      }
    }
  }
  watchClosedScriptInfo(info) {
    Debug.assert(!info.fileWatcher);
    if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) {
      const indexOfNodeModules = info.path.indexOf("/node_modules/");
      if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
        info.fileWatcher = this.watchFactory.watchFile(
          info.fileName,
          (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind),
          500 /* Medium */,
          this.hostConfiguration.watchOptions,
          WatchType.ClosedScriptInfo
        );
      } else {
        info.mTime = this.getModifiedTime(info);
        info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules));
      }
    }
  }
  createNodeModulesWatcher(dir) {
    const watcher = this.watchFactory.watchDirectory(
      dir,
      (fileOrDirectory) => {
        var _a;
        const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory));
        if (!fileOrDirectoryPath)
          return;
        const basename = getBaseFileName(fileOrDirectoryPath);
        if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename === "package.json" || basename === "node_modules")) {
          result.affectedModuleSpecifierCacheProjects.forEach((projectName) => {
            var _a2, _b;
            (_b = (_a2 = this.findProject(projectName)) == null ? void 0 : _a2.getModuleSpecifierCache()) == null ? void 0 : _b.clear();
          });
        }
        if (result.refreshScriptInfoRefCount) {
          if (dir === fileOrDirectoryPath) {
            this.refreshScriptInfosInDirectory(dir);
          } else {
            const info = this.getScriptInfoForPath(fileOrDirectoryPath);
            if (info) {
              if (isScriptInfoWatchedFromNodeModules(info)) {
                this.refreshScriptInfo(info);
              }
            } else if (!hasExtension(fileOrDirectoryPath)) {
              this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
            }
          }
        }
      },
      1 /* Recursive */,
      this.hostConfiguration.watchOptions,
      WatchType.NodeModules
    );
    const result = {
      refreshScriptInfoRefCount: 0,
      affectedModuleSpecifierCacheProjects: void 0,
      close: () => {
        var _a;
        if (!result.refreshScriptInfoRefCount && !((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size)) {
          watcher.close();
          this.nodeModulesWatchers.delete(dir);
        }
      }
    };
    this.nodeModulesWatchers.set(dir, result);
    return result;
  }
  /** @internal */
  watchPackageJsonsInNodeModules(dir, project) {
    const watcher = this.nodeModulesWatchers.get(dir) || this.createNodeModulesWatcher(dir);
    (watcher.affectedModuleSpecifierCacheProjects || (watcher.affectedModuleSpecifierCacheProjects = /* @__PURE__ */ new Set())).add(project.getProjectName());
    return {
      close: () => {
        var _a;
        (_a = watcher.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.delete(project.getProjectName());
        watcher.close();
      }
    };
  }
  watchClosedScriptInfoInNodeModules(dir) {
    const watchDir = dir + "/node_modules";
    const watcher = this.nodeModulesWatchers.get(watchDir) || this.createNodeModulesWatcher(watchDir);
    watcher.refreshScriptInfoRefCount++;
    return {
      close: () => {
        watcher.refreshScriptInfoRefCount--;
        watcher.close();
      }
    };
  }
  getModifiedTime(info) {
    return (this.host.getModifiedTime(info.path) || missingFileModifiedTime).getTime();
  }
  refreshScriptInfo(info) {
    const mTime = this.getModifiedTime(info);
    if (mTime !== info.mTime) {
      const eventKind = getFileWatcherEventKind(info.mTime, mTime);
      info.mTime = mTime;
      this.onSourceFileChanged(info, eventKind);
    }
  }
  refreshScriptInfosInDirectory(dir) {
    dir = dir + directorySeparator;
    this.filenameToScriptInfo.forEach((info) => {
      if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) {
        this.refreshScriptInfo(info);
      }
    });
  }
  stopWatchingScriptInfo(info) {
    if (info.fileWatcher) {
      info.fileWatcher.close();
      info.fileWatcher = void 0;
    }
  }
  getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
    if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) {
      return this.getOrCreateScriptInfoWorker(
        fileName,
        currentDirectory,
        /*openedByClient*/
        false,
        /*fileContent*/
        void 0,
        scriptKind,
        hasMixedContent,
        hostToQueryFileExistsOn
      );
    }
    const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName));
    if (info) {
      return info;
    }
    return void 0;
  }
  getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) {
    return this.getOrCreateScriptInfoWorker(
      fileName,
      currentDirectory,
      /*openedByClient*/
      true,
      fileContent,
      scriptKind,
      hasMixedContent
    );
  }
  getOrCreateScriptInfoForNormalizedPath(fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
    return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
  }
  getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
    Debug.assert(fileContent === void 0 || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content");
    const path = normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName);
    let info = this.getScriptInfoForPath(path);
    if (!info) {
      const isDynamic = isDynamicFileName(fileName);
      Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}
Script info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`);
      Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}
Open script files with non rooted disk path opened with current directory context cannot have same canonical names`);
      Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}
Dynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`);
      if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
        return;
      }
      info = new ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path));
      this.filenameToScriptInfo.set(info.path, info);
      this.filenameToScriptInfoVersion.delete(info.path);
      if (!openedByClient) {
        this.watchClosedScriptInfo(info);
      } else if (!isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) {
        this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info);
      }
    }
    if (openedByClient) {
      this.stopWatchingScriptInfo(info);
      info.open(fileContent);
      if (hasMixedContent) {
        info.registerFileUpdate();
      }
    }
    return info;
  }
  /**
   * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred
   */
  getScriptInfoForNormalizedPath(fileName) {
    return !isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || this.getScriptInfoForPath(normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName));
  }
  getScriptInfoForPath(fileName) {
    return this.filenameToScriptInfo.get(fileName);
  }
  /** @internal */
  getDocumentPositionMapper(project, generatedFileName, sourceFileName) {
    const declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host);
    if (!declarationInfo) {
      if (sourceFileName) {
        project.addGeneratedFileWatch(generatedFileName, sourceFileName);
      }
      return void 0;
    }
    declarationInfo.getSnapshot();
    if (isString(declarationInfo.sourceMapFilePath)) {
      const sourceMapFileInfo2 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
      if (sourceMapFileInfo2) {
        sourceMapFileInfo2.getSnapshot();
        if (sourceMapFileInfo2.documentPositionMapper !== void 0) {
          sourceMapFileInfo2.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo2.sourceInfos);
          return sourceMapFileInfo2.documentPositionMapper ? sourceMapFileInfo2.documentPositionMapper : void 0;
        }
      }
      declarationInfo.sourceMapFilePath = void 0;
    } else if (declarationInfo.sourceMapFilePath) {
      declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos);
      return void 0;
    } else if (declarationInfo.sourceMapFilePath !== void 0) {
      return void 0;
    }
    let sourceMapFileInfo;
    let mapFileNameFromDeclarationInfo;
    let readMapFile = (mapFileName, mapFileNameFromDts) => {
      const mapInfo = this.getOrCreateScriptInfoNotOpenedByClient(mapFileName, project.currentDirectory, this.host);
      if (!mapInfo) {
        mapFileNameFromDeclarationInfo = mapFileNameFromDts;
        return void 0;
      }
      sourceMapFileInfo = mapInfo;
      const snap = mapInfo.getSnapshot();
      if (mapInfo.documentPositionMapper !== void 0)
        return mapInfo.documentPositionMapper;
      return getSnapshotText(snap);
    };
    const projectName = project.projectName;
    const documentPositionMapper = getDocumentPositionMapper(
      { getCanonicalFileName: this.toCanonicalFileName, log: (s) => this.logger.info(s), getSourceFileLike: (f) => this.getSourceFileLike(f, projectName, declarationInfo) },
      declarationInfo.fileName,
      declarationInfo.textStorage.getLineInfo(),
      readMapFile
    );
    readMapFile = void 0;
    if (sourceMapFileInfo) {
      declarationInfo.sourceMapFilePath = sourceMapFileInfo.path;
      sourceMapFileInfo.declarationInfoPath = declarationInfo.path;
      sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false;
      sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos);
    } else if (mapFileNameFromDeclarationInfo) {
      declarationInfo.sourceMapFilePath = {
        watcher: this.addMissingSourceMapFile(
          project.currentDirectory === this.currentDirectory ? mapFileNameFromDeclarationInfo : getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory),
          declarationInfo.path
        ),
        sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project)
      };
    } else {
      declarationInfo.sourceMapFilePath = false;
    }
    return documentPositionMapper;
  }
  addSourceInfoToSourceMap(sourceFileName, project, sourceInfos) {
    if (sourceFileName) {
      const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost);
      (sourceInfos || (sourceInfos = /* @__PURE__ */ new Set())).add(sourceInfo.path);
    }
    return sourceInfos;
  }
  addMissingSourceMapFile(mapFileName, declarationInfoPath) {
    const fileWatcher = this.watchFactory.watchFile(
      mapFileName,
      () => {
        const declarationInfo = this.getScriptInfoForPath(declarationInfoPath);
        if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) {
          this.delayUpdateProjectGraphs(
            declarationInfo.containingProjects,
            /*clearSourceMapperCache*/
            true
          );
          this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos);
          declarationInfo.closeSourceMapFileWatcher();
        }
      },
      2e3 /* High */,
      this.hostConfiguration.watchOptions,
      WatchType.MissingSourceMapFile
    );
    return fileWatcher;
  }
  /** @internal */
  getSourceFileLike(fileName, projectNameOrProject, declarationInfo) {
    const project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject);
    if (project) {
      const path = project.toPath(fileName);
      const sourceFile = project.getSourceFile(path);
      if (sourceFile && sourceFile.resolvedPath === path)
        return sourceFile;
    }
    const info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host);
    if (!info)
      return void 0;
    if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
      const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
      if (sourceMapInfo) {
        (sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = /* @__PURE__ */ new Set())).add(info.path);
      }
    }
    if (info.cacheSourceFile)
      return info.cacheSourceFile.sourceFile;
    if (!info.sourceFileLike) {
      info.sourceFileLike = {
        get text() {
          Debug.fail("shouldnt need text");
          return "";
        },
        getLineAndCharacterOfPosition: (pos) => {
          const lineOffset = info.positionToLineOffset(pos);
          return { line: lineOffset.line - 1, character: lineOffset.offset - 1 };
        },
        getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits)
      };
    }
    return info.sourceFileLike;
  }
  /** @internal */
  setPerformanceEventHandler(performanceEventHandler) {
    this.performanceEventHandler = performanceEventHandler;
  }
  setHostConfiguration(args) {
    var _a;
    if (args.file) {
      const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file));
      if (info) {
        info.setOptions(convertFormatOptions(args.formatOptions), args.preferences);
        this.logger.info(`Host configuration update for file ${args.file}`);
      }
    } else {
      if (args.hostInfo !== void 0) {
        this.hostConfiguration.hostInfo = args.hostInfo;
        this.logger.info(`Host information ${args.hostInfo}`);
      }
      if (args.formatOptions) {
        this.hostConfiguration.formatCodeOptions = { ...this.hostConfiguration.formatCodeOptions, ...convertFormatOptions(args.formatOptions) };
        this.logger.info("Format host information updated");
      }
      if (args.preferences) {
        const {
          lazyConfiguredProjectsFromExternalProject,
          includePackageJsonAutoImports
        } = this.hostConfiguration.preferences;
        this.hostConfiguration.preferences = { ...this.hostConfiguration.preferences, ...args.preferences };
        if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
          this.configuredProjects.forEach((project) => {
            if (project.hasExternalProjectRef() && project.pendingReload === 2 /* Full */ && !this.pendingProjectUpdates.has(project.getProjectName())) {
              project.updateGraph();
            }
          });
        }
        if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) {
          this.invalidateProjectPackageJson(
            /*packageJsonPath*/
            void 0
          );
        }
      }
      if (args.extraFileExtensions) {
        this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
        this.reloadProjects();
        this.logger.info("Host file extension mappings updated");
      }
      if (args.watchOptions) {
        this.hostConfiguration.watchOptions = (_a = convertWatchOptions(args.watchOptions)) == null ? void 0 : _a.watchOptions;
        this.logger.info(`Host watch options changed to ${JSON.stringify(this.hostConfiguration.watchOptions)}, it will be take effect for next watches.`);
      }
    }
  }
  /** @internal */
  getWatchOptions(project) {
    return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions());
  }
  /** @internal */
  getWatchOptionsFromProjectWatchOptions(projectOptions) {
    return projectOptions && this.hostConfiguration.watchOptions ? { ...this.hostConfiguration.watchOptions, ...projectOptions } : projectOptions || this.hostConfiguration.watchOptions;
  }
  closeLog() {
    this.logger.close();
  }
  /**
   * This function rebuilds the project for every file opened by the client
   * This does not reload contents of open files from disk. But we could do that if needed
   */
  reloadProjects() {
    this.logger.info("reload projects.");
    this.filenameToScriptInfo.forEach((info) => {
      if (this.openFiles.has(info.path))
        return;
      if (!info.fileWatcher)
        return;
      this.onSourceFileChanged(info, this.host.fileExists(info.fileName) ? 1 /* Changed */ : 2 /* Deleted */);
    });
    this.pendingProjectUpdates.forEach((_project, projectName) => {
      this.throttledOperations.cancel(projectName);
      this.pendingProjectUpdates.delete(projectName);
    });
    this.throttledOperations.cancel(ensureProjectForOpenFileSchedule);
    this.pendingEnsureProjectForOpenFiles = false;
    this.configFileExistenceInfoCache.forEach((info) => {
      if (info.config)
        info.config.reloadLevel = 2 /* Full */;
    });
    this.reloadConfiguredProjectForFiles(
      this.openFiles,
      /*clearSemanticCache*/
      true,
      /*delayReload*/
      false,
      returnTrue,
      "User requested reload projects"
    );
    this.externalProjects.forEach((project) => {
      this.clearSemanticCache(project);
      project.updateGraph();
    });
    this.inferredProjects.forEach((project) => this.clearSemanticCache(project));
    this.ensureProjectForOpenFiles();
  }
  /**
   * This function goes through all the openFiles and tries to file the config file for them.
   * If the config file is found and it refers to existing project, it reloads it either immediately
   * or schedules it for reload depending on delayReload option
   * If there is no existing project it just opens the configured project for the config file
   * reloadForInfo provides a way to filter out files to reload configured project for
   */
  reloadConfiguredProjectForFiles(openFiles, clearSemanticCache, delayReload, shouldReloadProjectFor, reason) {
    const updatedProjects = /* @__PURE__ */ new Map();
    const reloadChildProject = (child) => {
      if (!updatedProjects.has(child.canonicalConfigFilePath)) {
        updatedProjects.set(child.canonicalConfigFilePath, true);
        this.reloadConfiguredProject(
          child,
          reason,
          /*isInitialLoad*/
          false,
          clearSemanticCache
        );
      }
    };
    openFiles == null ? void 0 : openFiles.forEach((openFileValue, path) => {
      this.configFileForOpenFiles.delete(path);
      if (!shouldReloadProjectFor(openFileValue)) {
        return;
      }
      const info = this.getScriptInfoForPath(path);
      Debug.assert(info.isScriptOpen());
      const configFileName = this.getConfigFileNameForFile(info);
      if (configFileName) {
        const project = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName);
        if (!updatedProjects.has(project.canonicalConfigFilePath)) {
          updatedProjects.set(project.canonicalConfigFilePath, true);
          if (delayReload) {
            project.pendingReload = 2 /* Full */;
            project.pendingReloadReason = reason;
            if (clearSemanticCache)
              this.clearSemanticCache(project);
            this.delayUpdateProjectGraph(project);
          } else {
            this.reloadConfiguredProject(
              project,
              reason,
              /*isInitialLoad*/
              false,
              clearSemanticCache
            );
            if (!projectContainsInfoDirectly(project, info)) {
              const referencedProject = forEachResolvedProjectReferenceProject(
                project,
                info.path,
                (child) => {
                  reloadChildProject(child);
                  return projectContainsInfoDirectly(child, info);
                },
                1 /* FindCreate */
              );
              if (referencedProject) {
                forEachResolvedProjectReferenceProject(
                  project,
                  /*fileName*/
                  void 0,
                  reloadChildProject,
                  0 /* Find */
                );
              }
            }
          }
        }
      }
    });
  }
  /**
   * Remove the root of inferred project if script info is part of another project
   */
  removeRootOfInferredProjectIfNowPartOfOtherProject(info) {
    Debug.assert(info.containingProjects.length > 0);
    const firstProject = info.containingProjects[0];
    if (!firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && forEach(info.containingProjects, (p) => p !== firstProject && !p.isOrphan())) {
      firstProject.removeFile(
        info,
        /*fileExists*/
        true,
        /*detachFromProject*/
        true
      );
    }
  }
  /**
   * This function is to update the project structure for every inferred project.
   * It is called on the premise that all the configured projects are
   * up to date.
   * This will go through open files and assign them to inferred project if open file is not part of any other project
   * After that all the inferred project graphs are updated
   */
  ensureProjectForOpenFiles() {
    this.logger.info("Before ensureProjectForOpenFiles:");
    this.printProjects();
    this.openFiles.forEach((projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      if (info.isOrphan()) {
        this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
      } else {
        this.removeRootOfInferredProjectIfNowPartOfOtherProject(info);
      }
    });
    this.pendingEnsureProjectForOpenFiles = false;
    this.inferredProjects.forEach(updateProjectIfDirty);
    this.logger.info("After ensureProjectForOpenFiles:");
    this.printProjects();
  }
  /**
   * Open file whose contents is managed by the client
   * @param filename is absolute pathname
   * @param fileContent is a known version of the file content that is more up to date than the one on disk
   */
  openClientFile(fileName, fileContent, scriptKind, projectRootPath) {
    return this.openClientFileWithNormalizedPath(
      toNormalizedPath(fileName),
      fileContent,
      scriptKind,
      /*hasMixedContent*/
      false,
      projectRootPath ? toNormalizedPath(projectRootPath) : void 0
    );
  }
  /** @internal */
  getOriginalLocationEnsuringConfiguredProject(project, location) {
    const isSourceOfProjectReferenceRedirect = project.isSourceOfProjectReferenceRedirect(location.fileName);
    const originalLocation = isSourceOfProjectReferenceRedirect ? location : project.getSourceMapper().tryGetSourcePosition(location);
    if (!originalLocation)
      return void 0;
    const { fileName } = originalLocation;
    const scriptInfo = this.getScriptInfo(fileName);
    if (!scriptInfo && !this.host.fileExists(fileName))
      return void 0;
    const originalFileInfo = { fileName: toNormalizedPath(fileName), path: this.toPath(fileName) };
    const configFileName = this.getConfigFileNameForFile(originalFileInfo);
    if (!configFileName)
      return void 0;
    let configuredProject = this.findConfiguredProjectByProjectName(configFileName);
    if (!configuredProject) {
      if (project.getCompilerOptions().disableReferencedProjectLoad) {
        if (isSourceOfProjectReferenceRedirect) {
          return location;
        }
        return (scriptInfo == null ? void 0 : scriptInfo.containingProjects.length) ? originalLocation : location;
      }
      configuredProject = this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`);
    }
    updateProjectIfDirty(configuredProject);
    const projectContainsOriginalInfo = (project2) => {
      const info = this.getScriptInfo(fileName);
      return info && projectContainsInfoDirectly(project2, info);
    };
    if (configuredProject.isSolution() || !projectContainsOriginalInfo(configuredProject)) {
      configuredProject = forEachResolvedProjectReferenceProject(
        configuredProject,
        fileName,
        (child) => {
          updateProjectIfDirty(child);
          return projectContainsOriginalInfo(child) ? child : void 0;
        },
        2 /* FindCreateLoad */,
        `Creating project referenced in solution ${configuredProject.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`
      );
      if (!configuredProject)
        return void 0;
      if (configuredProject === project)
        return originalLocation;
    }
    addOriginalConfiguredProject(configuredProject);
    const originalScriptInfo = this.getScriptInfo(fileName);
    if (!originalScriptInfo || !originalScriptInfo.containingProjects.length)
      return void 0;
    originalScriptInfo.containingProjects.forEach((project2) => {
      if (isConfiguredProject(project2)) {
        addOriginalConfiguredProject(project2);
      }
    });
    return originalLocation;
    function addOriginalConfiguredProject(originalProject) {
      if (!project.originalConfiguredProjects) {
        project.originalConfiguredProjects = /* @__PURE__ */ new Set();
      }
      project.originalConfiguredProjects.add(originalProject.canonicalConfigFilePath);
    }
  }
  /** @internal */
  fileExists(fileName) {
    return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName);
  }
  findExternalProjectContainingOpenScriptInfo(info) {
    return find(this.externalProjects, (proj) => {
      updateProjectIfDirty(proj);
      return proj.containsScriptInfo(info);
    });
  }
  getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
    const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent);
    this.openFiles.set(info.path, projectRootPath);
    return info;
  }
  assignProjectToOpenedScriptInfo(info) {
    let configFileName;
    let configFileErrors;
    let project = this.findExternalProjectContainingOpenScriptInfo(info);
    let retainProjects;
    let projectForConfigFileDiag;
    let defaultConfigProjectIsCreated = false;
    if (!project && this.serverMode === 0 /* Semantic */) {
      configFileName = this.getConfigFileNameForFile(info);
      if (configFileName) {
        project = this.findConfiguredProjectByProjectName(configFileName);
        if (!project) {
          project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${info.fileName} to open`);
          defaultConfigProjectIsCreated = true;
        } else {
          updateProjectIfDirty(project);
        }
        projectForConfigFileDiag = project.containsScriptInfo(info) ? project : void 0;
        retainProjects = project;
        if (!projectContainsInfoDirectly(project, info)) {
          forEachResolvedProjectReferenceProject(
            project,
            info.path,
            (child) => {
              updateProjectIfDirty(child);
              if (!isArray(retainProjects)) {
                retainProjects = [project, child];
              } else {
                retainProjects.push(child);
              }
              if (projectContainsInfoDirectly(child, info)) {
                projectForConfigFileDiag = child;
                return child;
              }
              if (!projectForConfigFileDiag && child.containsScriptInfo(info)) {
                projectForConfigFileDiag = child;
              }
            },
            2 /* FindCreateLoad */,
            `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open`
          );
        }
        if (projectForConfigFileDiag) {
          configFileName = projectForConfigFileDiag.getConfigFilePath();
          if (projectForConfigFileDiag !== project || defaultConfigProjectIsCreated) {
            configFileErrors = projectForConfigFileDiag.getAllProjectErrors();
            this.sendConfigFileDiagEvent(projectForConfigFileDiag, info.fileName);
          }
        } else {
          configFileName = void 0;
        }
        this.createAncestorProjects(info, project);
      }
    }
    info.containingProjects.forEach(updateProjectIfDirty);
    if (info.isOrphan()) {
      if (isArray(retainProjects)) {
        retainProjects.forEach((project2) => this.sendConfigFileDiagEvent(project2, info.fileName));
      } else if (retainProjects) {
        this.sendConfigFileDiagEvent(retainProjects, info.fileName);
      }
      Debug.assert(this.openFiles.has(info.path));
      this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
    }
    Debug.assert(!info.isOrphan());
    return { configFileName, configFileErrors, retainProjects };
  }
  createAncestorProjects(info, project) {
    if (!info.isAttached(project))
      return;
    while (true) {
      if (!project.isInitialLoadPending() && (!project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching))
        return;
      const configFileName = this.getConfigFileNameForFile({
        fileName: project.getConfigFilePath(),
        path: info.path,
        configFileInfo: true
      });
      if (!configFileName)
        return;
      const ancestor = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProjectWithDelayLoad(configFileName, `Creating project possibly referencing default composite project ${project.getProjectName()} of open file ${info.fileName}`);
      if (ancestor.isInitialLoadPending()) {
        ancestor.setPotentialProjectReference(project.canonicalConfigFilePath);
      }
      project = ancestor;
    }
  }
  /** @internal */
  loadAncestorProjectTree(forProjects) {
    forProjects = forProjects || mapDefinedEntries(
      this.configuredProjects,
      (key, project) => !project.isInitialLoadPending() ? [key, true] : void 0
    );
    const seenProjects = /* @__PURE__ */ new Set();
    for (const project of arrayFrom(this.configuredProjects.values())) {
      if (forEachPotentialProjectReference(project, (potentialRefPath) => forProjects.has(potentialRefPath))) {
        updateProjectIfDirty(project);
      }
      this.ensureProjectChildren(project, forProjects, seenProjects);
    }
  }
  ensureProjectChildren(project, forProjects, seenProjects) {
    var _a;
    if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath))
      return;
    if (project.getCompilerOptions().disableReferencedProjectLoad)
      return;
    const children = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences();
    if (!children)
      return;
    for (const child of children) {
      if (!child)
        continue;
      const referencedProject = forEachResolvedProjectReference(child.references, (ref) => forProjects.has(ref.sourceFile.path) ? ref : void 0);
      if (!referencedProject)
        continue;
      const configFileName = toNormalizedPath(child.sourceFile.fileName);
      const childProject = project.projectService.findConfiguredProjectByProjectName(configFileName) || project.projectService.createAndLoadConfiguredProject(configFileName, `Creating project referenced by : ${project.projectName} as it references project ${referencedProject.sourceFile.fileName}`);
      updateProjectIfDirty(childProject);
      this.ensureProjectChildren(childProject, forProjects, seenProjects);
    }
  }
  cleanupAfterOpeningFile(toRetainConfigProjects) {
    this.removeOrphanConfiguredProjects(toRetainConfigProjects);
    for (const inferredProject of this.inferredProjects.slice()) {
      if (inferredProject.isOrphan()) {
        this.removeProject(inferredProject);
      }
    }
    this.removeOrphanScriptInfos();
  }
  openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
    const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
    const { retainProjects, ...result } = this.assignProjectToOpenedScriptInfo(info);
    this.cleanupAfterOpeningFile(retainProjects);
    this.telemetryOnOpenFile(info);
    this.printProjects();
    return result;
  }
  removeOrphanConfiguredProjects(toRetainConfiguredProjects) {
    const toRemoveConfiguredProjects = new Map(this.configuredProjects);
    const markOriginalProjectsAsUsed = (project) => {
      if (!project.isOrphan() && project.originalConfiguredProjects) {
        project.originalConfiguredProjects.forEach(
          (_value, configuredProjectPath) => {
            const project2 = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath);
            return project2 && retainConfiguredProject(project2);
          }
        );
      }
    };
    if (toRetainConfiguredProjects) {
      if (isArray(toRetainConfiguredProjects)) {
        toRetainConfiguredProjects.forEach(retainConfiguredProject);
      } else {
        retainConfiguredProject(toRetainConfiguredProjects);
      }
    }
    this.inferredProjects.forEach(markOriginalProjectsAsUsed);
    this.externalProjects.forEach(markOriginalProjectsAsUsed);
    this.configuredProjects.forEach((project) => {
      if (project.hasOpenRef()) {
        retainConfiguredProject(project);
      } else if (toRemoveConfiguredProjects.has(project.canonicalConfigFilePath)) {
        forEachReferencedProject(
          project,
          (ref) => isRetained(ref) && retainConfiguredProject(project)
        );
      }
    });
    toRemoveConfiguredProjects.forEach((project) => this.removeProject(project));
    function isRetained(project) {
      return project.hasOpenRef() || !toRemoveConfiguredProjects.has(project.canonicalConfigFilePath);
    }
    function retainConfiguredProject(project) {
      if (toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath)) {
        markOriginalProjectsAsUsed(project);
        forEachReferencedProject(project, retainConfiguredProject);
      }
    }
  }
  removeOrphanScriptInfos() {
    const toRemoveScriptInfos = new Map(this.filenameToScriptInfo);
    this.filenameToScriptInfo.forEach((info) => {
      if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByBackgroundProject()) {
        if (!info.sourceMapFilePath)
          return;
        let sourceInfos;
        if (isString(info.sourceMapFilePath)) {
          const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
          sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
        } else {
          sourceInfos = info.sourceMapFilePath.sourceInfos;
        }
        if (!sourceInfos)
          return;
        if (!forEachKey(sourceInfos, (path) => {
          const info2 = this.getScriptInfoForPath(path);
          return !!info2 && (info2.isScriptOpen() || !info2.isOrphan());
        })) {
          return;
        }
      }
      toRemoveScriptInfos.delete(info.path);
      if (info.sourceMapFilePath) {
        let sourceInfos;
        if (isString(info.sourceMapFilePath)) {
          toRemoveScriptInfos.delete(info.sourceMapFilePath);
          const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
          sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
        } else {
          sourceInfos = info.sourceMapFilePath.sourceInfos;
        }
        if (sourceInfos) {
          sourceInfos.forEach((_value, path) => toRemoveScriptInfos.delete(path));
        }
      }
    });
    toRemoveScriptInfos.forEach((info) => {
      this.stopWatchingScriptInfo(info);
      this.deleteScriptInfo(info);
      info.closeSourceMapFileWatcher();
    });
  }
  telemetryOnOpenFile(scriptInfo) {
    if (this.serverMode !== 0 /* Semantic */ || !this.eventHandler || !scriptInfo.isJavaScript() || !addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) {
      return;
    }
    const project = this.ensureDefaultProjectForFile(scriptInfo);
    if (!project.languageServiceEnabled) {
      return;
    }
    const sourceFile = project.getSourceFile(scriptInfo.path);
    const checkJs = !!sourceFile && !!sourceFile.checkJsDirective;
    this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info: { checkJs } } });
  }
  closeClientFile(uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
    const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName));
    const result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
    if (!skipAssignOrphanScriptInfosToInferredProject) {
      this.printProjects();
    }
    return result;
  }
  collectChanges(lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) {
    for (const proj of currentProjects) {
      const knownProject = find(lastKnownProjectVersions, (p) => p.projectName === proj.getProjectName());
      result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo));
    }
  }
  /** @internal */
  synchronizeProjectList(knownProjects, includeProjectReferenceRedirectInfo) {
    const files = [];
    this.collectChanges(knownProjects, this.externalProjects, includeProjectReferenceRedirectInfo, files);
    this.collectChanges(knownProjects, this.configuredProjects.values(), includeProjectReferenceRedirectInfo, files);
    this.collectChanges(knownProjects, this.inferredProjects, includeProjectReferenceRedirectInfo, files);
    return files;
  }
  /** @internal */
  applyChangesInOpenFiles(openFiles, changedFiles, closedFiles) {
    let openScriptInfos;
    let assignOrphanScriptInfosToInferredProject = false;
    if (openFiles) {
      for (const file of openFiles) {
        const info = this.getOrCreateOpenScriptInfo(
          toNormalizedPath(file.fileName),
          file.content,
          tryConvertScriptKindName(file.scriptKind),
          file.hasMixedContent,
          file.projectRootPath ? toNormalizedPath(file.projectRootPath) : void 0
        );
        (openScriptInfos || (openScriptInfos = [])).push(info);
      }
    }
    if (changedFiles) {
      for (const file of changedFiles) {
        const scriptInfo = this.getScriptInfo(file.fileName);
        Debug.assert(!!scriptInfo);
        this.applyChangesToFile(scriptInfo, file.changes);
      }
    }
    if (closedFiles) {
      for (const file of closedFiles) {
        assignOrphanScriptInfosToInferredProject = this.closeClientFile(
          file,
          /*skipAssignOrphanScriptInfosToInferredProject*/
          true
        ) || assignOrphanScriptInfosToInferredProject;
      }
    }
    let retainProjects;
    if (openScriptInfos) {
      retainProjects = flatMap(openScriptInfos, (info) => this.assignProjectToOpenedScriptInfo(info).retainProjects);
    }
    if (assignOrphanScriptInfosToInferredProject) {
      this.assignOrphanScriptInfosToInferredProject();
    }
    if (openScriptInfos) {
      this.cleanupAfterOpeningFile(retainProjects);
      openScriptInfos.forEach((info) => this.telemetryOnOpenFile(info));
      this.printProjects();
    } else if (length(closedFiles)) {
      this.printProjects();
    }
  }
  /** @internal */
  applyChangesToFile(scriptInfo, changes) {
    for (const change of changes) {
      scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
    }
  }
  closeConfiguredProjectReferencedFromExternalProject(configFile) {
    const configuredProject = this.findConfiguredProjectByProjectName(configFile);
    if (configuredProject) {
      configuredProject.deleteExternalProjectReference();
      if (!configuredProject.hasOpenRef()) {
        this.removeProject(configuredProject);
        return;
      }
    }
  }
  closeExternalProject(uncheckedFileName) {
    const fileName = toNormalizedPath(uncheckedFileName);
    const configFiles = this.externalProjectToConfiguredProjectMap.get(fileName);
    if (configFiles) {
      for (const configFile of configFiles) {
        this.closeConfiguredProjectReferencedFromExternalProject(configFile);
      }
      this.externalProjectToConfiguredProjectMap.delete(fileName);
    } else {
      const externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
      if (externalProject) {
        this.removeProject(externalProject);
      }
    }
  }
  openExternalProjects(projects) {
    const projectsToClose = arrayToMap(this.externalProjects, (p) => p.getProjectName(), (_) => true);
    forEachKey(this.externalProjectToConfiguredProjectMap, (externalProjectName) => {
      projectsToClose.set(externalProjectName, true);
    });
    for (const externalProject of projects) {
      this.openExternalProject(externalProject);
      projectsToClose.delete(externalProject.projectFileName);
    }
    forEachKey(projectsToClose, (externalProjectName) => {
      this.closeExternalProject(externalProjectName);
    });
  }
  static escapeFilenameForRegex(filename) {
    return filename.replace(this.filenameEscapeRegexp, "\\$&");
  }
  resetSafeList() {
    this.safelist = defaultTypeSafeList;
  }
  applySafeList(proj) {
    const { rootFiles } = proj;
    const typeAcquisition = proj.typeAcquisition;
    Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now");
    if (typeAcquisition.enable === false || typeAcquisition.disableFilenameBasedTypeAcquisition) {
      return [];
    }
    const typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []);
    const excludeRules = [];
    const normalizedNames = rootFiles.map((f) => normalizeSlashes(f.fileName));
    const excludedFiles = [];
    for (const name of Object.keys(this.safelist)) {
      const rule2 = this.safelist[name];
      for (const root of normalizedNames) {
        if (rule2.match.test(root)) {
          this.logger.info(`Excluding files based on rule ${name} matching file '${root}'`);
          if (rule2.types) {
            for (const type of rule2.types) {
              if (typeAcqInclude.indexOf(type) < 0) {
                typeAcqInclude.push(type);
              }
            }
          }
          if (rule2.exclude) {
            for (const exclude of rule2.exclude) {
              const processedRule = root.replace(rule2.match, (...groups) => {
                return exclude.map((groupNumberOrString) => {
                  if (typeof groupNumberOrString === "number") {
                    if (!isString(groups[groupNumberOrString])) {
                      this.logger.info(`Incorrect RegExp specification in safelist rule ${name} - not enough groups`);
                      return "\\*";
                    }
                    return _ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]);
                  }
                  return groupNumberOrString;
                }).join("");
              });
              if (excludeRules.indexOf(processedRule) === -1) {
                excludeRules.push(processedRule);
              }
            }
          } else {
            const escaped = _ProjectService.escapeFilenameForRegex(root);
            if (excludeRules.indexOf(escaped) < 0) {
              excludeRules.push(escaped);
            }
          }
        }
      }
    }
    const excludeRegexes = excludeRules.map((e) => new RegExp(e, "i"));
    const filesToKeep = [];
    for (let i = 0; i < proj.rootFiles.length; i++) {
      if (excludeRegexes.some((re) => re.test(normalizedNames[i]))) {
        excludedFiles.push(normalizedNames[i]);
      } else {
        let exclude = false;
        if (typeAcquisition.enable) {
          const baseName = getBaseFileName(toFileNameLowerCase(normalizedNames[i]));
          if (fileExtensionIs(baseName, "js")) {
            const inferredTypingName = removeFileExtension(baseName);
            const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName);
            const typeName = this.legacySafelist.get(cleanedTypingName);
            if (typeName !== void 0) {
              this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`);
              excludedFiles.push(normalizedNames[i]);
              exclude = true;
              if (typeAcqInclude.indexOf(typeName) < 0) {
                typeAcqInclude.push(typeName);
              }
            }
          }
        }
        if (!exclude) {
          if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) {
            excludedFiles.push(normalizedNames[i]);
          } else {
            filesToKeep.push(proj.rootFiles[i]);
          }
        }
      }
    }
    proj.rootFiles = filesToKeep;
    return excludedFiles;
  }
  openExternalProject(proj) {
    proj.typeAcquisition = proj.typeAcquisition || {};
    proj.typeAcquisition.include = proj.typeAcquisition.include || [];
    proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || [];
    if (proj.typeAcquisition.enable === void 0) {
      proj.typeAcquisition.enable = hasNoTypeScriptSource(proj.rootFiles.map((f) => f.fileName));
    }
    const excludedFiles = this.applySafeList(proj);
    let tsConfigFiles;
    const rootFiles = [];
    for (const file of proj.rootFiles) {
      const normalized = toNormalizedPath(file.fileName);
      if (getBaseConfigFileName(normalized)) {
        if (this.serverMode === 0 /* Semantic */ && this.host.fileExists(normalized)) {
          (tsConfigFiles || (tsConfigFiles = [])).push(normalized);
        }
      } else {
        rootFiles.push(file);
      }
    }
    if (tsConfigFiles) {
      tsConfigFiles.sort();
    }
    const externalProject = this.findExternalProjectByProjectName(proj.projectFileName);
    let exisingConfigFiles;
    if (externalProject) {
      externalProject.excludedFiles = excludedFiles;
      if (!tsConfigFiles) {
        const compilerOptions = convertCompilerOptions(proj.options);
        const watchOptionsAndErrors = convertWatchOptions(proj.options, externalProject.getCurrentDirectory());
        const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, proj.rootFiles, externalFilePropertyReader);
        if (lastFileExceededProgramSize) {
          externalProject.disableLanguageService(lastFileExceededProgramSize);
        } else {
          externalProject.enableLanguageService();
        }
        externalProject.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors);
        this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions);
        externalProject.updateGraph();
        return;
      }
      this.closeExternalProject(proj.projectFileName);
    } else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) {
      if (!tsConfigFiles) {
        this.closeExternalProject(proj.projectFileName);
      } else {
        const oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName);
        let iNew = 0;
        let iOld = 0;
        while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) {
          const newConfig = tsConfigFiles[iNew];
          const oldConfig = oldConfigFiles[iOld];
          if (oldConfig < newConfig) {
            this.closeConfiguredProjectReferencedFromExternalProject(oldConfig);
            iOld++;
          } else if (oldConfig > newConfig) {
            iNew++;
          } else {
            (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig);
            iOld++;
            iNew++;
          }
        }
        for (let i = iOld; i < oldConfigFiles.length; i++) {
          this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]);
        }
      }
    }
    if (tsConfigFiles) {
      this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles);
      for (const tsconfigFile of tsConfigFiles) {
        let project = this.findConfiguredProjectByProjectName(tsconfigFile);
        if (!project) {
          project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? this.createConfiguredProjectWithDelayLoad(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`) : this.createLoadAndUpdateConfiguredProject(tsconfigFile, `Creating configured project in external project: ${proj.projectFileName}`);
        }
        if (project && !contains(exisingConfigFiles, tsconfigFile)) {
          project.addExternalProjectReference();
        }
      }
    } else {
      this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName);
      const project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
      project.updateGraph();
    }
  }
  hasDeferredExtension() {
    for (const extension of this.hostConfiguration.extraFileExtensions) {
      if (extension.scriptKind === 7 /* Deferred */) {
        return true;
      }
    }
    return false;
  }
  /**
   * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously
   * @internal
   */
  requestEnablePlugin(project, pluginConfigEntry, searchPaths) {
    if (!this.host.importPlugin && !this.host.require) {
      this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
      return;
    }
    this.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`);
    if (!pluginConfigEntry.name || parsePackageName(pluginConfigEntry.name).rest) {
      this.logger.info(`Skipped loading plugin ${pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)} because only package name is allowed plugin name`);
      return;
    }
    if (this.host.importPlugin) {
      const importPromise = Project3.importServicePluginAsync(
        pluginConfigEntry,
        searchPaths,
        this.host,
        (s) => this.logger.info(s)
      );
      this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map());
      let promises = this.pendingPluginEnablements.get(project);
      if (!promises)
        this.pendingPluginEnablements.set(project, promises = []);
      promises.push(importPromise);
      return;
    }
    this.endEnablePlugin(project, Project3.importServicePluginSync(
      pluginConfigEntry,
      searchPaths,
      this.host,
      (s) => this.logger.info(s)
    ));
  }
  /**
   * Performs the remaining steps of enabling a plugin after its module has been instantiated.
   * @internal
   */
  endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) {
    var _a;
    if (resolvedModule) {
      const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name);
      if (configurationOverride) {
        const pluginName = pluginConfigEntry.name;
        pluginConfigEntry = configurationOverride;
        pluginConfigEntry.name = pluginName;
      }
      project.enableProxy(resolvedModule, pluginConfigEntry);
    } else {
      forEach(errorLogs, (message) => this.logger.info(message));
      this.logger.info(`Couldn't find ${pluginConfigEntry.name}`);
    }
  }
  /** @internal */
  hasNewPluginEnablementRequests() {
    return !!this.pendingPluginEnablements;
  }
  /** @internal */
  hasPendingPluginEnablements() {
    return !!this.currentPluginEnablementPromise;
  }
  /**
   * Waits for any ongoing plugin enablement requests to complete.
   *
   * @internal
   */
  async waitForPendingPlugins() {
    while (this.currentPluginEnablementPromise) {
      await this.currentPluginEnablementPromise;
    }
  }
  /**
   * Starts enabling any requested plugins without waiting for the result.
   *
   * @internal
   */
  enableRequestedPlugins() {
    if (this.pendingPluginEnablements) {
      void this.enableRequestedPluginsAsync();
    }
  }
  async enableRequestedPluginsAsync() {
    if (this.currentPluginEnablementPromise) {
      await this.waitForPendingPlugins();
    }
    if (!this.pendingPluginEnablements) {
      return;
    }
    const entries = arrayFrom(this.pendingPluginEnablements.entries());
    this.pendingPluginEnablements = void 0;
    this.currentPluginEnablementPromise = this.enableRequestedPluginsWorker(entries);
    await this.currentPluginEnablementPromise;
  }
  async enableRequestedPluginsWorker(pendingPlugins) {
    Debug.assert(this.currentPluginEnablementPromise === void 0);
    await Promise.all(map(pendingPlugins, ([project, promises]) => this.enableRequestedPluginsForProjectAsync(project, promises)));
    this.currentPluginEnablementPromise = void 0;
    this.sendProjectsUpdatedInBackgroundEvent();
  }
  async enableRequestedPluginsForProjectAsync(project, promises) {
    const results = await Promise.all(promises);
    if (project.isClosed()) {
      return;
    }
    for (const result of results) {
      this.endEnablePlugin(project, result);
    }
    this.delayUpdateProjectGraph(project);
  }
  configurePlugin(args) {
    this.forEachEnabledProject((project) => project.onPluginConfigurationChanged(args.pluginName, args.configuration));
    this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || /* @__PURE__ */ new Map();
    this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
  }
  /** @internal */
  getPackageJsonsVisibleToFile(fileName, rootDir) {
    const packageJsonCache = this.packageJsonCache;
    const rootPath = rootDir && this.toPath(rootDir);
    const filePath = this.toPath(fileName);
    const result = [];
    const processDirectory = (directory) => {
      switch (packageJsonCache.directoryHasPackageJson(directory)) {
        case 3 /* Maybe */:
          packageJsonCache.searchDirectoryAndAncestors(directory);
          return processDirectory(directory);
        case -1 /* True */:
          const packageJsonFileName = combinePaths(directory, "package.json");
          this.watchPackageJsonFile(packageJsonFileName);
          const info = packageJsonCache.getInDirectory(directory);
          if (info)
            result.push(info);
      }
      if (rootPath && rootPath === directory) {
        return true;
      }
    };
    forEachAncestorDirectory(getDirectoryPath(filePath), processDirectory);
    return result;
  }
  /** @internal */
  getNearestAncestorDirectoryWithPackageJson(fileName) {
    return forEachAncestorDirectory(fileName, (directory) => {
      switch (this.packageJsonCache.directoryHasPackageJson(this.toPath(directory))) {
        case -1 /* True */:
          return directory;
        case 0 /* False */:
          return void 0;
        case 3 /* Maybe */:
          return this.host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0;
      }
    });
  }
  /** @internal */
  watchPackageJsonFile(path) {
    const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = /* @__PURE__ */ new Map());
    if (!watchers.has(path)) {
      this.invalidateProjectPackageJson(path);
      watchers.set(path, this.watchFactory.watchFile(
        path,
        (fileName, eventKind) => {
          const path2 = this.toPath(fileName);
          switch (eventKind) {
            case 0 /* Created */:
              return Debug.fail();
            case 1 /* Changed */:
              this.packageJsonCache.addOrUpdate(path2);
              this.invalidateProjectPackageJson(path2);
              break;
            case 2 /* Deleted */:
              this.packageJsonCache.delete(path2);
              this.invalidateProjectPackageJson(path2);
              watchers.get(path2).close();
              watchers.delete(path2);
          }
        },
        250 /* Low */,
        this.hostConfiguration.watchOptions,
        WatchType.PackageJson
      ));
    }
  }
  /** @internal */
  onAddPackageJson(path) {
    this.packageJsonCache.addOrUpdate(path);
    this.watchPackageJsonFile(path);
  }
  /** @internal */
  includePackageJsonAutoImports() {
    switch (this.hostConfiguration.preferences.includePackageJsonAutoImports) {
      case "on":
        return 1 /* On */;
      case "off":
        return 0 /* Off */;
      default:
        return 2 /* Auto */;
    }
  }
  /** @internal */
  invalidateProjectPackageJson(packageJsonPath) {
    this.configuredProjects.forEach(invalidate);
    this.inferredProjects.forEach(invalidate);
    this.externalProjects.forEach(invalidate);
    function invalidate(project) {
      if (packageJsonPath) {
        project.onPackageJsonChange(packageJsonPath);
      } else {
        project.onAutoImportProviderSettingsChanged();
      }
    }
  }
  /** @internal */
  getIncompleteCompletionsCache() {
    return this.incompleteCompletionsCache || (this.incompleteCompletionsCache = createIncompleteCompletionsCache());
  }
};
var ProjectService3 = _ProjectService;
/** Makes a filename safe to insert in a RegExp */
ProjectService3.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
function createIncompleteCompletionsCache() {
  let info;
  return {
    get() {
      return info;
    },
    set(newInfo) {
      info = newInfo;
    },
    clear() {
      info = void 0;
    }
  };
}
function isConfigFile(config) {
  return config.kind !== void 0;
}
function printProjectWithoutFileNames(project) {
  project.print(
    /*writeProjectFileNames*/
    false,
    /*writeFileExplaination*/
    false,
    /*writeFileVersionAndText*/
    false
  );
}

// src/server/moduleSpecifierCache.ts
function createModuleSpecifierCache(host) {
  let containedNodeModulesWatchers;
  let cache;
  let currentKey;
  const result = {
    get(fromFileName, toFileName2, preferences, options) {
      if (!cache || currentKey !== key(fromFileName, preferences, options))
        return void 0;
      return cache.get(toFileName2);
    },
    set(fromFileName, toFileName2, preferences, options, modulePaths, moduleSpecifiers) {
      ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo(
        modulePaths,
        moduleSpecifiers,
        /*isBlockedByPackageJsonDependencies*/
        false
      ));
      if (moduleSpecifiers) {
        for (const p of modulePaths) {
          if (p.isInNodeModules) {
            const nodeModulesPath = p.path.substring(0, p.path.indexOf(nodeModulesPathPart) + nodeModulesPathPart.length - 1);
            if (!(containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.has(nodeModulesPath))) {
              (containedNodeModulesWatchers || (containedNodeModulesWatchers = /* @__PURE__ */ new Map())).set(
                nodeModulesPath,
                host.watchNodeModulesForPackageJsonChanges(nodeModulesPath)
              );
            }
          }
        }
      }
    },
    setModulePaths(fromFileName, toFileName2, preferences, options, modulePaths) {
      const cache2 = ensureCache(fromFileName, preferences, options);
      const info = cache2.get(toFileName2);
      if (info) {
        info.modulePaths = modulePaths;
      } else {
        cache2.set(toFileName2, createInfo(
          modulePaths,
          /*moduleSpecifiers*/
          void 0,
          /*isBlockedByPackageJsonDependencies*/
          void 0
        ));
      }
    },
    setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, isBlockedByPackageJsonDependencies) {
      const cache2 = ensureCache(fromFileName, preferences, options);
      const info = cache2.get(toFileName2);
      if (info) {
        info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies;
      } else {
        cache2.set(toFileName2, createInfo(
          /*modulePaths*/
          void 0,
          /*moduleSpecifiers*/
          void 0,
          isBlockedByPackageJsonDependencies
        ));
      }
    },
    clear() {
      containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.forEach((watcher) => watcher.close());
      cache == null ? void 0 : cache.clear();
      containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.clear();
      currentKey = void 0;
    },
    count() {
      return cache ? cache.size : 0;
    }
  };
  if (Debug.isDebugging) {
    Object.defineProperty(result, "__cache", { get: () => cache });
  }
  return result;
  function ensureCache(fromFileName, preferences, options) {
    const newKey = key(fromFileName, preferences, options);
    if (cache && currentKey !== newKey) {
      result.clear();
    }
    currentKey = newKey;
    return cache || (cache = /* @__PURE__ */ new Map());
  }
  function key(fromFileName, preferences, options) {
    return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`;
  }
  function createInfo(modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies) {
    return { modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies };
  }
}

// src/server/packageJsonCache.ts
function createPackageJsonCache(host) {
  const packageJsons = /* @__PURE__ */ new Map();
  const directoriesWithoutPackageJson = /* @__PURE__ */ new Map();
  return {
    addOrUpdate,
    forEach: packageJsons.forEach.bind(packageJsons),
    get: packageJsons.get.bind(packageJsons),
    delete: (fileName) => {
      packageJsons.delete(fileName);
      directoriesWithoutPackageJson.set(getDirectoryPath(fileName), true);
    },
    getInDirectory: (directory) => {
      return packageJsons.get(combinePaths(directory, "package.json")) || void 0;
    },
    directoryHasPackageJson,
    searchDirectoryAndAncestors: (directory) => {
      forEachAncestorDirectory(directory, (ancestor) => {
        if (directoryHasPackageJson(ancestor) !== 3 /* Maybe */) {
          return true;
        }
        const packageJsonFileName = host.toPath(combinePaths(ancestor, "package.json"));
        if (tryFileExists(host, packageJsonFileName)) {
          addOrUpdate(packageJsonFileName);
        } else {
          directoriesWithoutPackageJson.set(ancestor, true);
        }
      });
    }
  };
  function addOrUpdate(fileName) {
    const packageJsonInfo = Debug.checkDefined(createPackageJsonInfo(fileName, host.host));
    packageJsons.set(fileName, packageJsonInfo);
    directoriesWithoutPackageJson.delete(getDirectoryPath(fileName));
  }
  function directoryHasPackageJson(directory) {
    return packageJsons.has(combinePaths(directory, "package.json")) ? -1 /* True */ : directoriesWithoutPackageJson.has(directory) ? 0 /* False */ : 3 /* Maybe */;
  }
}

// src/server/session.ts
var nullCancellationToken = {
  isCancellationRequested: () => false,
  setRequest: () => void 0,
  resetRequest: () => void 0
};
function hrTimeToMilliseconds(time) {
  const seconds = time[0];
  const nanoseconds = time[1];
  return (1e9 * seconds + nanoseconds) / 1e6;
}
function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) {
  if ((isInferredProject(project) || isExternalProject(project)) && project.isJsOnlyProject()) {
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    return scriptInfo && !scriptInfo.isJavaScript();
  }
  return false;
}
function dtsChangeCanAffectEmit(compilationSettings) {
  return getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata;
}
function formatDiag(fileName, project, diag2) {
  const scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
  return {
    start: scriptInfo.positionToLineOffset(diag2.start),
    end: scriptInfo.positionToLineOffset(diag2.start + diag2.length),
    // TODO: GH#18217
    text: flattenDiagnosticMessageText(diag2.messageText, "\n"),
    code: diag2.code,
    category: diagnosticCategoryName(diag2),
    reportsUnnecessary: diag2.reportsUnnecessary,
    reportsDeprecated: diag2.reportsDeprecated,
    source: diag2.source,
    relatedInformation: map(diag2.relatedInformation, formatRelatedInformation)
  };
}
function formatRelatedInformation(info) {
  if (!info.file) {
    return {
      message: flattenDiagnosticMessageText(info.messageText, "\n"),
      category: diagnosticCategoryName(info),
      code: info.code
    };
  }
  return {
    span: {
      start: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start)),
      end: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start + info.length)),
      // TODO: GH#18217
      file: info.file.fileName
    },
    message: flattenDiagnosticMessageText(info.messageText, "\n"),
    category: diagnosticCategoryName(info),
    code: info.code
  };
}
function convertToLocation(lineAndCharacter) {
  return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 };
}
function formatDiagnosticToProtocol(diag2, includeFileName) {
  const start2 = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start));
  const end = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start + diag2.length));
  const text = flattenDiagnosticMessageText(diag2.messageText, "\n");
  const { code, source } = diag2;
  const category = diagnosticCategoryName(diag2);
  const common = {
    start: start2,
    end,
    text,
    code,
    category,
    reportsUnnecessary: diag2.reportsUnnecessary,
    reportsDeprecated: diag2.reportsDeprecated,
    source,
    relatedInformation: map(diag2.relatedInformation, formatRelatedInformation)
  };
  return includeFileName ? { ...common, fileName: diag2.file && diag2.file.fileName } : common;
}
function allEditsBeforePos(edits, pos) {
  return edits.every((edit) => textSpanEnd(edit.span) < pos);
}
var CommandNames = CommandTypes;
function formatMessage2(msg, logger, byteLength, newLine) {
  const verboseLogging = logger.hasLevel(3 /* verbose */);
  const json = JSON.stringify(msg);
  if (verboseLogging) {
    logger.info(`${msg.type}:${indent2(JSON.stringify(msg, void 0, " "))}`);
  }
  const len = byteLength(json, "utf8");
  return `Content-Length: ${1 + len}\r
\r
${json}${newLine}`;
}
var MultistepOperation = class {
  constructor(operationHost) {
    this.operationHost = operationHost;
  }
  startNew(action) {
    this.complete();
    this.requestId = this.operationHost.getCurrentRequestId();
    this.executeAction(action);
  }
  complete() {
    if (this.requestId !== void 0) {
      this.operationHost.sendRequestCompletedEvent(this.requestId);
      this.requestId = void 0;
    }
    this.setTimerHandle(void 0);
    this.setImmediateId(void 0);
  }
  immediate(actionType, action) {
    const requestId = this.requestId;
    Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id");
    this.setImmediateId(this.operationHost.getServerHost().setImmediate(() => {
      this.immediateId = void 0;
      this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action));
    }, actionType));
  }
  delay(actionType, ms, action) {
    const requestId = this.requestId;
    Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id");
    this.setTimerHandle(this.operationHost.getServerHost().setTimeout(() => {
      this.timerHandle = void 0;
      this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action));
    }, ms, actionType));
  }
  executeAction(action) {
    var _a, _b, _c, _d, _e, _f;
    let stop = false;
    try {
      if (this.operationHost.isCancellationRequested()) {
        stop = true;
        (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId, early: true });
      } else {
        (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.Session, "stepAction", { seq: this.requestId });
        action(this);
        (_c = tracing) == null ? void 0 : _c.pop();
      }
    } catch (e) {
      (_d = tracing) == null ? void 0 : _d.popAll();
      stop = true;
      if (e instanceof OperationCanceledException) {
        (_e = tracing) == null ? void 0 : _e.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId });
      } else {
        (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: e.message });
        this.operationHost.logError(e, `delayed processing of request ${this.requestId}`);
      }
    }
    if (stop || !this.hasPendingWork()) {
      this.complete();
    }
  }
  setTimerHandle(timerHandle) {
    if (this.timerHandle !== void 0) {
      this.operationHost.getServerHost().clearTimeout(this.timerHandle);
    }
    this.timerHandle = timerHandle;
  }
  setImmediateId(immediateId) {
    if (this.immediateId !== void 0) {
      this.operationHost.getServerHost().clearImmediate(this.immediateId);
    }
    this.immediateId = immediateId;
  }
  hasPendingWork() {
    return !!this.timerHandle || !!this.immediateId;
  }
};
function toEvent(eventName, body) {
  return {
    seq: 0,
    type: "event",
    event: eventName,
    body
  };
}
function combineProjectOutput(defaultValue, getValue, projects, action) {
  const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, (project) => action(project, defaultValue));
  if (!isArray(projects) && projects.symLinkedProjects) {
    projects.symLinkedProjects.forEach((projects2, path) => {
      const value = getValue(path);
      outputs.push(...flatMap(projects2, (project) => action(project, value)));
    });
  }
  return deduplicate(outputs, equateValues);
}
function createDocumentSpanSet() {
  return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual);
}
function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences) {
  const perProjectResults = getPerProjectReferences(
    projects,
    defaultProject,
    initialLocation,
    /*isForRename*/
    true,
    (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences),
    (renameLocation, cb) => cb(documentSpanLocation(renameLocation))
  );
  if (isArray(perProjectResults)) {
    return perProjectResults;
  }
  const results = [];
  const seen = createDocumentSpanSet();
  perProjectResults.forEach((projectResults, project) => {
    for (const result of projectResults) {
      if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) {
        results.push(result);
        seen.add(result);
      }
    }
  });
  return results;
}
function getDefinitionLocation(defaultProject, initialLocation, isForRename) {
  const infos = defaultProject.getLanguageService().getDefinitionAtPosition(
    initialLocation.fileName,
    initialLocation.pos,
    /*searchOtherFilesOnly*/
    false,
    /*stopAtAlias*/
    isForRename
  );
  const info = infos && firstOrUndefined(infos);
  return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : void 0;
}
function getReferencesWorker(projects, defaultProject, initialLocation, logger) {
  var _a, _b;
  const perProjectResults = getPerProjectReferences(
    projects,
    defaultProject,
    initialLocation,
    /*isForRename*/
    false,
    (project, position) => {
      logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`);
      return project.getLanguageService().findReferences(position.fileName, position.pos);
    },
    (referencedSymbol, cb) => {
      cb(documentSpanLocation(referencedSymbol.definition));
      for (const ref of referencedSymbol.references) {
        cb(documentSpanLocation(ref));
      }
    }
  );
  if (isArray(perProjectResults)) {
    return perProjectResults;
  }
  const defaultProjectResults = perProjectResults.get(defaultProject);
  if (((_b = (_a = defaultProjectResults == null ? void 0 : defaultProjectResults[0]) == null ? void 0 : _a.references[0]) == null ? void 0 : _b.isDefinition) === void 0) {
    perProjectResults.forEach((projectResults) => {
      for (const referencedSymbol of projectResults) {
        for (const ref of referencedSymbol.references) {
          delete ref.isDefinition;
        }
      }
    });
  } else {
    const knownSymbolSpans = createDocumentSpanSet();
    for (const referencedSymbol of defaultProjectResults) {
      for (const ref of referencedSymbol.references) {
        if (ref.isDefinition) {
          knownSymbolSpans.add(ref);
          break;
        }
      }
    }
    const updatedProjects = /* @__PURE__ */ new Set();
    while (true) {
      let progress = false;
      perProjectResults.forEach((referencedSymbols, project) => {
        if (updatedProjects.has(project))
          return;
        const updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans);
        if (updated) {
          updatedProjects.add(project);
          progress = true;
        }
      });
      if (!progress)
        break;
    }
    perProjectResults.forEach((referencedSymbols, project) => {
      if (updatedProjects.has(project))
        return;
      for (const referencedSymbol of referencedSymbols) {
        for (const ref of referencedSymbol.references) {
          ref.isDefinition = false;
        }
      }
    });
  }
  const results = [];
  const seenRefs = createDocumentSpanSet();
  perProjectResults.forEach((projectResults, project) => {
    for (const referencedSymbol of projectResults) {
      const mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project);
      const definition = mappedDefinitionFile === void 0 ? referencedSymbol.definition : {
        ...referencedSymbol.definition,
        textSpan: createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length),
        // Why would the length be the same in the original?
        fileName: mappedDefinitionFile.fileName,
        contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project)
      };
      let symbolToAddTo = find(results, (o) => documentSpansEqual(o.definition, definition));
      if (!symbolToAddTo) {
        symbolToAddTo = { definition, references: [] };
        results.push(symbolToAddTo);
      }
      for (const ref of referencedSymbol.references) {
        if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) {
          seenRefs.add(ref);
          symbolToAddTo.references.push(ref);
        }
      }
    }
  });
  return results.filter((o) => o.references.length !== 0);
}
function forEachProjectInProjects(projects, path, cb) {
  for (const project of isArray(projects) ? projects : projects.projects) {
    cb(project, path);
  }
  if (!isArray(projects) && projects.symLinkedProjects) {
    projects.symLinkedProjects.forEach((symlinkedProjects, symlinkedPath) => {
      for (const project of symlinkedProjects) {
        cb(project, symlinkedPath);
      }
    });
  }
}
function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) {
  const resultsMap = /* @__PURE__ */ new Map();
  const queue = createQueue();
  queue.enqueue({ project: defaultProject, location: initialLocation });
  forEachProjectInProjects(projects, initialLocation.fileName, (project, path) => {
    const location = { fileName: path, pos: initialLocation.pos };
    queue.enqueue({ project, location });
  });
  const projectService = defaultProject.projectService;
  const cancellationToken = defaultProject.getCancellationToken();
  const defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename);
  const getGeneratedDefinition = memoize(() => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition));
  const getSourceDefinition = memoize(() => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition));
  const searchedProjectKeys = /* @__PURE__ */ new Set();
  onCancellation:
    while (!queue.isEmpty()) {
      while (!queue.isEmpty()) {
        if (cancellationToken.isCancellationRequested())
          break onCancellation;
        const { project, location } = queue.dequeue();
        if (resultsMap.has(project))
          continue;
        if (isLocationProjectReferenceRedirect(project, location))
          continue;
        updateProjectIfDirty(project);
        if (!project.containsFile(toNormalizedPath(location.fileName))) {
          continue;
        }
        const projectResults = searchPosition(project, location);
        resultsMap.set(project, projectResults ?? emptyArray2);
        searchedProjectKeys.add(getProjectKey(project));
      }
      if (defaultDefinition) {
        projectService.loadAncestorProjectTree(searchedProjectKeys);
        projectService.forEachEnabledProject((project) => {
          if (cancellationToken.isCancellationRequested())
            return;
          if (resultsMap.has(project))
            return;
          const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition);
          if (location) {
            queue.enqueue({ project, location });
          }
        });
      }
    }
  if (resultsMap.size === 1) {
    return firstIterator(resultsMap.values());
  }
  return resultsMap;
  function searchPosition(project, location) {
    const projectResults = getResultsForPosition(project, location);
    if (!projectResults)
      return void 0;
    for (const result of projectResults) {
      forPositionInResult(result, (position) => {
        const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position);
        if (!originalLocation)
          return;
        const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName);
        for (const project2 of originalScriptInfo.containingProjects) {
          if (!project2.isOrphan() && !resultsMap.has(project2)) {
            queue.enqueue({ project: project2, location: originalLocation });
          }
        }
        const symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo);
        if (symlinkedProjectsMap) {
          symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => {
            for (const symlinkedProject of symlinkedProjects) {
              if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) {
                queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } });
              }
            }
          });
        }
      });
    }
    return projectResults;
  }
}
function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) {
  if (project.containsFile(toNormalizedPath(definition.fileName)) && !isLocationProjectReferenceRedirect(project, definition)) {
    return definition;
  }
  const generatedDefinition = getGeneratedDefinition();
  if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName)))
    return generatedDefinition;
  const sourceDefinition = getSourceDefinition();
  return sourceDefinition && project.containsFile(toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : void 0;
}
function isLocationProjectReferenceRedirect(project, location) {
  if (!location)
    return false;
  const program = project.getLanguageService().getProgram();
  if (!program)
    return false;
  const sourceFile = program.getSourceFile(location.fileName);
  return !!sourceFile && sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName);
}
function getProjectKey(project) {
  return isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName();
}
function documentSpanLocation({ fileName, textSpan }) {
  return { fileName, pos: textSpan.start };
}
function getMappedLocationForProject(location, project) {
  return getMappedLocation(location, project.getSourceMapper(), (p) => project.projectService.fileExists(p));
}
function getMappedDocumentSpanForProject(documentSpan, project) {
  return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p));
}
function getMappedContextSpanForProject(documentSpan, project) {
  return getMappedContextSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p));
}
var invalidPartialSemanticModeCommands = [
  "openExternalProject" /* OpenExternalProject */,
  "openExternalProjects" /* OpenExternalProjects */,
  "closeExternalProject" /* CloseExternalProject */,
  "synchronizeProjectList" /* SynchronizeProjectList */,
  "emit-output" /* EmitOutput */,
  "compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */,
  "compileOnSaveEmitFile" /* CompileOnSaveEmitFile */,
  "compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */,
  "encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */,
  "semanticDiagnosticsSync" /* SemanticDiagnosticsSync */,
  "suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */,
  "geterrForProject" /* GeterrForProject */,
  "reload" /* Reload */,
  "reloadProjects" /* ReloadProjects */,
  "getCodeFixes" /* GetCodeFixes */,
  "getCodeFixes-full" /* GetCodeFixesFull */,
  "getCombinedCodeFix" /* GetCombinedCodeFix */,
  "getCombinedCodeFix-full" /* GetCombinedCodeFixFull */,
  "applyCodeActionCommand" /* ApplyCodeActionCommand */,
  "getSupportedCodeFixes" /* GetSupportedCodeFixes */,
  "getApplicableRefactors" /* GetApplicableRefactors */,
  "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */,
  "getEditsForRefactor" /* GetEditsForRefactor */,
  "getEditsForRefactor-full" /* GetEditsForRefactorFull */,
  "organizeImports" /* OrganizeImports */,
  "organizeImports-full" /* OrganizeImportsFull */,
  "getEditsForFileRename" /* GetEditsForFileRename */,
  "getEditsForFileRename-full" /* GetEditsForFileRenameFull */,
  "prepareCallHierarchy" /* PrepareCallHierarchy */,
  "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */,
  "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */
];
var invalidSyntacticModeCommands = [
  ...invalidPartialSemanticModeCommands,
  "definition" /* Definition */,
  "definition-full" /* DefinitionFull */,
  "definitionAndBoundSpan" /* DefinitionAndBoundSpan */,
  "definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */,
  "typeDefinition" /* TypeDefinition */,
  "implementation" /* Implementation */,
  "implementation-full" /* ImplementationFull */,
  "references" /* References */,
  "references-full" /* ReferencesFull */,
  "rename" /* Rename */,
  "renameLocations-full" /* RenameLocationsFull */,
  "rename-full" /* RenameInfoFull */,
  "quickinfo" /* Quickinfo */,
  "quickinfo-full" /* QuickinfoFull */,
  "completionInfo" /* CompletionInfo */,
  "completions" /* Completions */,
  "completions-full" /* CompletionsFull */,
  "completionEntryDetails" /* CompletionDetails */,
  "completionEntryDetails-full" /* CompletionDetailsFull */,
  "signatureHelp" /* SignatureHelp */,
  "signatureHelp-full" /* SignatureHelpFull */,
  "navto" /* Navto */,
  "navto-full" /* NavtoFull */,
  "documentHighlights" /* DocumentHighlights */,
  "documentHighlights-full" /* DocumentHighlightsFull */
];
var Session3 = class {
  constructor(opts) {
    this.changeSeq = 0;
    this.handlers = new Map(Object.entries({
      // TODO(jakebailey): correctly type the handlers
      ["status" /* Status */]: () => {
        const response = { version };
        return this.requiredResponse(response);
      },
      ["openExternalProject" /* OpenExternalProject */]: (request) => {
        this.projectService.openExternalProject(request.arguments);
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["openExternalProjects" /* OpenExternalProjects */]: (request) => {
        this.projectService.openExternalProjects(request.arguments.projects);
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["closeExternalProject" /* CloseExternalProject */]: (request) => {
        this.projectService.closeExternalProject(request.arguments.projectFileName);
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["synchronizeProjectList" /* SynchronizeProjectList */]: (request) => {
        const result = this.projectService.synchronizeProjectList(request.arguments.knownProjects, request.arguments.includeProjectReferenceRedirectInfo);
        if (!result.some((p) => p.projectErrors && p.projectErrors.length !== 0)) {
          return this.requiredResponse(result);
        }
        const converted = map(result, (p) => {
          if (!p.projectErrors || p.projectErrors.length === 0) {
            return p;
          }
          return {
            info: p.info,
            changes: p.changes,
            files: p.files,
            projectErrors: this.convertToDiagnosticsWithLinePosition(
              p.projectErrors,
              /*scriptInfo*/
              void 0
            )
          };
        });
        return this.requiredResponse(converted);
      },
      ["updateOpen" /* UpdateOpen */]: (request) => {
        this.changeSeq++;
        this.projectService.applyChangesInOpenFiles(
          request.arguments.openFiles && mapIterator(request.arguments.openFiles, (file) => ({
            fileName: file.file,
            content: file.fileContent,
            scriptKind: file.scriptKindName,
            projectRootPath: file.projectRootPath
          })),
          request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({
            fileName: file.fileName,
            changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), (change) => {
              const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName));
              const start2 = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
              const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
              return start2 >= 0 ? { span: { start: start2, length: end - start2 }, newText: change.newText } : void 0;
            })
          })),
          request.arguments.closedFiles
        );
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["applyChangedToOpenFiles" /* ApplyChangedToOpenFiles */]: (request) => {
        this.changeSeq++;
        this.projectService.applyChangesInOpenFiles(
          request.arguments.openFiles,
          request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({
            fileName: file.fileName,
            // apply changes in reverse order
            changes: arrayReverseIterator(file.changes)
          })),
          request.arguments.closedFiles
        );
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["exit" /* Exit */]: () => {
        this.exit();
        return this.notRequired();
      },
      ["definition" /* Definition */]: (request) => {
        return this.requiredResponse(this.getDefinition(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["definition-full" /* DefinitionFull */]: (request) => {
        return this.requiredResponse(this.getDefinition(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["definitionAndBoundSpan" /* DefinitionAndBoundSpan */]: (request) => {
        return this.requiredResponse(this.getDefinitionAndBoundSpan(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */]: (request) => {
        return this.requiredResponse(this.getDefinitionAndBoundSpan(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["findSourceDefinition" /* FindSourceDefinition */]: (request) => {
        return this.requiredResponse(this.findSourceDefinition(request.arguments));
      },
      ["emit-output" /* EmitOutput */]: (request) => {
        return this.requiredResponse(this.getEmitOutput(request.arguments));
      },
      ["typeDefinition" /* TypeDefinition */]: (request) => {
        return this.requiredResponse(this.getTypeDefinition(request.arguments));
      },
      ["implementation" /* Implementation */]: (request) => {
        return this.requiredResponse(this.getImplementation(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["implementation-full" /* ImplementationFull */]: (request) => {
        return this.requiredResponse(this.getImplementation(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["references" /* References */]: (request) => {
        return this.requiredResponse(this.getReferences(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["references-full" /* ReferencesFull */]: (request) => {
        return this.requiredResponse(this.getReferences(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["rename" /* Rename */]: (request) => {
        return this.requiredResponse(this.getRenameLocations(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["renameLocations-full" /* RenameLocationsFull */]: (request) => {
        return this.requiredResponse(this.getRenameLocations(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["rename-full" /* RenameInfoFull */]: (request) => {
        return this.requiredResponse(this.getRenameInfo(request.arguments));
      },
      ["open" /* Open */]: (request) => {
        this.openClientFile(
          toNormalizedPath(request.arguments.file),
          request.arguments.fileContent,
          convertScriptKindName(request.arguments.scriptKindName),
          // TODO: GH#18217
          request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0
        );
        return this.notRequired();
      },
      ["quickinfo" /* Quickinfo */]: (request) => {
        return this.requiredResponse(this.getQuickInfoWorker(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["quickinfo-full" /* QuickinfoFull */]: (request) => {
        return this.requiredResponse(this.getQuickInfoWorker(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["getOutliningSpans" /* GetOutliningSpans */]: (request) => {
        return this.requiredResponse(this.getOutliningSpans(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["outliningSpans" /* GetOutliningSpansFull */]: (request) => {
        return this.requiredResponse(this.getOutliningSpans(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["todoComments" /* TodoComments */]: (request) => {
        return this.requiredResponse(this.getTodoComments(request.arguments));
      },
      ["indentation" /* Indentation */]: (request) => {
        return this.requiredResponse(this.getIndentation(request.arguments));
      },
      ["nameOrDottedNameSpan" /* NameOrDottedNameSpan */]: (request) => {
        return this.requiredResponse(this.getNameOrDottedNameSpan(request.arguments));
      },
      ["breakpointStatement" /* BreakpointStatement */]: (request) => {
        return this.requiredResponse(this.getBreakpointStatement(request.arguments));
      },
      ["braceCompletion" /* BraceCompletion */]: (request) => {
        return this.requiredResponse(this.isValidBraceCompletion(request.arguments));
      },
      ["docCommentTemplate" /* DocCommentTemplate */]: (request) => {
        return this.requiredResponse(this.getDocCommentTemplate(request.arguments));
      },
      ["getSpanOfEnclosingComment" /* GetSpanOfEnclosingComment */]: (request) => {
        return this.requiredResponse(this.getSpanOfEnclosingComment(request.arguments));
      },
      ["fileReferences" /* FileReferences */]: (request) => {
        return this.requiredResponse(this.getFileReferences(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["fileReferences-full" /* FileReferencesFull */]: (request) => {
        return this.requiredResponse(this.getFileReferences(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["format" /* Format */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsForRange(request.arguments));
      },
      ["formatonkey" /* Formatonkey */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsAfterKeystroke(request.arguments));
      },
      ["format-full" /* FormatFull */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsForDocumentFull(request.arguments));
      },
      ["formatonkey-full" /* FormatonkeyFull */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsAfterKeystrokeFull(request.arguments));
      },
      ["formatRange-full" /* FormatRangeFull */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsForRangeFull(request.arguments));
      },
      ["completionInfo" /* CompletionInfo */]: (request) => {
        return this.requiredResponse(this.getCompletions(request.arguments, "completionInfo" /* CompletionInfo */));
      },
      ["completions" /* Completions */]: (request) => {
        return this.requiredResponse(this.getCompletions(request.arguments, "completions" /* Completions */));
      },
      ["completions-full" /* CompletionsFull */]: (request) => {
        return this.requiredResponse(this.getCompletions(request.arguments, "completions-full" /* CompletionsFull */));
      },
      ["completionEntryDetails" /* CompletionDetails */]: (request) => {
        return this.requiredResponse(this.getCompletionEntryDetails(
          request.arguments,
          /*fullResult*/
          false
        ));
      },
      ["completionEntryDetails-full" /* CompletionDetailsFull */]: (request) => {
        return this.requiredResponse(this.getCompletionEntryDetails(
          request.arguments,
          /*fullResult*/
          true
        ));
      },
      ["compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */]: (request) => {
        return this.requiredResponse(this.getCompileOnSaveAffectedFileList(request.arguments));
      },
      ["compileOnSaveEmitFile" /* CompileOnSaveEmitFile */]: (request) => {
        return this.requiredResponse(this.emitFile(request.arguments));
      },
      ["signatureHelp" /* SignatureHelp */]: (request) => {
        return this.requiredResponse(this.getSignatureHelpItems(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["signatureHelp-full" /* SignatureHelpFull */]: (request) => {
        return this.requiredResponse(this.getSignatureHelpItems(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */]: (request) => {
        return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments));
      },
      ["encodedSyntacticClassifications-full" /* EncodedSyntacticClassificationsFull */]: (request) => {
        return this.requiredResponse(this.getEncodedSyntacticClassifications(request.arguments));
      },
      ["encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */]: (request) => {
        return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments));
      },
      ["cleanup" /* Cleanup */]: () => {
        this.cleanup();
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["semanticDiagnosticsSync" /* SemanticDiagnosticsSync */]: (request) => {
        return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments));
      },
      ["syntacticDiagnosticsSync" /* SyntacticDiagnosticsSync */]: (request) => {
        return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments));
      },
      ["suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */]: (request) => {
        return this.requiredResponse(this.getSuggestionDiagnosticsSync(request.arguments));
      },
      ["geterr" /* Geterr */]: (request) => {
        this.errorCheck.startNew((next) => this.getDiagnostics(next, request.arguments.delay, request.arguments.files));
        return this.notRequired();
      },
      ["geterrForProject" /* GeterrForProject */]: (request) => {
        this.errorCheck.startNew((next) => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file));
        return this.notRequired();
      },
      ["change" /* Change */]: (request) => {
        this.change(request.arguments);
        return this.notRequired();
      },
      ["configure" /* Configure */]: (request) => {
        this.projectService.setHostConfiguration(request.arguments);
        this.doOutput(
          /*info*/
          void 0,
          "configure" /* Configure */,
          request.seq,
          /*success*/
          true
        );
        return this.notRequired();
      },
      ["reload" /* Reload */]: (request) => {
        this.reload(request.arguments, request.seq);
        return this.requiredResponse({ reloadFinished: true });
      },
      ["saveto" /* Saveto */]: (request) => {
        const savetoArgs = request.arguments;
        this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
        return this.notRequired();
      },
      ["close" /* Close */]: (request) => {
        const closeArgs = request.arguments;
        this.closeClientFile(closeArgs.file);
        return this.notRequired();
      },
      ["navto" /* Navto */]: (request) => {
        return this.requiredResponse(this.getNavigateToItems(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["navto-full" /* NavtoFull */]: (request) => {
        return this.requiredResponse(this.getNavigateToItems(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["brace" /* Brace */]: (request) => {
        return this.requiredResponse(this.getBraceMatching(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["brace-full" /* BraceFull */]: (request) => {
        return this.requiredResponse(this.getBraceMatching(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["navbar" /* NavBar */]: (request) => {
        return this.requiredResponse(this.getNavigationBarItems(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["navbar-full" /* NavBarFull */]: (request) => {
        return this.requiredResponse(this.getNavigationBarItems(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["navtree" /* NavTree */]: (request) => {
        return this.requiredResponse(this.getNavigationTree(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["navtree-full" /* NavTreeFull */]: (request) => {
        return this.requiredResponse(this.getNavigationTree(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["documentHighlights" /* DocumentHighlights */]: (request) => {
        return this.requiredResponse(this.getDocumentHighlights(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["documentHighlights-full" /* DocumentHighlightsFull */]: (request) => {
        return this.requiredResponse(this.getDocumentHighlights(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["compilerOptionsForInferredProjects" /* CompilerOptionsForInferredProjects */]: (request) => {
        this.setCompilerOptionsForInferredProjects(request.arguments);
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["projectInfo" /* ProjectInfo */]: (request) => {
        return this.requiredResponse(this.getProjectInfo(request.arguments));
      },
      ["reloadProjects" /* ReloadProjects */]: () => {
        this.projectService.reloadProjects();
        return this.notRequired();
      },
      ["jsxClosingTag" /* JsxClosingTag */]: (request) => {
        return this.requiredResponse(this.getJsxClosingTag(request.arguments));
      },
      ["linkedEditingRange" /* LinkedEditingRange */]: (request) => {
        return this.requiredResponse(this.getLinkedEditingRange(request.arguments));
      },
      ["getCodeFixes" /* GetCodeFixes */]: (request) => {
        return this.requiredResponse(this.getCodeFixes(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getCodeFixes-full" /* GetCodeFixesFull */]: (request) => {
        return this.requiredResponse(this.getCodeFixes(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["getCombinedCodeFix" /* GetCombinedCodeFix */]: (request) => {
        return this.requiredResponse(this.getCombinedCodeFix(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getCombinedCodeFix-full" /* GetCombinedCodeFixFull */]: (request) => {
        return this.requiredResponse(this.getCombinedCodeFix(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["applyCodeActionCommand" /* ApplyCodeActionCommand */]: (request) => {
        return this.requiredResponse(this.applyCodeActionCommand(request.arguments));
      },
      ["getSupportedCodeFixes" /* GetSupportedCodeFixes */]: (request) => {
        return this.requiredResponse(this.getSupportedCodeFixes(request.arguments));
      },
      ["getApplicableRefactors" /* GetApplicableRefactors */]: (request) => {
        return this.requiredResponse(this.getApplicableRefactors(request.arguments));
      },
      ["getEditsForRefactor" /* GetEditsForRefactor */]: (request) => {
        return this.requiredResponse(this.getEditsForRefactor(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => {
        return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments));
      },
      ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => {
        return this.requiredResponse(this.getEditsForRefactor(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["organizeImports" /* OrganizeImports */]: (request) => {
        return this.requiredResponse(this.organizeImports(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["organizeImports-full" /* OrganizeImportsFull */]: (request) => {
        return this.requiredResponse(this.organizeImports(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["getEditsForFileRename" /* GetEditsForFileRename */]: (request) => {
        return this.requiredResponse(this.getEditsForFileRename(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getEditsForFileRename-full" /* GetEditsForFileRenameFull */]: (request) => {
        return this.requiredResponse(this.getEditsForFileRename(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["configurePlugin" /* ConfigurePlugin */]: (request) => {
        this.configurePlugin(request.arguments);
        this.doOutput(
          /*info*/
          void 0,
          "configurePlugin" /* ConfigurePlugin */,
          request.seq,
          /*success*/
          true
        );
        return this.notRequired();
      },
      ["selectionRange" /* SelectionRange */]: (request) => {
        return this.requiredResponse(this.getSmartSelectionRange(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["selectionRange-full" /* SelectionRangeFull */]: (request) => {
        return this.requiredResponse(this.getSmartSelectionRange(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["prepareCallHierarchy" /* PrepareCallHierarchy */]: (request) => {
        return this.requiredResponse(this.prepareCallHierarchy(request.arguments));
      },
      ["provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */]: (request) => {
        return this.requiredResponse(this.provideCallHierarchyIncomingCalls(request.arguments));
      },
      ["provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]: (request) => {
        return this.requiredResponse(this.provideCallHierarchyOutgoingCalls(request.arguments));
      },
      ["toggleLineComment" /* ToggleLineComment */]: (request) => {
        return this.requiredResponse(this.toggleLineComment(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["toggleLineComment-full" /* ToggleLineCommentFull */]: (request) => {
        return this.requiredResponse(this.toggleLineComment(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["toggleMultilineComment" /* ToggleMultilineComment */]: (request) => {
        return this.requiredResponse(this.toggleMultilineComment(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["toggleMultilineComment-full" /* ToggleMultilineCommentFull */]: (request) => {
        return this.requiredResponse(this.toggleMultilineComment(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["commentSelection" /* CommentSelection */]: (request) => {
        return this.requiredResponse(this.commentSelection(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["commentSelection-full" /* CommentSelectionFull */]: (request) => {
        return this.requiredResponse(this.commentSelection(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["uncommentSelection" /* UncommentSelection */]: (request) => {
        return this.requiredResponse(this.uncommentSelection(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["uncommentSelection-full" /* UncommentSelectionFull */]: (request) => {
        return this.requiredResponse(this.uncommentSelection(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["provideInlayHints" /* ProvideInlayHints */]: (request) => {
        return this.requiredResponse(this.provideInlayHints(request.arguments));
      }
    }));
    this.host = opts.host;
    this.cancellationToken = opts.cancellationToken;
    this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller;
    this.byteLength = opts.byteLength;
    this.hrtime = opts.hrtime;
    this.logger = opts.logger;
    this.canUseEvents = opts.canUseEvents;
    this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents;
    this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate;
    const { throttleWaitMilliseconds } = opts;
    this.eventHandler = this.canUseEvents ? opts.eventHandler || ((event) => this.defaultEventHandler(event)) : void 0;
    const multistepOperationHost = {
      executeWithRequestId: (requestId, action) => this.executeWithRequestId(requestId, action),
      getCurrentRequestId: () => this.currentRequestId,
      getServerHost: () => this.host,
      logError: (err, cmd) => this.logError(err, cmd),
      sendRequestCompletedEvent: (requestId) => this.sendRequestCompletedEvent(requestId),
      isCancellationRequested: () => this.cancellationToken.isCancellationRequested()
    };
    this.errorCheck = new MultistepOperation(multistepOperationHost);
    const settings = {
      host: this.host,
      logger: this.logger,
      cancellationToken: this.cancellationToken,
      useSingleInferredProject: opts.useSingleInferredProject,
      useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot,
      typingsInstaller: this.typingsInstaller,
      throttleWaitMilliseconds,
      eventHandler: this.eventHandler,
      suppressDiagnosticEvents: this.suppressDiagnosticEvents,
      globalPlugins: opts.globalPlugins,
      pluginProbeLocations: opts.pluginProbeLocations,
      allowLocalPluginLoads: opts.allowLocalPluginLoads,
      typesMapLocation: opts.typesMapLocation,
      serverMode: opts.serverMode,
      session: this
    };
    this.projectService = new ProjectService3(settings);
    this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this));
    this.gcTimer = new GcTimer(
      this.host,
      /*delay*/
      7e3,
      this.logger
    );
    switch (this.projectService.serverMode) {
      case 0 /* Semantic */:
        break;
      case 1 /* PartialSemantic */:
        invalidPartialSemanticModeCommands.forEach(
          (commandName) => this.handlers.set(commandName, (request) => {
            throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.PartialSemantic`);
          })
        );
        break;
      case 2 /* Syntactic */:
        invalidSyntacticModeCommands.forEach(
          (commandName) => this.handlers.set(commandName, (request) => {
            throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.Syntactic`);
          })
        );
        break;
      default:
        Debug.assertNever(this.projectService.serverMode);
    }
  }
  sendRequestCompletedEvent(requestId) {
    this.event({ request_seq: requestId }, "requestCompleted");
  }
  addPerformanceData(key, value) {
    if (!this.performanceData) {
      this.performanceData = {};
    }
    this.performanceData[key] = (this.performanceData[key] ?? 0) + value;
  }
  performanceEventHandler(event) {
    switch (event.kind) {
      case "UpdateGraph":
        this.addPerformanceData("updateGraphDurationMs", event.durationMs);
        break;
      case "CreatePackageJsonAutoImportProvider":
        this.addPerformanceData("createAutoImportProviderProgramDurationMs", event.durationMs);
        break;
    }
  }
  defaultEventHandler(event) {
    switch (event.eventName) {
      case ProjectsUpdatedInBackgroundEvent:
        const { openFiles } = event.data;
        this.projectsUpdatedInBackgroundEvent(openFiles);
        break;
      case ProjectLoadingStartEvent:
        const { project, reason } = event.data;
        this.event(
          { projectName: project.getProjectName(), reason },
          ProjectLoadingStartEvent
        );
        break;
      case ProjectLoadingFinishEvent:
        const { project: finishProject } = event.data;
        this.event({ projectName: finishProject.getProjectName() }, ProjectLoadingFinishEvent);
        break;
      case LargeFileReferencedEvent:
        const { file, fileSize, maxFileSize: maxFileSize2 } = event.data;
        this.event({ file, fileSize, maxFileSize: maxFileSize2 }, LargeFileReferencedEvent);
        break;
      case ConfigFileDiagEvent:
        const { triggerFile, configFileName: configFile, diagnostics } = event.data;
        const bakedDiags = map(diagnostics, (diagnostic) => formatDiagnosticToProtocol(
          diagnostic,
          /*includeFileName*/
          true
        ));
        this.event({
          triggerFile,
          configFile,
          diagnostics: bakedDiags
        }, ConfigFileDiagEvent);
        break;
      case ProjectLanguageServiceStateEvent: {
        const eventName = ProjectLanguageServiceStateEvent;
        this.event({
          projectName: event.data.project.getProjectName(),
          languageServiceEnabled: event.data.languageServiceEnabled
        }, eventName);
        break;
      }
      case ProjectInfoTelemetryEvent: {
        const eventName = "telemetry";
        this.event({
          telemetryEventName: event.eventName,
          payload: event.data
        }, eventName);
        break;
      }
    }
  }
  projectsUpdatedInBackgroundEvent(openFiles) {
    this.projectService.logger.info(`got projects updated in background, updating diagnostics for ${openFiles}`);
    if (openFiles.length) {
      if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) {
        this.errorCheck.startNew((next) => this.updateErrorCheck(
          next,
          openFiles,
          100,
          /*requireOpen*/
          true
        ));
      }
      this.event({
        openFiles
      }, ProjectsUpdatedInBackgroundEvent);
    }
  }
  logError(err, cmd) {
    this.logErrorWorker(err, cmd);
  }
  logErrorWorker(err, cmd, fileRequest) {
    let msg = "Exception on executing command " + cmd;
    if (err.message) {
      msg += ":\n" + indent2(err.message);
      if (err.stack) {
        msg += "\n" + indent2(err.stack);
      }
    }
    if (this.logger.hasLevel(3 /* verbose */)) {
      if (fileRequest) {
        try {
          const { file, project } = this.getFileAndProject(fileRequest);
          const scriptInfo = project.getScriptInfoForNormalizedPath(file);
          if (scriptInfo) {
            const text = getSnapshotText(scriptInfo.getSnapshot());
            msg += `

File text of ${fileRequest.file}:${indent2(text)}
`;
          }
        } catch {
        }
      }
      if (err.ProgramFiles) {
        msg += `

Program files: ${JSON.stringify(err.ProgramFiles)}
`;
        msg += `

Projects::
`;
        let counter = 0;
        const addProjectInfo = (project) => {
          msg += `
Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter}
`;
          msg += project.filesToString(
            /*writeProjectFileNames*/
            true
          );
          msg += "\n-----------------------------------------------\n";
          counter++;
        };
        this.projectService.externalProjects.forEach(addProjectInfo);
        this.projectService.configuredProjects.forEach(addProjectInfo);
        this.projectService.inferredProjects.forEach(addProjectInfo);
      }
    }
    this.logger.msg(msg, "Err" /* Err */);
  }
  send(msg) {
    if (msg.type === "event" && !this.canUseEvents) {
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`Session does not support events: ignored event: ${JSON.stringify(msg)}`);
      }
      return;
    }
    this.writeMessage(msg);
  }
  writeMessage(msg) {
    var _a;
    const msgText = formatMessage2(msg, this.logger, this.byteLength, this.host.newLine);
    (_a = perfLogger) == null ? void 0 : _a.logEvent(`Response message size: ${msgText.length}`);
    this.host.write(msgText);
  }
  event(body, eventName) {
    this.send(toEvent(eventName, body));
  }
  /** @internal */
  doOutput(info, cmdName, reqSeq, success, message) {
    const res = {
      seq: 0,
      type: "response",
      command: cmdName,
      request_seq: reqSeq,
      success,
      performanceData: this.performanceData
    };
    if (success) {
      let metadata;
      if (isArray(info)) {
        res.body = info;
        metadata = info.metadata;
        delete info.metadata;
      } else if (typeof info === "object") {
        if (info.metadata) {
          const { metadata: infoMetadata, ...body } = info;
          res.body = body;
          metadata = infoMetadata;
        } else {
          res.body = info;
        }
      } else {
        res.body = info;
      }
      if (metadata)
        res.metadata = metadata;
    } else {
      Debug.assert(info === void 0);
    }
    if (message) {
      res.message = message;
    }
    this.send(res);
  }
  semanticCheck(file, project) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath });
    const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file);
    this.sendDiagnosticsEvent(file, project, diags, "semanticDiag");
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  syntacticCheck(file, project) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath });
    this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag");
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  suggestionCheck(file, project) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath });
    this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag");
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  sendDiagnosticsEvent(file, project, diagnostics, kind) {
    try {
      this.event({ file, diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)) }, kind);
    } catch (err) {
      this.logError(err, kind);
    }
  }
  /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */
  updateErrorCheck(next, checkList, ms, requireOpen = true) {
    Debug.assert(!this.suppressDiagnosticEvents);
    const seq = this.changeSeq;
    const followMs = Math.min(ms, 200);
    let index = 0;
    const goNext = () => {
      index++;
      if (checkList.length > index) {
        next.delay("checkOne", followMs, checkOne);
      }
    };
    const checkOne = () => {
      if (this.changeSeq !== seq) {
        return;
      }
      let item = checkList[index];
      if (isString(item)) {
        item = this.toPendingErrorCheck(item);
        if (!item) {
          goNext();
          return;
        }
      }
      const { fileName, project } = item;
      updateProjectIfDirty(project);
      if (!project.containsFile(fileName, requireOpen)) {
        return;
      }
      this.syntacticCheck(fileName, project);
      if (this.changeSeq !== seq) {
        return;
      }
      if (project.projectService.serverMode !== 0 /* Semantic */) {
        goNext();
        return;
      }
      next.immediate("semanticCheck", () => {
        this.semanticCheck(fileName, project);
        if (this.changeSeq !== seq) {
          return;
        }
        if (this.getPreferences(fileName).disableSuggestions) {
          goNext();
          return;
        }
        next.immediate("suggestionCheck", () => {
          this.suggestionCheck(fileName, project);
          goNext();
        });
      });
    };
    if (checkList.length > index && this.changeSeq === seq) {
      next.delay("checkOne", ms, checkOne);
    }
  }
  cleanProjects(caption, projects) {
    if (!projects) {
      return;
    }
    this.logger.info(`cleaning ${caption}`);
    for (const p of projects) {
      p.getLanguageService(
        /*ensureSynchronized*/
        false
      ).cleanupSemanticCache();
    }
  }
  cleanup() {
    this.cleanProjects("inferred projects", this.projectService.inferredProjects);
    this.cleanProjects("configured projects", arrayFrom(this.projectService.configuredProjects.values()));
    this.cleanProjects("external projects", this.projectService.externalProjects);
    if (this.host.gc) {
      this.logger.info(`host.gc()`);
      this.host.gc();
    }
  }
  getEncodedSyntacticClassifications(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    return languageService.getEncodedSyntacticClassifications(file, args);
  }
  getEncodedSemanticClassifications(args) {
    const { file, project } = this.getFileAndProject(args);
    const format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */;
    return project.getLanguageService().getEncodedSemanticClassifications(file, args, format);
  }
  getProject(projectFileName) {
    return projectFileName === void 0 ? void 0 : this.projectService.findProject(projectFileName);
  }
  getConfigFileAndProject(args) {
    const project = this.getProject(args.projectFileName);
    const file = toNormalizedPath(args.file);
    return {
      configFile: project && project.hasConfigFile(file) ? file : void 0,
      project
    };
  }
  getConfigFileDiagnostics(configFile, project, includeLinePosition) {
    const projectErrors = project.getAllProjectErrors();
    const optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics();
    const diagnosticsForConfigFile = filter(
      concatenate(projectErrors, optionsErrors),
      (diagnostic) => !!diagnostic.file && diagnostic.file.fileName === configFile
    );
    return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map(
      diagnosticsForConfigFile,
      (diagnostic) => formatDiagnosticToProtocol(
        diagnostic,
        /*includeFileName*/
        false
      )
    );
  }
  convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) {
    return diagnostics.map((d) => ({
      message: flattenDiagnosticMessageText(d.messageText, this.host.newLine),
      start: d.start,
      // TODO: GH#18217
      length: d.length,
      // TODO: GH#18217
      category: diagnosticCategoryName(d),
      code: d.code,
      source: d.source,
      startLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start)),
      // TODO: GH#18217
      endLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start + d.length)),
      // TODO: GH#18217
      reportsUnnecessary: d.reportsUnnecessary,
      reportsDeprecated: d.reportsDeprecated,
      relatedInformation: map(d.relatedInformation, formatRelatedInformation)
    }));
  }
  getCompilerOptionsDiagnostics(args) {
    const project = this.getProject(args.projectFileName);
    return this.convertToDiagnosticsWithLinePosition(
      filter(
        project.getLanguageService().getCompilerOptionsDiagnostics(),
        (diagnostic) => !diagnostic.file
      ),
      /*scriptInfo*/
      void 0
    );
  }
  convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) {
    return diagnostics.map((d) => ({
      message: flattenDiagnosticMessageText(d.messageText, this.host.newLine),
      start: d.start,
      length: d.length,
      category: diagnosticCategoryName(d),
      code: d.code,
      source: d.source,
      startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
      // TODO: GH#18217
      endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length),
      reportsUnnecessary: d.reportsUnnecessary,
      reportsDeprecated: d.reportsDeprecated,
      relatedInformation: map(d.relatedInformation, formatRelatedInformation)
    }));
  }
  getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition) {
    const { project, file } = this.getFileAndProject(args);
    if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) {
      return emptyArray2;
    }
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const diagnostics = selector(project, file);
    return includeLinePosition ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) : diagnostics.map((d) => formatDiag(file, project, d));
  }
  getDefinition(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || emptyArray2, project);
    return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session3.mapToOriginalLocation);
  }
  mapDefinitionInfoLocations(definitions, project) {
    return definitions.map((info) => {
      const newDocumentSpan = getMappedDocumentSpanForProject(info, project);
      return !newDocumentSpan ? info : {
        ...newDocumentSpan,
        containerKind: info.containerKind,
        containerName: info.containerName,
        kind: info.kind,
        name: info.name,
        failedAliasResolution: info.failedAliasResolution,
        ...info.unverified && { unverified: info.unverified }
      };
    });
  }
  getDefinitionAndBoundSpan(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const scriptInfo = Debug.checkDefined(project.getScriptInfo(file));
    const unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position);
    if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) {
      return {
        definitions: emptyArray2,
        textSpan: void 0
        // TODO: GH#18217
      };
    }
    const definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project);
    const { textSpan } = unmappedDefinitionAndBoundSpan;
    if (simplifiedResult) {
      return {
        definitions: this.mapDefinitionInfo(definitions, project),
        textSpan: toProtocolTextSpan(textSpan, scriptInfo)
      };
    }
    return {
      definitions: definitions.map(Session3.mapToOriginalLocation),
      textSpan
    };
  }
  findSourceDefinition(args) {
    var _a;
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const unmappedDefinitions = project.getLanguageService().getDefinitionAtPosition(file, position);
    let definitions = this.mapDefinitionInfoLocations(unmappedDefinitions || emptyArray2, project).slice();
    const needsJsResolution = this.projectService.serverMode === 0 /* Semantic */ && (!some(definitions, (d) => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || some(definitions, (d) => !!d.failedAliasResolution));
    if (needsJsResolution) {
      const definitionSet = createSet((d) => d.textSpan.start, documentSpansEqual);
      definitions == null ? void 0 : definitions.forEach((d) => definitionSet.add(d));
      const noDtsProject = project.getNoDtsResolutionProject([file]);
      const ls = noDtsProject.getLanguageService();
      const jsDefinitions = (_a = ls.getDefinitionAtPosition(
        file,
        position,
        /*searchOtherFilesOnly*/
        true,
        /*stopAtAlias*/
        false
      )) == null ? void 0 : _a.filter((d) => toNormalizedPath(d.fileName) !== file);
      if (some(jsDefinitions)) {
        for (const jsDefinition of jsDefinitions) {
          if (jsDefinition.unverified) {
            const refined = tryRefineDefinition(jsDefinition, project.getLanguageService().getProgram(), ls.getProgram());
            if (some(refined)) {
              for (const def of refined) {
                definitionSet.add(def);
              }
              continue;
            }
          }
          definitionSet.add(jsDefinition);
        }
      } else {
        const ambientCandidates = definitions.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient);
        for (const candidate of some(ambientCandidates) ? ambientCandidates : getAmbientCandidatesByClimbingAccessChain()) {
          const fileNameToSearch = findImplementationFileFromDtsFileName(candidate.fileName, file, noDtsProject);
          if (!fileNameToSearch || !ensureRoot(noDtsProject, fileNameToSearch)) {
            continue;
          }
          const noDtsProgram = ls.getProgram();
          const fileToSearch = Debug.checkDefined(noDtsProgram.getSourceFile(fileNameToSearch));
          for (const match of searchForDeclaration(candidate.name, fileToSearch, noDtsProgram)) {
            definitionSet.add(match);
          }
        }
      }
      definitions = arrayFrom(definitionSet.values());
    }
    definitions = definitions.filter((d) => !d.isAmbient && !d.failedAliasResolution);
    return this.mapDefinitionInfo(definitions, project);
    function findImplementationFileFromDtsFileName(fileName, resolveFromFile, auxiliaryProject) {
      var _a2, _b, _c;
      const nodeModulesPathParts = getNodeModulePathParts(fileName);
      if (nodeModulesPathParts && fileName.lastIndexOf(nodeModulesPathPart) === nodeModulesPathParts.topLevelNodeModulesIndex) {
        const packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex);
        const packageJsonCache = (_a2 = project.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache();
        const compilerOptions = project.getCompilationSettings();
        const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory + "/package.json", project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions));
        if (!packageJson)
          return void 0;
        const entrypoints = getEntrypointsFromPackageJsonInfo(
          packageJson,
          { moduleResolution: 2 /* Node10 */ },
          project,
          project.getModuleResolutionCache()
        );
        const packageNamePathPart = fileName.substring(
          nodeModulesPathParts.topLevelPackageNameIndex + 1,
          nodeModulesPathParts.packageRootIndex
        );
        const packageName = getPackageNameFromTypesPackageName(unmangleScopedPackageName(packageNamePathPart));
        const path = project.toPath(fileName);
        if (entrypoints && some(entrypoints, (e) => project.toPath(e) === path)) {
          return (_b = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(packageName, resolveFromFile).resolvedModule) == null ? void 0 : _b.resolvedFileName;
        } else {
          const pathToFileInPackage = fileName.substring(nodeModulesPathParts.packageRootIndex + 1);
          const specifier = `${packageName}/${removeFileExtension(pathToFileInPackage)}`;
          return (_c = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(specifier, resolveFromFile).resolvedModule) == null ? void 0 : _c.resolvedFileName;
        }
      }
      return void 0;
    }
    function getAmbientCandidatesByClimbingAccessChain() {
      const ls = project.getLanguageService();
      const program = ls.getProgram();
      const initialNode = getTouchingPropertyName(program.getSourceFile(file), position);
      if ((isStringLiteralLike(initialNode) || isIdentifier(initialNode)) && isAccessExpression(initialNode.parent)) {
        return forEachNameInAccessChainWalkingLeft(initialNode, (nameInChain) => {
          var _a2;
          if (nameInChain === initialNode)
            return void 0;
          const candidates = (_a2 = ls.getDefinitionAtPosition(
            file,
            nameInChain.getStart(),
            /*searchOtherFilesOnly*/
            true,
            /*stopAtAlias*/
            false
          )) == null ? void 0 : _a2.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient).map((d) => ({
            fileName: d.fileName,
            name: getTextOfIdentifierOrLiteral(initialNode)
          }));
          if (some(candidates)) {
            return candidates;
          }
        }) || emptyArray2;
      }
      return emptyArray2;
    }
    function tryRefineDefinition(definition, program, noDtsProgram) {
      var _a2;
      const fileToSearch = noDtsProgram.getSourceFile(definition.fileName);
      if (!fileToSearch) {
        return void 0;
      }
      const initialNode = getTouchingPropertyName(program.getSourceFile(file), position);
      const symbol = program.getTypeChecker().getSymbolAtLocation(initialNode);
      const importSpecifier = symbol && getDeclarationOfKind(symbol, 275 /* ImportSpecifier */);
      if (!importSpecifier)
        return void 0;
      const nameToSearch = ((_a2 = importSpecifier.propertyName) == null ? void 0 : _a2.text) || importSpecifier.name.text;
      return searchForDeclaration(nameToSearch, fileToSearch, noDtsProgram);
    }
    function searchForDeclaration(declarationName, fileToSearch, noDtsProgram) {
      const matches = ts_FindAllReferences_exports.Core.getTopMostDeclarationNamesInFile(declarationName, fileToSearch);
      return mapDefined(matches, (match) => {
        const symbol = noDtsProgram.getTypeChecker().getSymbolAtLocation(match);
        const decl = getDeclarationFromName(match);
        if (symbol && decl) {
          return ts_GoToDefinition_exports.createDefinitionInfo(
            decl,
            noDtsProgram.getTypeChecker(),
            symbol,
            decl,
            /*unverified*/
            true
          );
        }
      });
    }
    function ensureRoot(project2, fileName) {
      const info = project2.getScriptInfo(fileName);
      if (!info)
        return false;
      if (!project2.containsScriptInfo(info)) {
        project2.addRoot(info);
        project2.updateGraph();
      }
      return true;
    }
  }
  getEmitOutput(args) {
    const { file, project } = this.getFileAndProject(args);
    if (!project.shouldEmitFile(project.getScriptInfo(file))) {
      return { emitSkipped: true, outputFiles: [], diagnostics: [] };
    }
    const result = project.getLanguageService().getEmitOutput(file);
    return args.richResponse ? {
      ...result,
      diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : result.diagnostics.map((d) => formatDiagnosticToProtocol(
        d,
        /*includeFileName*/
        true
      ))
    } : result;
  }
  mapJSDocTagInfo(tags, project, richResponse) {
    return tags ? tags.map((tag) => {
      var _a;
      return {
        ...tag,
        text: richResponse ? this.mapDisplayParts(tag.text, project) : (_a = tag.text) == null ? void 0 : _a.map((part) => part.text).join("")
      };
    }) : [];
  }
  mapDisplayParts(parts, project) {
    if (!parts) {
      return [];
    }
    return parts.map((part) => part.kind !== "linkName" ? part : {
      ...part,
      target: this.toFileSpan(part.target.fileName, part.target.textSpan, project)
    });
  }
  mapSignatureHelpItems(items, project, richResponse) {
    return items.map((item) => ({
      ...item,
      documentation: this.mapDisplayParts(item.documentation, project),
      parameters: item.parameters.map((p) => ({ ...p, documentation: this.mapDisplayParts(p.documentation, project) })),
      tags: this.mapJSDocTagInfo(item.tags, project, richResponse)
    }));
  }
  mapDefinitionInfo(definitions, project) {
    return definitions.map((def) => ({ ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), ...def.unverified && { unverified: def.unverified } }));
  }
  /*
   * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in
   * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols.
   * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a
   * set of additional fields, and does the reverse for VS (store the .d.ts location where
   * it used to be and stores the .ts location in the additional fields).
  */
  static mapToOriginalLocation(def) {
    if (def.originalFileName) {
      Debug.assert(def.originalTextSpan !== void 0, "originalTextSpan should be present if originalFileName is");
      return {
        ...def,
        fileName: def.originalFileName,
        textSpan: def.originalTextSpan,
        targetFileName: def.fileName,
        targetTextSpan: def.textSpan,
        contextSpan: def.originalContextSpan,
        targetContextSpan: def.contextSpan
      };
    }
    return def;
  }
  toFileSpan(fileName, textSpan, project) {
    const ls = project.getLanguageService();
    const start2 = ls.toLineColumnOffset(fileName, textSpan.start);
    const end = ls.toLineColumnOffset(fileName, textSpanEnd(textSpan));
    return {
      file: fileName,
      start: { line: start2.line + 1, offset: start2.character + 1 },
      end: { line: end.line + 1, offset: end.character + 1 }
    };
  }
  toFileSpanWithContext(fileName, textSpan, contextSpan, project) {
    const fileSpan = this.toFileSpan(fileName, textSpan, project);
    const context = contextSpan && this.toFileSpan(fileName, contextSpan, project);
    return context ? { ...fileSpan, contextStart: context.start, contextEnd: context.end } : fileSpan;
  }
  getTypeDefinition(args) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || emptyArray2, project);
    return this.mapDefinitionInfo(definitions, project);
  }
  mapImplementationLocations(implementations, project) {
    return implementations.map((info) => {
      const newDocumentSpan = getMappedDocumentSpanForProject(info, project);
      return !newDocumentSpan ? info : {
        ...newDocumentSpan,
        kind: info.kind,
        displayParts: info.displayParts
      };
    });
  }
  getImplementation(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || emptyArray2, project);
    return simplifiedResult ? implementations.map(({ fileName, textSpan, contextSpan }) => this.toFileSpanWithContext(fileName, textSpan, contextSpan, project)) : implementations.map(Session3.mapToOriginalLocation);
  }
  getSyntacticDiagnosticsSync(args) {
    const { configFile } = this.getConfigFileAndProject(args);
    if (configFile) {
      return emptyArray2;
    }
    return this.getDiagnosticsWorker(
      args,
      /*isSemantic*/
      false,
      (project, file) => project.getLanguageService().getSyntacticDiagnostics(file),
      !!args.includeLinePosition
    );
  }
  getSemanticDiagnosticsSync(args) {
    const { configFile, project } = this.getConfigFileAndProject(args);
    if (configFile) {
      return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition);
    }
    return this.getDiagnosticsWorker(
      args,
      /*isSemantic*/
      true,
      (project2, file) => project2.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file),
      !!args.includeLinePosition
    );
  }
  getSuggestionDiagnosticsSync(args) {
    const { configFile } = this.getConfigFileAndProject(args);
    if (configFile) {
      return emptyArray2;
    }
    return this.getDiagnosticsWorker(
      args,
      /*isSemantic*/
      true,
      (project, file) => project.getLanguageService().getSuggestionDiagnostics(file),
      !!args.includeLinePosition
    );
  }
  getJsxClosingTag(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    const tag = languageService.getJsxClosingTagAtPosition(file, position);
    return tag === void 0 ? void 0 : { newText: tag.newText, caretOffset: 0 };
  }
  getLinkedEditingRange(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    const linkedEditInfo = languageService.getLinkedEditingRangeAtPosition(file, position);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    if (scriptInfo === void 0 || linkedEditInfo === void 0)
      return void 0;
    return convertLinkedEditInfoToRanges(linkedEditInfo, scriptInfo);
  }
  getDocumentHighlights(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch);
    if (!documentHighlights)
      return emptyArray2;
    if (!simplifiedResult)
      return documentHighlights;
    return documentHighlights.map(({ fileName, highlightSpans }) => {
      const scriptInfo = project.getScriptInfo(fileName);
      return {
        file: fileName,
        highlightSpans: highlightSpans.map(({ textSpan, kind, contextSpan }) => ({
          ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo),
          kind
        }))
      };
    });
  }
  provideInlayHints(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const hints = project.getLanguageService().provideInlayHints(file, args, this.getPreferences(file));
    return hints.map((hint) => ({
      ...hint,
      position: scriptInfo.positionToLineOffset(hint.position)
    }));
  }
  setCompilerOptionsForInferredProjects(args) {
    this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath);
  }
  getProjectInfo(args) {
    return this.getProjectInfoWorker(
      args.file,
      args.projectFileName,
      args.needFileNameList,
      /*excludeConfigFiles*/
      false
    );
  }
  getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) {
    const { project } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName);
    updateProjectIfDirty(project);
    const projectInfo = {
      configFileName: project.getProjectName(),
      languageServiceDisabled: !project.languageServiceEnabled,
      fileNames: needFileNameList ? project.getFileNames(
        /*excludeFilesFromExternalLibraries*/
        false,
        excludeConfigFiles
      ) : void 0
    };
    return projectInfo;
  }
  getRenameInfo(args) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const preferences = this.getPreferences(file);
    return project.getLanguageService().getRenameInfo(file, position, preferences);
  }
  getProjects(args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) {
    let projects;
    let symLinkedProjects;
    if (args.projectFileName) {
      const project = this.getProject(args.projectFileName);
      if (project) {
        projects = [project];
      }
    } else {
      const scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file);
      if (!scriptInfo) {
        if (ignoreNoProjectError)
          return emptyArray2;
        this.projectService.logErrorForScriptInfoNotFound(args.file);
        return Errors.ThrowNoProject();
      } else if (!getScriptInfoEnsuringProjectsUptoDate) {
        this.projectService.ensureDefaultProjectForFile(scriptInfo);
      }
      projects = scriptInfo.containingProjects;
      symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo);
    }
    projects = filter(projects, (p) => p.languageServiceEnabled && !p.isOrphan());
    if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) {
      this.projectService.logErrorForScriptInfoNotFound(args.file ?? args.projectFileName);
      return Errors.ThrowNoProject();
    }
    return symLinkedProjects ? { projects, symLinkedProjects } : projects;
  }
  getDefaultProject(args) {
    if (args.projectFileName) {
      const project = this.getProject(args.projectFileName);
      if (project) {
        return project;
      }
      if (!args.file) {
        return Errors.ThrowNoProject();
      }
    }
    const info = this.projectService.getScriptInfo(args.file);
    return info.getDefaultProject();
  }
  getRenameLocations(args, simplifiedResult) {
    const file = toNormalizedPath(args.file);
    const position = this.getPositionInFile(args, file);
    const projects = this.getProjects(args);
    const defaultProject = this.getDefaultProject(args);
    const preferences = this.getPreferences(file);
    const renameInfo = this.mapRenameInfo(
      defaultProject.getLanguageService().getRenameInfo(file, position, preferences),
      Debug.checkDefined(this.projectService.getScriptInfo(file))
    );
    if (!renameInfo.canRename)
      return simplifiedResult ? { info: renameInfo, locs: [] } : [];
    const locations = getRenameLocationsWorker(
      projects,
      defaultProject,
      { fileName: args.file, pos: position },
      !!args.findInStrings,
      !!args.findInComments,
      preferences
    );
    if (!simplifiedResult)
      return locations;
    return { info: renameInfo, locs: this.toSpanGroups(locations) };
  }
  mapRenameInfo(info, scriptInfo) {
    if (info.canRename) {
      const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info;
      return identity(
        { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) }
      );
    } else {
      return info;
    }
  }
  toSpanGroups(locations) {
    const map2 = /* @__PURE__ */ new Map();
    for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) {
      let group2 = map2.get(fileName);
      if (!group2)
        map2.set(fileName, group2 = { file: fileName, locs: [] });
      const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName));
      group2.locs.push({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), ...prefixSuffixText });
    }
    return arrayFrom(map2.values());
  }
  getReferences(args, simplifiedResult) {
    const file = toNormalizedPath(args.file);
    const projects = this.getProjects(args);
    const position = this.getPositionInFile(args, file);
    const references = getReferencesWorker(
      projects,
      this.getDefaultProject(args),
      { fileName: args.file, pos: position },
      this.logger
    );
    if (!simplifiedResult)
      return references;
    const preferences = this.getPreferences(file);
    const defaultProject = this.getDefaultProject(args);
    const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file);
    const nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position);
    const symbolDisplayString = nameInfo ? displayPartsToString(nameInfo.displayParts) : "";
    const nameSpan = nameInfo && nameInfo.textSpan;
    const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0;
    const symbolName2 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : "";
    const refs = flatMap(references, (referencedSymbol) => {
      return referencedSymbol.references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences));
    });
    return { refs, symbolName: symbolName2, symbolStartOffset, symbolDisplayString };
  }
  getFileReferences(args, simplifiedResult) {
    const projects = this.getProjects(args);
    const fileName = args.file;
    const preferences = this.getPreferences(toNormalizedPath(fileName));
    const references = [];
    const seen = createDocumentSpanSet();
    forEachProjectInProjects(
      projects,
      /*path*/
      void 0,
      (project) => {
        if (project.getCancellationToken().isCancellationRequested())
          return;
        const projectOutputs = project.getLanguageService().getFileReferences(fileName);
        if (projectOutputs) {
          for (const referenceEntry of projectOutputs) {
            if (!seen.has(referenceEntry)) {
              references.push(referenceEntry);
              seen.add(referenceEntry);
            }
          }
        }
      }
    );
    if (!simplifiedResult)
      return references;
    const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences));
    return {
      refs,
      symbolName: `"${args.file}"`
    };
  }
  /**
   * @param fileName is the name of the file to be opened
   * @param fileContent is a version of the file content that is known to be more up to date than the one on disk
   */
  openClientFile(fileName, fileContent, scriptKind, projectRootPath) {
    this.projectService.openClientFileWithNormalizedPath(
      fileName,
      fileContent,
      scriptKind,
      /*hasMixedContent*/
      false,
      projectRootPath
    );
  }
  getPosition(args, scriptInfo) {
    return args.position !== void 0 ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
  }
  getPositionInFile(args, file) {
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    return this.getPosition(args, scriptInfo);
  }
  getFileAndProject(args) {
    return this.getFileAndProjectWorker(args.file, args.projectFileName);
  }
  getFileAndLanguageServiceForSyntacticOperation(args) {
    const { file, project } = this.getFileAndProject(args);
    return {
      file,
      languageService: project.getLanguageService(
        /*ensureSynchronized*/
        false
      )
    };
  }
  getFileAndProjectWorker(uncheckedFileName, projectFileName) {
    const file = toNormalizedPath(uncheckedFileName);
    const project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file);
    return { file, project };
  }
  getOutliningSpans(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const spans = languageService.getOutliningSpans(file);
    if (simplifiedResult) {
      const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
      return spans.map((s) => ({
        textSpan: toProtocolTextSpan(s.textSpan, scriptInfo),
        hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo),
        bannerText: s.bannerText,
        autoCollapse: s.autoCollapse,
        kind: s.kind
      }));
    } else {
      return spans;
    }
  }
  getTodoComments(args) {
    const { file, project } = this.getFileAndProject(args);
    return project.getLanguageService().getTodoComments(file, args.descriptors);
  }
  getDocCommentTemplate(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file));
  }
  getSpanOfEnclosingComment(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const onlyMultiLine = args.onlyMultiLine;
    const position = this.getPositionInFile(args, file);
    return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine);
  }
  getIndentation(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    const indentation = languageService.getIndentationAtPosition(file, position, options);
    return { position, indentation };
  }
  getBreakpointStatement(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.getBreakpointStatementAtPosition(file, position);
  }
  getNameOrDottedNameSpan(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.getNameOrDottedNameSpan(file, position, position);
  }
  isValidBraceCompletion(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0));
  }
  getQuickInfoWorker(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo));
    if (!quickInfo) {
      return void 0;
    }
    const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc;
    if (simplifiedResult) {
      const displayString = displayPartsToString(quickInfo.displayParts);
      return {
        kind: quickInfo.kind,
        kindModifiers: quickInfo.kindModifiers,
        start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start),
        end: scriptInfo.positionToLineOffset(textSpanEnd(quickInfo.textSpan)),
        displayString,
        documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : displayPartsToString(quickInfo.documentation),
        tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts)
      };
    } else {
      return useDisplayParts ? quickInfo : {
        ...quickInfo,
        tags: this.mapJSDocTagInfo(
          quickInfo.tags,
          project,
          /*richResponse*/
          false
        )
      };
    }
  }
  getFormattingEditsForRange(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
    const endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
    const edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file));
    if (!edits) {
      return void 0;
    }
    return edits.map((edit) => this.convertTextChangeToCodeEdit(edit, scriptInfo));
  }
  getFormattingEditsForRangeFull(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options);
  }
  getFormattingEditsForDocumentFull(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    return languageService.getFormattingEditsForDocument(file, options);
  }
  getFormattingEditsAfterKeystrokeFull(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options);
  }
  getFormattingEditsAfterKeystroke(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
    const formatOptions = this.getFormatOptions(file);
    const edits = languageService.getFormattingEditsAfterKeystroke(
      file,
      position,
      args.key,
      formatOptions
    );
    if (args.key === "\n" && (!edits || edits.length === 0 || allEditsBeforePos(edits, position))) {
      const { lineText, absolutePosition } = scriptInfo.textStorage.getAbsolutePositionAndLineText(args.line);
      if (lineText && lineText.search("\\S") < 0) {
        const preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions);
        let hasIndent = 0;
        let i, len;
        for (i = 0, len = lineText.length; i < len; i++) {
          if (lineText.charAt(i) === " ") {
            hasIndent++;
          } else if (lineText.charAt(i) === "	") {
            hasIndent += formatOptions.tabSize;
          } else {
            break;
          }
        }
        if (preferredIndent !== hasIndent) {
          const firstNoWhiteSpacePosition = absolutePosition + i;
          edits.push({
            span: createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition),
            newText: ts_formatting_exports.getIndentationString(preferredIndent, formatOptions)
          });
        }
      }
    }
    if (!edits) {
      return void 0;
    }
    return edits.map((edit) => {
      return {
        start: scriptInfo.positionToLineOffset(edit.span.start),
        end: scriptInfo.positionToLineOffset(textSpanEnd(edit.span)),
        newText: edit.newText ? edit.newText : ""
      };
    });
  }
  getCompletions(args, kind) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const completions = project.getLanguageService().getCompletionsAtPosition(
      file,
      position,
      {
        ...convertUserPreferences(this.getPreferences(file)),
        triggerCharacter: args.triggerCharacter,
        triggerKind: args.triggerKind,
        includeExternalModuleExports: args.includeExternalModuleExports,
        includeInsertTextCompletions: args.includeInsertTextCompletions
      },
      project.projectService.getFormatCodeOptions(file)
    );
    if (completions === void 0)
      return void 0;
    if (kind === "completions-full" /* CompletionsFull */)
      return completions;
    const prefix = args.prefix || "";
    const entries = mapDefined(completions.entries, (entry) => {
      if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
        const {
          name,
          kind: kind2,
          kindModifiers,
          sortText,
          insertText,
          replacementSpan,
          hasAction,
          source,
          sourceDisplay,
          labelDetails,
          isSnippet,
          isRecommended,
          isPackageJsonImport,
          isImportStatementCompletion,
          data
        } = entry;
        const convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : void 0;
        return {
          name,
          kind: kind2,
          kindModifiers,
          sortText,
          insertText,
          replacementSpan: convertedSpan,
          isSnippet,
          hasAction: hasAction || void 0,
          source,
          sourceDisplay,
          labelDetails,
          isRecommended,
          isPackageJsonImport,
          isImportStatementCompletion,
          data
        };
      }
    });
    if (kind === "completions" /* Completions */) {
      if (completions.metadata)
        entries.metadata = completions.metadata;
      return entries;
    }
    const res = {
      ...completions,
      optionalReplacementSpan: completions.optionalReplacementSpan && toProtocolTextSpan(completions.optionalReplacementSpan, scriptInfo),
      entries
    };
    return res;
  }
  getCompletionEntryDetails(args, fullResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const formattingOptions = project.projectService.getFormatCodeOptions(file);
    const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc;
    const result = mapDefined(args.entryNames, (entryName) => {
      const { name, source, data } = typeof entryName === "string" ? { name: entryName, source: void 0, data: void 0 } : entryName;
      return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file), data ? cast(data, isCompletionEntryData) : void 0);
    });
    return fullResult ? useDisplayParts ? result : result.map((details) => ({ ...details, tags: this.mapJSDocTagInfo(
      details.tags,
      project,
      /*richResponse*/
      false
    ) })) : result.map((details) => ({
      ...details,
      codeActions: map(details.codeActions, (action) => this.mapCodeAction(action)),
      documentation: this.mapDisplayParts(details.documentation, project),
      tags: this.mapJSDocTagInfo(details.tags, project, useDisplayParts)
    }));
  }
  getCompileOnSaveAffectedFileList(args) {
    const projects = this.getProjects(
      args,
      /*getScriptInfoEnsuringProjectsUptoDate*/
      true,
      /*ignoreNoProjectError*/
      true
    );
    const info = this.projectService.getScriptInfo(args.file);
    if (!info) {
      return emptyArray2;
    }
    return combineProjectOutput(
      info,
      (path) => this.projectService.getScriptInfoForPath(path),
      projects,
      (project, info2) => {
        if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) {
          return void 0;
        }
        const compilationSettings = project.getCompilationSettings();
        if (!!compilationSettings.noEmit || isDeclarationFileName(info2.fileName) && !dtsChangeCanAffectEmit(compilationSettings)) {
          return void 0;
        }
        return {
          projectFileName: project.getProjectName(),
          fileNames: project.getCompileOnSaveAffectedFileList(info2),
          projectUsesOutFile: !!outFile(compilationSettings)
        };
      }
    );
  }
  emitFile(args) {
    const { file, project } = this.getFileAndProject(args);
    if (!project) {
      Errors.ThrowNoProject();
    }
    if (!project.languageServiceEnabled) {
      return args.richResponse ? { emitSkipped: true, diagnostics: [] } : false;
    }
    const scriptInfo = project.getScriptInfo(file);
    const { emitSkipped, diagnostics } = project.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark));
    return args.richResponse ? {
      emitSkipped,
      diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : diagnostics.map((d) => formatDiagnosticToProtocol(
        d,
        /*includeFileName*/
        true
      ))
    } : !emitSkipped;
  }
  getSignatureHelpItems(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args);
    const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc;
    if (helpItems && simplifiedResult) {
      const span = helpItems.applicableSpan;
      return {
        ...helpItems,
        applicableSpan: {
          start: scriptInfo.positionToLineOffset(span.start),
          end: scriptInfo.positionToLineOffset(span.start + span.length)
        },
        items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts)
      };
    } else if (useDisplayParts || !helpItems) {
      return helpItems;
    } else {
      return {
        ...helpItems,
        items: helpItems.items.map((item) => ({ ...item, tags: this.mapJSDocTagInfo(
          item.tags,
          project,
          /*richResponse*/
          false
        ) }))
      };
    }
  }
  toPendingErrorCheck(uncheckedFileName) {
    const fileName = toNormalizedPath(uncheckedFileName);
    const project = this.projectService.tryGetDefaultProjectForFile(fileName);
    return project && { fileName, project };
  }
  getDiagnostics(next, delay, fileNames) {
    if (this.suppressDiagnosticEvents) {
      return;
    }
    if (fileNames.length > 0) {
      this.updateErrorCheck(next, fileNames, delay);
    }
  }
  change(args) {
    const scriptInfo = this.projectService.getScriptInfo(args.file);
    Debug.assert(!!scriptInfo);
    scriptInfo.textStorage.switchToScriptVersionCache();
    const start2 = scriptInfo.lineOffsetToPosition(args.line, args.offset);
    const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
    if (start2 >= 0) {
      this.changeSeq++;
      this.projectService.applyChangesToFile(scriptInfo, singleIterator({
        span: { start: start2, length: end - start2 },
        newText: args.insertString
        // TODO: GH#18217
      }));
    }
  }
  reload(args, reqSeq) {
    const file = toNormalizedPath(args.file);
    const tempFileName = args.tmpfile === void 0 ? void 0 : toNormalizedPath(args.tmpfile);
    const info = this.projectService.getScriptInfoForNormalizedPath(file);
    if (info) {
      this.changeSeq++;
      if (info.reloadFromFile(tempFileName)) {
        this.doOutput(
          /*info*/
          void 0,
          "reload" /* Reload */,
          reqSeq,
          /*success*/
          true
        );
      }
    }
  }
  saveToTmp(fileName, tempFileName) {
    const scriptInfo = this.projectService.getScriptInfo(fileName);
    if (scriptInfo) {
      scriptInfo.saveTo(tempFileName);
    }
  }
  closeClientFile(fileName) {
    if (!fileName) {
      return;
    }
    const file = normalizePath(fileName);
    this.projectService.closeClientFile(file);
  }
  mapLocationNavigationBarItems(items, scriptInfo) {
    return map(items, (item) => ({
      text: item.text,
      kind: item.kind,
      kindModifiers: item.kindModifiers,
      spans: item.spans.map((span) => toProtocolTextSpan(span, scriptInfo)),
      childItems: this.mapLocationNavigationBarItems(item.childItems, scriptInfo),
      indent: item.indent
    }));
  }
  getNavigationBarItems(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const items = languageService.getNavigationBarItems(file);
    return !items ? void 0 : simplifiedResult ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items;
  }
  toLocationNavigationTree(tree, scriptInfo) {
    return {
      text: tree.text,
      kind: tree.kind,
      kindModifiers: tree.kindModifiers,
      spans: tree.spans.map((span) => toProtocolTextSpan(span, scriptInfo)),
      nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo),
      childItems: map(tree.childItems, (item) => this.toLocationNavigationTree(item, scriptInfo))
    };
  }
  getNavigationTree(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const tree = languageService.getNavigationTree(file);
    return !tree ? void 0 : simplifiedResult ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree;
  }
  getNavigateToItems(args, simplifiedResult) {
    const full = this.getFullNavigateToItems(args);
    return !simplifiedResult ? flatMap(full, ({ navigateToItems }) => navigateToItems) : flatMap(
      full,
      ({ project, navigateToItems }) => navigateToItems.map((navItem) => {
        const scriptInfo = project.getScriptInfo(navItem.fileName);
        const bakedItem = {
          name: navItem.name,
          kind: navItem.kind,
          kindModifiers: navItem.kindModifiers,
          isCaseSensitive: navItem.isCaseSensitive,
          matchKind: navItem.matchKind,
          file: navItem.fileName,
          start: scriptInfo.positionToLineOffset(navItem.textSpan.start),
          end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan))
        };
        if (navItem.kindModifiers && navItem.kindModifiers !== "") {
          bakedItem.kindModifiers = navItem.kindModifiers;
        }
        if (navItem.containerName && navItem.containerName.length > 0) {
          bakedItem.containerName = navItem.containerName;
        }
        if (navItem.containerKind && navItem.containerKind.length > 0) {
          bakedItem.containerKind = navItem.containerKind;
        }
        return bakedItem;
      })
    );
  }
  getFullNavigateToItems(args) {
    const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args;
    if (currentFileOnly) {
      Debug.assertIsDefined(args.file);
      const { file, project } = this.getFileAndProject(args);
      return [{ project, navigateToItems: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }];
    }
    const outputs = [];
    const seenItems = /* @__PURE__ */ new Map();
    if (!args.file && !projectFileName) {
      this.projectService.loadAncestorProjectTree();
      this.projectService.forEachEnabledProject((project) => addItemsForProject(project));
    } else {
      const projects = this.getProjects(args);
      forEachProjectInProjects(
        projects,
        /*path*/
        void 0,
        (project) => addItemsForProject(project)
      );
    }
    return outputs;
    function addItemsForProject(project) {
      const projectItems = project.getLanguageService().getNavigateToItems(
        searchValue,
        maxResultCount,
        /*fileName*/
        void 0,
        /*excludeDts*/
        project.isNonTsProject()
      );
      const unseenItems = filter(projectItems, (item) => tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project));
      if (unseenItems.length) {
        outputs.push({ project, navigateToItems: unseenItems });
      }
    }
    function tryAddSeenItem(item) {
      const name = item.name;
      if (!seenItems.has(name)) {
        seenItems.set(name, [item]);
        return true;
      }
      const seen = seenItems.get(name);
      for (const seenItem of seen) {
        if (navigateToItemIsEqualTo(seenItem, item)) {
          return false;
        }
      }
      seen.push(item);
      return true;
    }
    function navigateToItemIsEqualTo(a, b) {
      if (a === b) {
        return true;
      }
      if (!a || !b) {
        return false;
      }
      return a.containerKind === b.containerKind && a.containerName === b.containerName && a.fileName === b.fileName && a.isCaseSensitive === b.isCaseSensitive && a.kind === b.kind && a.kindModifiers === b.kindModifiers && a.matchKind === b.matchKind && a.name === b.name && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length;
    }
  }
  getSupportedCodeFixes(args) {
    if (!args)
      return getSupportedCodeFixes();
    if (args.file) {
      const { file, project: project2 } = this.getFileAndProject(args);
      return project2.getLanguageService().getSupportedCodeFixes(file);
    }
    const project = this.getProject(args.projectFileName);
    if (!project)
      Errors.ThrowNoProject();
    return project.getLanguageService().getSupportedCodeFixes();
  }
  isLocation(locationOrSpan) {
    return locationOrSpan.line !== void 0;
  }
  extractPositionOrRange(args, scriptInfo) {
    let position;
    let textRange;
    if (this.isLocation(args)) {
      position = getPosition(args);
    } else {
      textRange = this.getRange(args, scriptInfo);
    }
    return Debug.checkDefined(position === void 0 ? textRange : position);
    function getPosition(loc) {
      return loc.position !== void 0 ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
    }
  }
  getRange(args, scriptInfo) {
    const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
    return { pos: startPosition, end: endPosition };
  }
  getApplicableRefactors(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions);
  }
  getEditsForRefactor(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const result = project.getLanguageService().getEditsForRefactor(
      file,
      this.getFormatOptions(file),
      this.extractPositionOrRange(args, scriptInfo),
      args.refactor,
      args.action,
      this.getPreferences(file),
      args.interactiveRefactorArguments
    );
    if (result === void 0) {
      return {
        edits: []
      };
    }
    if (simplifiedResult) {
      const { renameFilename, renameLocation, edits } = result;
      let mappedRenameLocation;
      if (renameFilename !== void 0 && renameLocation !== void 0) {
        const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename));
        mappedRenameLocation = getLocationInNewDocument(getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits);
      }
      return {
        renameLocation: mappedRenameLocation,
        renameFilename,
        edits: this.mapTextChangesToCodeEdits(edits),
        notApplicableReason: result.notApplicableReason
      };
    }
    return result;
  }
  getMoveToRefactoringFileSuggestions(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file));
  }
  organizeImports(args, simplifiedResult) {
    Debug.assert(args.scope.type === "file");
    const { file, project } = this.getFileAndProject(args.scope.args);
    const changes = project.getLanguageService().organizeImports(
      {
        fileName: file,
        mode: args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : void 0),
        type: "file"
      },
      this.getFormatOptions(file),
      this.getPreferences(file)
    );
    if (simplifiedResult) {
      return this.mapTextChangesToCodeEdits(changes);
    } else {
      return changes;
    }
  }
  getEditsForFileRename(args, simplifiedResult) {
    const oldPath = toNormalizedPath(args.oldFilePath);
    const newPath = toNormalizedPath(args.newFilePath);
    const formatOptions = this.getHostFormatOptions();
    const preferences = this.getHostPreferences();
    const seenFiles = /* @__PURE__ */ new Set();
    const textChanges2 = [];
    this.projectService.loadAncestorProjectTree();
    this.projectService.forEachEnabledProject((project) => {
      const projectTextChanges = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences);
      const projectFiles = [];
      for (const textChange of projectTextChanges) {
        if (!seenFiles.has(textChange.fileName)) {
          textChanges2.push(textChange);
          projectFiles.push(textChange.fileName);
        }
      }
      for (const file of projectFiles) {
        seenFiles.add(file);
      }
    });
    return simplifiedResult ? textChanges2.map((c) => this.mapTextChangeToCodeEdit(c)) : textChanges2;
  }
  getCodeFixes(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
    let codeActions;
    try {
      codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file));
    } catch (e) {
      const ls = project.getLanguageService();
      const existingDiagCodes = [
        ...ls.getSyntacticDiagnostics(file),
        ...ls.getSemanticDiagnostics(file),
        ...ls.getSuggestionDiagnostics(file)
      ].map((d) => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) && d.code);
      const badCode = args.errorCodes.find((c) => !existingDiagCodes.includes(c));
      if (badCode !== void 0) {
        e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error:
${e.message}`;
      }
      throw e;
    }
    return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions;
  }
  getCombinedCodeFix({ scope, fixId: fixId52 }, simplifiedResult) {
    Debug.assert(scope.type === "file");
    const { file, project } = this.getFileAndProject(scope.args);
    const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId52, this.getFormatOptions(file), this.getPreferences(file));
    if (simplifiedResult) {
      return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands };
    } else {
      return res;
    }
  }
  applyCodeActionCommand(args) {
    const commands = args.command;
    for (const command of toArray(commands)) {
      const { file, project } = this.getFileAndProject(command);
      project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(
        (_result) => {
        },
        (_error) => {
        }
      );
    }
    return {};
  }
  getStartAndEndPosition(args, scriptInfo) {
    let startPosition, endPosition;
    if (args.startPosition !== void 0) {
      startPosition = args.startPosition;
    } else {
      startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
      args.startPosition = startPosition;
    }
    if (args.endPosition !== void 0) {
      endPosition = args.endPosition;
    } else {
      endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
      args.endPosition = endPosition;
    }
    return { startPosition, endPosition };
  }
  mapCodeAction({ description: description3, changes, commands }) {
    return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands };
  }
  mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId52, fixAllDescription }) {
    return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription };
  }
  mapTextChangesToCodeEdits(textChanges2) {
    return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change));
  }
  mapTextChangeToCodeEdit(textChanges2) {
    const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges2.fileName);
    if (!!textChanges2.isNewFile === !!scriptInfo) {
      if (!scriptInfo) {
        this.projectService.logErrorForScriptInfoNotFound(textChanges2.fileName);
      }
      Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges2.isNewFile, hasScriptInfo: !!scriptInfo }));
    }
    return scriptInfo ? { fileName: textChanges2.fileName, textChanges: textChanges2.textChanges.map((textChange) => convertTextChangeToCodeEdit(textChange, scriptInfo)) } : convertNewFileTextChangeToCodeEdit(textChanges2);
  }
  convertTextChangeToCodeEdit(change, scriptInfo) {
    return {
      start: scriptInfo.positionToLineOffset(change.span.start),
      end: scriptInfo.positionToLineOffset(change.span.start + change.span.length),
      newText: change.newText ? change.newText : ""
    };
  }
  getBraceMatching(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const spans = languageService.getBraceMatchingAtPosition(file, position);
    return !spans ? void 0 : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans;
  }
  getDiagnosticsForProject(next, delay, fileName) {
    if (this.suppressDiagnosticEvents) {
      return;
    }
    const { fileNames, languageServiceDisabled } = this.getProjectInfoWorker(
      fileName,
      /*projectFileName*/
      void 0,
      /*needFileNameList*/
      true,
      /*excludeConfigFiles*/
      true
    );
    if (languageServiceDisabled) {
      return;
    }
    const fileNamesInProject = fileNames.filter((value) => !stringContains(value, "lib.d.ts"));
    if (fileNamesInProject.length === 0) {
      return;
    }
    const highPriorityFiles = [];
    const mediumPriorityFiles = [];
    const lowPriorityFiles = [];
    const veryLowPriorityFiles = [];
    const normalizedFileName = toNormalizedPath(fileName);
    const project = this.projectService.ensureDefaultProjectForFile(normalizedFileName);
    for (const fileNameInProject of fileNamesInProject) {
      if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) {
        highPriorityFiles.push(fileNameInProject);
      } else {
        const info = this.projectService.getScriptInfo(fileNameInProject);
        if (!info.isScriptOpen()) {
          if (isDeclarationFileName(fileNameInProject)) {
            veryLowPriorityFiles.push(fileNameInProject);
          } else {
            lowPriorityFiles.push(fileNameInProject);
          }
        } else {
          mediumPriorityFiles.push(fileNameInProject);
        }
      }
    }
    const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles];
    const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project }));
    this.updateErrorCheck(
      next,
      checkList,
      delay,
      /*requireOpen*/
      false
    );
  }
  configurePlugin(args) {
    this.projectService.configurePlugin(args);
  }
  getSmartSelectionRange(args, simplifiedResult) {
    const { locations } = args;
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file));
    return map(locations, (location) => {
      const pos = this.getPosition(location, scriptInfo);
      const selectionRange = languageService.getSmartSelectionRange(file, pos);
      return simplifiedResult ? this.mapSelectionRange(selectionRange, scriptInfo) : selectionRange;
    });
  }
  toggleLineComment(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfo(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.toggleLineComment(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  toggleMultilineComment(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.toggleMultilineComment(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  commentSelection(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.commentSelection(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  uncommentSelection(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.uncommentSelection(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  mapSelectionRange(selectionRange, scriptInfo) {
    const result = {
      textSpan: toProtocolTextSpan(selectionRange.textSpan, scriptInfo)
    };
    if (selectionRange.parent) {
      result.parent = this.mapSelectionRange(selectionRange.parent, scriptInfo);
    }
    return result;
  }
  getScriptInfoFromProjectService(file) {
    const normalizedFile = toNormalizedPath(file);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(normalizedFile);
    if (!scriptInfo) {
      this.projectService.logErrorForScriptInfoNotFound(normalizedFile);
      return Errors.ThrowNoProject();
    }
    return scriptInfo;
  }
  toProtocolCallHierarchyItem(item) {
    const scriptInfo = this.getScriptInfoFromProjectService(item.file);
    return {
      name: item.name,
      kind: item.kind,
      kindModifiers: item.kindModifiers,
      file: item.file,
      containerName: item.containerName,
      span: toProtocolTextSpan(item.span, scriptInfo),
      selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo)
    };
  }
  toProtocolCallHierarchyIncomingCall(incomingCall) {
    const scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file);
    return {
      from: this.toProtocolCallHierarchyItem(incomingCall.from),
      fromSpans: incomingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo))
    };
  }
  toProtocolCallHierarchyOutgoingCall(outgoingCall, scriptInfo) {
    return {
      to: this.toProtocolCallHierarchyItem(outgoingCall.to),
      fromSpans: outgoingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo))
    };
  }
  prepareCallHierarchy(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    if (scriptInfo) {
      const position = this.getPosition(args, scriptInfo);
      const result = project.getLanguageService().prepareCallHierarchy(file, position);
      return result && mapOneOrMany(result, (item) => this.toProtocolCallHierarchyItem(item));
    }
    return void 0;
  }
  provideCallHierarchyIncomingCalls(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.getScriptInfoFromProjectService(file);
    const incomingCalls = project.getLanguageService().provideCallHierarchyIncomingCalls(file, this.getPosition(args, scriptInfo));
    return incomingCalls.map((call) => this.toProtocolCallHierarchyIncomingCall(call));
  }
  provideCallHierarchyOutgoingCalls(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.getScriptInfoFromProjectService(file);
    const outgoingCalls = project.getLanguageService().provideCallHierarchyOutgoingCalls(file, this.getPosition(args, scriptInfo));
    return outgoingCalls.map((call) => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo));
  }
  getCanonicalFileName(fileName) {
    const name = this.host.useCaseSensitiveFileNames ? fileName : toFileNameLowerCase(fileName);
    return normalizePath(name);
  }
  exit() {
  }
  notRequired() {
    return { responseRequired: false };
  }
  requiredResponse(response) {
    return { response, responseRequired: true };
  }
  addProtocolHandler(command, handler) {
    if (this.handlers.has(command)) {
      throw new Error(`Protocol handler already exists for command "${command}"`);
    }
    this.handlers.set(command, handler);
  }
  setCurrentRequest(requestId) {
    Debug.assert(this.currentRequestId === void 0);
    this.currentRequestId = requestId;
    this.cancellationToken.setRequest(requestId);
  }
  resetCurrentRequest(requestId) {
    Debug.assert(this.currentRequestId === requestId);
    this.currentRequestId = void 0;
    this.cancellationToken.resetRequest(requestId);
  }
  executeWithRequestId(requestId, f) {
    try {
      this.setCurrentRequest(requestId);
      return f();
    } finally {
      this.resetCurrentRequest(requestId);
    }
  }
  executeCommand(request) {
    const handler = this.handlers.get(request.command);
    if (handler) {
      const response = this.executeWithRequestId(request.seq, () => handler(request));
      this.projectService.enableRequestedPlugins();
      return response;
    } else {
      this.logger.msg(`Unrecognized JSON command:${stringifyIndented(request)}`, "Err" /* Err */);
      this.doOutput(
        /*info*/
        void 0,
        "unknown" /* Unknown */,
        request.seq,
        /*success*/
        false,
        `Unrecognized JSON command: ${request.command}`
      );
      return { responseRequired: false };
    }
  }
  onMessage(message) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
    this.gcTimer.scheduleCollect();
    this.performanceData = void 0;
    let start2;
    if (this.logger.hasLevel(2 /* requestTime */)) {
      start2 = this.hrtime();
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`request:${indent2(this.toStringMessage(message))}`);
      }
    }
    let request;
    let relevantFile;
    try {
      request = this.parseMessage(message);
      relevantFile = request.arguments && request.arguments.file ? request.arguments : void 0;
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { seq: request.seq, command: request.command });
      (_b = perfLogger) == null ? void 0 : _b.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100));
      (_c = tracing) == null ? void 0 : _c.push(
        tracing.Phase.Session,
        "executeCommand",
        { seq: request.seq, command: request.command },
        /*separateBeginAndEnd*/
        true
      );
      const { response, responseRequired } = this.executeCommand(request);
      (_d = tracing) == null ? void 0 : _d.pop();
      if (this.logger.hasLevel(2 /* requestTime */)) {
        const elapsedTime = hrTimeToMilliseconds(this.hrtime(start2)).toFixed(4);
        if (responseRequired) {
          this.logger.perftrc(`${request.seq}::${request.command}: elapsed time (in milliseconds) ${elapsedTime}`);
        } else {
          this.logger.perftrc(`${request.seq}::${request.command}: async elapsed time (in milliseconds) ${elapsedTime}`);
        }
      }
      (_e = perfLogger) == null ? void 0 : _e.logStopCommand("" + request.command, "Success");
      (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response });
      if (response) {
        this.doOutput(
          response,
          request.command,
          request.seq,
          /*success*/
          true
        );
      } else if (responseRequired) {
        this.doOutput(
          /*info*/
          void 0,
          request.command,
          request.seq,
          /*success*/
          false,
          "No content available."
        );
      }
    } catch (err) {
      (_g = tracing) == null ? void 0 : _g.popAll();
      if (err instanceof OperationCanceledException) {
        (_h = perfLogger) == null ? void 0 : _h.logStopCommand("" + (request && request.command), "Canceled: " + err);
        (_i = tracing) == null ? void 0 : _i.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command });
        this.doOutput(
          { canceled: true },
          request.command,
          request.seq,
          /*success*/
          true
        );
        return;
      }
      this.logErrorWorker(err, this.toStringMessage(message), relevantFile);
      (_j = perfLogger) == null ? void 0 : _j.logStopCommand("" + (request && request.command), "Error: " + err);
      (_k = tracing) == null ? void 0 : _k.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message });
      this.doOutput(
        /*info*/
        void 0,
        request ? request.command : "unknown" /* Unknown */,
        request ? request.seq : 0,
        /*success*/
        false,
        "Error processing request. " + err.message + "\n" + err.stack
      );
    }
  }
  parseMessage(message) {
    return JSON.parse(message);
  }
  toStringMessage(message) {
    return message;
  }
  getFormatOptions(file) {
    return this.projectService.getFormatCodeOptions(file);
  }
  getPreferences(file) {
    return this.projectService.getPreferences(file);
  }
  getHostFormatOptions() {
    return this.projectService.getHostFormatCodeOptions();
  }
  getHostPreferences() {
    return this.projectService.getHostPreferences();
  }
};
function toProtocolTextSpan(textSpan, scriptInfo) {
  return {
    start: scriptInfo.positionToLineOffset(textSpan.start),
    end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan))
  };
}
function toProtocolTextSpanWithContext(span, contextSpan, scriptInfo) {
  const textSpan = toProtocolTextSpan(span, scriptInfo);
  const contextTextSpan = contextSpan && toProtocolTextSpan(contextSpan, scriptInfo);
  return contextTextSpan ? { ...textSpan, contextStart: contextTextSpan.start, contextEnd: contextTextSpan.end } : textSpan;
}
function convertTextChangeToCodeEdit(change, scriptInfo) {
  return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText };
}
function positionToLineOffset(info, position) {
  return isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position);
}
function convertLinkedEditInfoToRanges(linkedEdit, scriptInfo) {
  const ranges = linkedEdit.ranges.map(
    (r) => {
      return {
        start: scriptInfo.positionToLineOffset(r.start),
        end: scriptInfo.positionToLineOffset(r.start + r.length)
      };
    }
  );
  if (!linkedEdit.wordPattern)
    return { ranges };
  return { ranges, wordPattern: linkedEdit.wordPattern };
}
function locationFromLineAndCharacter(lc) {
  return { line: lc.line + 1, offset: lc.character + 1 };
}
function convertNewFileTextChangeToCodeEdit(textChanges2) {
  Debug.assert(textChanges2.textChanges.length === 1);
  const change = first(textChanges2.textChanges);
  Debug.assert(change.span.start === 0 && change.span.length === 0);
  return { fileName: textChanges2.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] };
}
function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) {
  const newText = applyEdits(oldText, renameFilename, edits);
  const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation);
  return { line: line + 1, offset: character + 1 };
}
function applyEdits(text, textFilename, edits) {
  for (const { fileName, textChanges: textChanges2 } of edits) {
    if (fileName !== textFilename) {
      continue;
    }
    for (let i = textChanges2.length - 1; i >= 0; i--) {
      const { newText, span: { start: start2, length: length2 } } = textChanges2[i];
      text = text.slice(0, start2) + newText + text.slice(start2 + length2);
    }
  }
  return text;
}
function referenceEntryToReferencesResponseItem(projectService, { fileName, textSpan, contextSpan, isWriteAccess: isWriteAccess2, isDefinition }, { disableLineTextInReferences }) {
  const scriptInfo = Debug.checkDefined(projectService.getScriptInfo(fileName));
  const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo);
  const lineText = disableLineTextInReferences ? void 0 : getLineText(scriptInfo, span);
  return {
    file: fileName,
    ...span,
    lineText,
    isWriteAccess: isWriteAccess2,
    isDefinition
  };
}
function getLineText(scriptInfo, span) {
  const lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1);
  return scriptInfo.getSnapshot().getText(lineSpan.start, textSpanEnd(lineSpan)).replace(/\r|\n/g, "");
}
function isCompletionEntryData(data) {
  return data === void 0 || data && typeof data === "object" && typeof data.exportName === "string" && (data.fileName === void 0 || typeof data.fileName === "string") && (data.ambientModuleName === void 0 || typeof data.ambientModuleName === "string" && (data.isPackageJsonImport === void 0 || typeof data.isPackageJsonImport === "boolean"));
}

// src/server/scriptVersionCache.ts
var lineCollectionCapacity = 4;
var CharRangeSection = /* @__PURE__ */ ((CharRangeSection2) => {
  CharRangeSection2[CharRangeSection2["PreStart"] = 0] = "PreStart";
  CharRangeSection2[CharRangeSection2["Start"] = 1] = "Start";
  CharRangeSection2[CharRangeSection2["Entire"] = 2] = "Entire";
  CharRangeSection2[CharRangeSection2["Mid"] = 3] = "Mid";
  CharRangeSection2[CharRangeSection2["End"] = 4] = "End";
  CharRangeSection2[CharRangeSection2["PostEnd"] = 5] = "PostEnd";
  return CharRangeSection2;
})(CharRangeSection || {});
var EditWalker = class {
  constructor() {
    this.goSubtree = true;
    this.lineIndex = new LineIndex();
    this.endBranch = [];
    this.state = 2 /* Entire */;
    this.initialText = "";
    this.trailingText = "";
    this.lineIndex.root = new LineNode();
    this.startPath = [this.lineIndex.root];
    this.stack = [this.lineIndex.root];
  }
  get done() {
    return false;
  }
  insertLines(insertedText, suppressTrailingText) {
    if (suppressTrailingText) {
      this.trailingText = "";
    }
    if (insertedText) {
      insertedText = this.initialText + insertedText + this.trailingText;
    } else {
      insertedText = this.initialText + this.trailingText;
    }
    const lm = LineIndex.linesFromText(insertedText);
    const lines = lm.lines;
    if (lines.length > 1 && lines[lines.length - 1] === "") {
      lines.pop();
    }
    let branchParent;
    let lastZeroCount;
    for (let k = this.endBranch.length - 1; k >= 0; k--) {
      this.endBranch[k].updateCounts();
      if (this.endBranch[k].charCount() === 0) {
        lastZeroCount = this.endBranch[k];
        if (k > 0) {
          branchParent = this.endBranch[k - 1];
        } else {
          branchParent = this.branchNode;
        }
      }
    }
    if (lastZeroCount) {
      branchParent.remove(lastZeroCount);
    }
    const leafNode = this.startPath[this.startPath.length - 1];
    if (lines.length > 0) {
      leafNode.text = lines[0];
      if (lines.length > 1) {
        let insertedNodes = new Array(lines.length - 1);
        let startNode2 = leafNode;
        for (let i = 1; i < lines.length; i++) {
          insertedNodes[i - 1] = new LineLeaf(lines[i]);
        }
        let pathIndex = this.startPath.length - 2;
        while (pathIndex >= 0) {
          const insertionNode = this.startPath[pathIndex];
          insertedNodes = insertionNode.insertAt(startNode2, insertedNodes);
          pathIndex--;
          startNode2 = insertionNode;
        }
        let insertedNodesLen = insertedNodes.length;
        while (insertedNodesLen > 0) {
          const newRoot = new LineNode();
          newRoot.add(this.lineIndex.root);
          insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes);
          insertedNodesLen = insertedNodes.length;
          this.lineIndex.root = newRoot;
        }
        this.lineIndex.root.updateCounts();
      } else {
        for (let j = this.startPath.length - 2; j >= 0; j--) {
          this.startPath[j].updateCounts();
        }
      }
    } else {
      const insertionNode = this.startPath[this.startPath.length - 2];
      insertionNode.remove(leafNode);
      for (let j = this.startPath.length - 2; j >= 0; j--) {
        this.startPath[j].updateCounts();
      }
    }
    return this.lineIndex;
  }
  post(_relativeStart, _relativeLength, lineCollection) {
    if (lineCollection === this.lineCollectionAtBranch) {
      this.state = 4 /* End */;
    }
    this.stack.pop();
  }
  pre(_relativeStart, _relativeLength, lineCollection, _parent, nodeType) {
    const currentNode = this.stack[this.stack.length - 1];
    if (this.state === 2 /* Entire */ && nodeType === 1 /* Start */) {
      this.state = 1 /* Start */;
      this.branchNode = currentNode;
      this.lineCollectionAtBranch = lineCollection;
    }
    let child;
    function fresh(node) {
      if (node.isLeaf()) {
        return new LineLeaf("");
      } else
        return new LineNode();
    }
    switch (nodeType) {
      case 0 /* PreStart */:
        this.goSubtree = false;
        if (this.state !== 4 /* End */) {
          currentNode.add(lineCollection);
        }
        break;
      case 1 /* Start */:
        if (this.state === 4 /* End */) {
          this.goSubtree = false;
        } else {
          child = fresh(lineCollection);
          currentNode.add(child);
          this.startPath.push(child);
        }
        break;
      case 2 /* Entire */:
        if (this.state !== 4 /* End */) {
          child = fresh(lineCollection);
          currentNode.add(child);
          this.startPath.push(child);
        } else {
          if (!lineCollection.isLeaf()) {
            child = fresh(lineCollection);
            currentNode.add(child);
            this.endBranch.push(child);
          }
        }
        break;
      case 3 /* Mid */:
        this.goSubtree = false;
        break;
      case 4 /* End */:
        if (this.state !== 4 /* End */) {
          this.goSubtree = false;
        } else {
          if (!lineCollection.isLeaf()) {
            child = fresh(lineCollection);
            currentNode.add(child);
            this.endBranch.push(child);
          }
        }
        break;
      case 5 /* PostEnd */:
        this.goSubtree = false;
        if (this.state !== 1 /* Start */) {
          currentNode.add(lineCollection);
        }
        break;
    }
    if (this.goSubtree) {
      this.stack.push(child);
    }
  }
  // just gather text from the leaves
  leaf(relativeStart, relativeLength, ll) {
    if (this.state === 1 /* Start */) {
      this.initialText = ll.text.substring(0, relativeStart);
    } else if (this.state === 2 /* Entire */) {
      this.initialText = ll.text.substring(0, relativeStart);
      this.trailingText = ll.text.substring(relativeStart + relativeLength);
    } else {
      this.trailingText = ll.text.substring(relativeStart + relativeLength);
    }
  }
};
var TextChange9 = class {
  constructor(pos, deleteLen, insertedText) {
    this.pos = pos;
    this.deleteLen = deleteLen;
    this.insertedText = insertedText;
  }
  getTextChangeRange() {
    return createTextChangeRange(
      createTextSpan(this.pos, this.deleteLen),
      this.insertedText ? this.insertedText.length : 0
    );
  }
};
var _ScriptVersionCache = class {
  constructor() {
    this.changes = [];
    this.versions = new Array(_ScriptVersionCache.maxVersions);
    this.minVersion = 0;
    // no versions earlier than min version will maintain change history
    this.currentVersion = 0;
  }
  versionToIndex(version2) {
    if (version2 < this.minVersion || version2 > this.currentVersion) {
      return void 0;
    }
    return version2 % _ScriptVersionCache.maxVersions;
  }
  currentVersionToIndex() {
    return this.currentVersion % _ScriptVersionCache.maxVersions;
  }
  // REVIEW: can optimize by coalescing simple edits
  edit(pos, deleteLen, insertedText) {
    this.changes.push(new TextChange9(pos, deleteLen, insertedText));
    if (this.changes.length > _ScriptVersionCache.changeNumberThreshold || deleteLen > _ScriptVersionCache.changeLengthThreshold || insertedText && insertedText.length > _ScriptVersionCache.changeLengthThreshold) {
      this.getSnapshot();
    }
  }
  getSnapshot() {
    return this._getSnapshot();
  }
  _getSnapshot() {
    let snap = this.versions[this.currentVersionToIndex()];
    if (this.changes.length > 0) {
      let snapIndex = snap.index;
      for (const change of this.changes) {
        snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText);
      }
      snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes);
      this.currentVersion = snap.version;
      this.versions[this.currentVersionToIndex()] = snap;
      this.changes = [];
      if (this.currentVersion - this.minVersion >= _ScriptVersionCache.maxVersions) {
        this.minVersion = this.currentVersion - _ScriptVersionCache.maxVersions + 1;
      }
    }
    return snap;
  }
  getSnapshotVersion() {
    return this._getSnapshot().version;
  }
  getAbsolutePositionAndLineText(oneBasedLine) {
    return this._getSnapshot().index.lineNumberToInfo(oneBasedLine);
  }
  lineOffsetToPosition(line, column) {
    return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1);
  }
  positionToLineOffset(position) {
    return this._getSnapshot().index.positionToLineOffset(position);
  }
  lineToTextSpan(line) {
    const index = this._getSnapshot().index;
    const { lineText, absolutePosition } = index.lineNumberToInfo(line + 1);
    const len = lineText !== void 0 ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition;
    return createTextSpan(absolutePosition, len);
  }
  getTextChangesBetweenVersions(oldVersion, newVersion) {
    if (oldVersion < newVersion) {
      if (oldVersion >= this.minVersion) {
        const textChangeRanges = [];
        for (let i = oldVersion + 1; i <= newVersion; i++) {
          const snap = this.versions[this.versionToIndex(i)];
          for (const textChange of snap.changesSincePreviousVersion) {
            textChangeRanges.push(textChange.getTextChangeRange());
          }
        }
        return collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges);
      } else {
        return void 0;
      }
    } else {
      return unchangedTextChangeRange;
    }
  }
  getLineCount() {
    return this._getSnapshot().index.getLineCount();
  }
  static fromString(script) {
    const svc = new _ScriptVersionCache();
    const snap = new LineIndexSnapshot(0, svc, new LineIndex());
    svc.versions[svc.currentVersion] = snap;
    const lm = LineIndex.linesFromText(script);
    snap.index.load(lm.lines);
    return svc;
  }
};
var ScriptVersionCache = _ScriptVersionCache;
ScriptVersionCache.changeNumberThreshold = 8;
ScriptVersionCache.changeLengthThreshold = 256;
ScriptVersionCache.maxVersions = 8;
var LineIndexSnapshot = class {
  constructor(version2, cache, index, changesSincePreviousVersion = emptyArray2) {
    this.version = version2;
    this.cache = cache;
    this.index = index;
    this.changesSincePreviousVersion = changesSincePreviousVersion;
  }
  getText(rangeStart, rangeEnd) {
    return this.index.getText(rangeStart, rangeEnd - rangeStart);
  }
  getLength() {
    return this.index.getLength();
  }
  getChangeRange(oldSnapshot) {
    if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) {
      if (this.version <= oldSnapshot.version) {
        return unchangedTextChangeRange;
      } else {
        return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version);
      }
    }
  }
};
var LineIndex = class {
  constructor() {
    // set this to true to check each edit for accuracy
    this.checkEdits = false;
  }
  absolutePositionOfStartOfLine(oneBasedLine) {
    return this.lineNumberToInfo(oneBasedLine).absolutePosition;
  }
  positionToLineOffset(position) {
    const { oneBasedLine, zeroBasedColumn } = this.root.charOffsetToLineInfo(1, position);
    return { line: oneBasedLine, offset: zeroBasedColumn + 1 };
  }
  positionToColumnAndLineText(position) {
    return this.root.charOffsetToLineInfo(1, position);
  }
  getLineCount() {
    return this.root.lineCount();
  }
  lineNumberToInfo(oneBasedLine) {
    const lineCount = this.getLineCount();
    if (oneBasedLine <= lineCount) {
      const { position, leaf } = this.root.lineNumberToInfo(oneBasedLine, 0);
      return { absolutePosition: position, lineText: leaf && leaf.text };
    } else {
      return { absolutePosition: this.root.charCount(), lineText: void 0 };
    }
  }
  load(lines) {
    if (lines.length > 0) {
      const leaves = [];
      for (let i = 0; i < lines.length; i++) {
        leaves[i] = new LineLeaf(lines[i]);
      }
      this.root = LineIndex.buildTreeFromBottom(leaves);
    } else {
      this.root = new LineNode();
    }
  }
  walk(rangeStart, rangeLength, walkFns) {
    this.root.walk(rangeStart, rangeLength, walkFns);
  }
  getText(rangeStart, rangeLength) {
    let accum = "";
    if (rangeLength > 0 && rangeStart < this.root.charCount()) {
      this.walk(rangeStart, rangeLength, {
        goSubtree: true,
        done: false,
        leaf: (relativeStart, relativeLength, ll) => {
          accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength));
        }
      });
    }
    return accum;
  }
  getLength() {
    return this.root.charCount();
  }
  every(f, rangeStart, rangeEnd) {
    if (!rangeEnd) {
      rangeEnd = this.root.charCount();
    }
    const walkFns = {
      goSubtree: true,
      done: false,
      leaf(relativeStart, relativeLength, ll) {
        if (!f(ll, relativeStart, relativeLength)) {
          this.done = true;
        }
      }
    };
    this.walk(rangeStart, rangeEnd - rangeStart, walkFns);
    return !walkFns.done;
  }
  edit(pos, deleteLength, newText) {
    if (this.root.charCount() === 0) {
      Debug.assert(deleteLength === 0);
      if (newText !== void 0) {
        this.load(LineIndex.linesFromText(newText).lines);
        return this;
      }
      return void 0;
    } else {
      let checkText;
      if (this.checkEdits) {
        const source = this.getText(0, this.root.charCount());
        checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength);
      }
      const walker = new EditWalker();
      let suppressTrailingText = false;
      if (pos >= this.root.charCount()) {
        pos = this.root.charCount() - 1;
        const endString = this.getText(pos, 1);
        if (newText) {
          newText = endString + newText;
        } else {
          newText = endString;
        }
        deleteLength = 0;
        suppressTrailingText = true;
      } else if (deleteLength > 0) {
        const e = pos + deleteLength;
        const { zeroBasedColumn, lineText } = this.positionToColumnAndLineText(e);
        if (zeroBasedColumn === 0) {
          deleteLength += lineText.length;
          newText = newText ? newText + lineText : lineText;
        }
      }
      this.root.walk(pos, deleteLength, walker);
      walker.insertLines(newText, suppressTrailingText);
      if (this.checkEdits) {
        const updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength());
        Debug.assert(checkText === updatedText, "buffer edit mismatch");
      }
      return walker.lineIndex;
    }
  }
  static buildTreeFromBottom(nodes) {
    if (nodes.length < lineCollectionCapacity) {
      return new LineNode(nodes);
    }
    const interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity));
    let nodeIndex = 0;
    for (let i = 0; i < interiorNodes.length; i++) {
      const end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length);
      interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end));
      nodeIndex = end;
    }
    return this.buildTreeFromBottom(interiorNodes);
  }
  static linesFromText(text) {
    const lineMap = computeLineStarts(text);
    if (lineMap.length === 0) {
      return { lines: [], lineMap };
    }
    const lines = new Array(lineMap.length);
    const lc = lineMap.length - 1;
    for (let lmi = 0; lmi < lc; lmi++) {
      lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]);
    }
    const endText = text.substring(lineMap[lc]);
    if (endText.length > 0) {
      lines[lc] = endText;
    } else {
      lines.pop();
    }
    return { lines, lineMap };
  }
};
var LineNode = class {
  constructor(children = []) {
    this.children = children;
    this.totalChars = 0;
    this.totalLines = 0;
    if (children.length)
      this.updateCounts();
  }
  isLeaf() {
    return false;
  }
  updateCounts() {
    this.totalChars = 0;
    this.totalLines = 0;
    for (const child of this.children) {
      this.totalChars += child.charCount();
      this.totalLines += child.lineCount();
    }
  }
  execWalk(rangeStart, rangeLength, walkFns, childIndex, nodeType) {
    if (walkFns.pre) {
      walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
    }
    if (walkFns.goSubtree) {
      this.children[childIndex].walk(rangeStart, rangeLength, walkFns);
      if (walkFns.post) {
        walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
      }
    } else {
      walkFns.goSubtree = true;
    }
    return walkFns.done;
  }
  skipChild(relativeStart, relativeLength, childIndex, walkFns, nodeType) {
    if (walkFns.pre && !walkFns.done) {
      walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType);
      walkFns.goSubtree = true;
    }
  }
  walk(rangeStart, rangeLength, walkFns) {
    let childIndex = 0;
    let childCharCount = this.children[childIndex].charCount();
    let adjustedStart = rangeStart;
    while (adjustedStart >= childCharCount) {
      this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */);
      adjustedStart -= childCharCount;
      childIndex++;
      childCharCount = this.children[childIndex].charCount();
    }
    if (adjustedStart + rangeLength <= childCharCount) {
      if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) {
        return;
      }
    } else {
      if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) {
        return;
      }
      let adjustedLength = rangeLength - (childCharCount - adjustedStart);
      childIndex++;
      const child = this.children[childIndex];
      childCharCount = child.charCount();
      while (adjustedLength > childCharCount) {
        if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) {
          return;
        }
        adjustedLength -= childCharCount;
        childIndex++;
        childCharCount = this.children[childIndex].charCount();
      }
      if (adjustedLength > 0) {
        if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) {
          return;
        }
      }
    }
    if (walkFns.pre) {
      const clen = this.children.length;
      if (childIndex < clen - 1) {
        for (let ej = childIndex + 1; ej < clen; ej++) {
          this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */);
        }
      }
    }
  }
  // Input position is relative to the start of this node.
  // Output line number is absolute.
  charOffsetToLineInfo(lineNumberAccumulator, relativePosition) {
    if (this.children.length === 0) {
      return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: void 0 };
    }
    for (const child of this.children) {
      if (child.charCount() > relativePosition) {
        if (child.isLeaf()) {
          return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text };
        } else {
          return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition);
        }
      } else {
        relativePosition -= child.charCount();
        lineNumberAccumulator += child.lineCount();
      }
    }
    const lineCount = this.lineCount();
    if (lineCount === 0) {
      return { oneBasedLine: 1, zeroBasedColumn: 0, lineText: void 0 };
    }
    const leaf = Debug.checkDefined(this.lineNumberToInfo(lineCount, 0).leaf);
    return { oneBasedLine: lineCount, zeroBasedColumn: leaf.charCount(), lineText: void 0 };
  }
  /**
   * Input line number is relative to the start of this node.
   * Output line number is relative to the child.
   * positionAccumulator will be an absolute position once relativeLineNumber reaches 0.
   */
  lineNumberToInfo(relativeOneBasedLine, positionAccumulator) {
    for (const child of this.children) {
      const childLineCount = child.lineCount();
      if (childLineCount >= relativeOneBasedLine) {
        return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator);
      } else {
        relativeOneBasedLine -= childLineCount;
        positionAccumulator += child.charCount();
      }
    }
    return { position: positionAccumulator, leaf: void 0 };
  }
  splitAfter(childIndex) {
    let splitNode;
    const clen = this.children.length;
    childIndex++;
    const endLength = childIndex;
    if (childIndex < clen) {
      splitNode = new LineNode();
      while (childIndex < clen) {
        splitNode.add(this.children[childIndex]);
        childIndex++;
      }
      splitNode.updateCounts();
    }
    this.children.length = endLength;
    return splitNode;
  }
  remove(child) {
    const childIndex = this.findChildIndex(child);
    const clen = this.children.length;
    if (childIndex < clen - 1) {
      for (let i = childIndex; i < clen - 1; i++) {
        this.children[i] = this.children[i + 1];
      }
    }
    this.children.pop();
  }
  findChildIndex(child) {
    const childIndex = this.children.indexOf(child);
    Debug.assert(childIndex !== -1);
    return childIndex;
  }
  insertAt(child, nodes) {
    let childIndex = this.findChildIndex(child);
    const clen = this.children.length;
    const nodeCount = nodes.length;
    if (clen < lineCollectionCapacity && childIndex === clen - 1 && nodeCount === 1) {
      this.add(nodes[0]);
      this.updateCounts();
      return [];
    } else {
      const shiftNode = this.splitAfter(childIndex);
      let nodeIndex = 0;
      childIndex++;
      while (childIndex < lineCollectionCapacity && nodeIndex < nodeCount) {
        this.children[childIndex] = nodes[nodeIndex];
        childIndex++;
        nodeIndex++;
      }
      let splitNodes = [];
      let splitNodeCount = 0;
      if (nodeIndex < nodeCount) {
        splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity);
        splitNodes = new Array(splitNodeCount);
        let splitNodeIndex = 0;
        for (let i = 0; i < splitNodeCount; i++) {
          splitNodes[i] = new LineNode();
        }
        let splitNode = splitNodes[0];
        while (nodeIndex < nodeCount) {
          splitNode.add(nodes[nodeIndex]);
          nodeIndex++;
          if (splitNode.children.length === lineCollectionCapacity) {
            splitNodeIndex++;
            splitNode = splitNodes[splitNodeIndex];
          }
        }
        for (let i = splitNodes.length - 1; i >= 0; i--) {
          if (splitNodes[i].children.length === 0) {
            splitNodes.pop();
          }
        }
      }
      if (shiftNode) {
        splitNodes.push(shiftNode);
      }
      this.updateCounts();
      for (let i = 0; i < splitNodeCount; i++) {
        splitNodes[i].updateCounts();
      }
      return splitNodes;
    }
  }
  // assume there is room for the item; return true if more room
  add(collection) {
    this.children.push(collection);
    Debug.assert(this.children.length <= lineCollectionCapacity);
  }
  charCount() {
    return this.totalChars;
  }
  lineCount() {
    return this.totalLines;
  }
};
var LineLeaf = class {
  constructor(text) {
    this.text = text;
  }
  isLeaf() {
    return true;
  }
  walk(rangeStart, rangeLength, walkFns) {
    walkFns.leaf(rangeStart, rangeLength, this);
  }
  charCount() {
    return this.text.length;
  }
  lineCount() {
    return 1;
  }
};

// src/tsserver/_namespaces/ts.server.ts
var ts_server_exports4 = {};
__export(ts_server_exports4, {
  ActionInvalidate: () => ActionInvalidate,
  ActionPackageInstalled: () => ActionPackageInstalled,
  ActionSet: () => ActionSet,
  ActionWatchTypingLocations: () => ActionWatchTypingLocations,
  Arguments: () => Arguments,
  AutoImportProviderProject: () => AutoImportProviderProject,
  CharRangeSection: () => CharRangeSection,
  CommandNames: () => CommandNames,
  ConfigFileDiagEvent: () => ConfigFileDiagEvent,
  ConfiguredProject: () => ConfiguredProject2,
  Errors: () => Errors,
  EventBeginInstallTypes: () => EventBeginInstallTypes,
  EventEndInstallTypes: () => EventEndInstallTypes,
  EventInitializationFailed: () => EventInitializationFailed,
  EventTypesRegistry: () => EventTypesRegistry,
  ExternalProject: () => ExternalProject2,
  GcTimer: () => GcTimer,
  InferredProject: () => InferredProject2,
  LargeFileReferencedEvent: () => LargeFileReferencedEvent,
  LineIndex: () => LineIndex,
  LineLeaf: () => LineLeaf,
  LineNode: () => LineNode,
  LogLevel: () => LogLevel2,
  Msg: () => Msg,
  OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent,
  Project: () => Project3,
  ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent,
  ProjectKind: () => ProjectKind,
  ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent,
  ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent,
  ProjectLoadingStartEvent: () => ProjectLoadingStartEvent,
  ProjectReferenceProjectLoadKind: () => ProjectReferenceProjectLoadKind,
  ProjectService: () => ProjectService3,
  ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent,
  ScriptInfo: () => ScriptInfo,
  ScriptVersionCache: () => ScriptVersionCache,
  Session: () => Session3,
  TextStorage: () => TextStorage,
  ThrottledOperations: () => ThrottledOperations,
  TypingsCache: () => TypingsCache,
  allFilesAreJsOrDts: () => allFilesAreJsOrDts,
  allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts,
  asNormalizedPath: () => asNormalizedPath,
  convertCompilerOptions: () => convertCompilerOptions,
  convertFormatOptions: () => convertFormatOptions,
  convertScriptKindName: () => convertScriptKindName,
  convertTypeAcquisition: () => convertTypeAcquisition,
  convertUserPreferences: () => convertUserPreferences,
  convertWatchOptions: () => convertWatchOptions,
  countEachFileTypes: () => countEachFileTypes,
  createInstallTypingsRequest: () => createInstallTypingsRequest,
  createModuleSpecifierCache: () => createModuleSpecifierCache,
  createNormalizedPathMap: () => createNormalizedPathMap,
  createPackageJsonCache: () => createPackageJsonCache,
  createSortedArray: () => createSortedArray2,
  emptyArray: () => emptyArray2,
  findArgument: () => findArgument,
  forEachResolvedProjectReferenceProject: () => forEachResolvedProjectReferenceProject,
  formatDiagnosticToProtocol: () => formatDiagnosticToProtocol,
  formatMessage: () => formatMessage2,
  getBaseConfigFileName: () => getBaseConfigFileName,
  getLocationInNewDocument: () => getLocationInNewDocument,
  getLogLevel: () => getLogLevel,
  hasArgument: () => hasArgument,
  hasNoTypeScriptSource: () => hasNoTypeScriptSource,
  indent: () => indent2,
  initializeNodeSystem: () => initializeNodeSystem,
  isConfigFile: () => isConfigFile,
  isConfiguredProject: () => isConfiguredProject,
  isDynamicFileName: () => isDynamicFileName,
  isExternalProject: () => isExternalProject,
  isInferredProject: () => isInferredProject,
  isInferredProjectName: () => isInferredProjectName,
  makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName,
  makeAuxiliaryProjectName: () => makeAuxiliaryProjectName,
  makeInferredProjectName: () => makeInferredProjectName,
  maxFileSize: () => maxFileSize,
  maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles,
  normalizedPathToPath: () => normalizedPathToPath,
  nowString: () => nowString,
  nullCancellationToken: () => nullCancellationToken,
  nullTypingsInstaller: () => nullTypingsInstaller,
  projectContainsInfoDirectly: () => projectContainsInfoDirectly,
  protocol: () => ts_server_protocol_exports,
  removeSorted: () => removeSorted,
  stringifyIndented: () => stringifyIndented,
  toEvent: () => toEvent,
  toNormalizedPath: () => toNormalizedPath,
  tryConvertScriptKindName: () => tryConvertScriptKindName,
  typingsInstaller: () => ts_server_typingsInstaller_exports,
  updateProjectIfDirty: () => updateProjectIfDirty
});

// src/tsserver/nodeServer.ts
function parseLoggingEnvironmentString(logEnvStr) {
  if (!logEnvStr) {
    return {};
  }
  const logEnv = { logToFile: true };
  const args = logEnvStr.split(" ");
  const len = args.length - 1;
  for (let i = 0; i < len; i += 2) {
    const option = args[i];
    const { value, extraPartCounter } = getEntireValue(i + 1);
    i += extraPartCounter;
    if (option && value) {
      switch (option) {
        case "-file":
          logEnv.file = value;
          break;
        case "-level":
          const level = getLogLevel(value);
          logEnv.detailLevel = level !== void 0 ? level : 1 /* normal */;
          break;
        case "-traceToConsole":
          logEnv.traceToConsole = value.toLowerCase() === "true";
          break;
        case "-logToFile":
          logEnv.logToFile = value.toLowerCase() === "true";
          break;
      }
    }
  }
  return logEnv;
  function getEntireValue(initialIndex) {
    let pathStart = args[initialIndex];
    let extraPartCounter = 0;
    if (pathStart.charCodeAt(0) === 34 /* doubleQuote */ && pathStart.charCodeAt(pathStart.length - 1) !== 34 /* doubleQuote */) {
      for (let i = initialIndex + 1; i < args.length; i++) {
        pathStart += " ";
        pathStart += args[i];
        extraPartCounter++;
        if (pathStart.charCodeAt(pathStart.length - 1) === 34 /* doubleQuote */)
          break;
      }
    }
    return { value: stripQuotes(pathStart), extraPartCounter };
  }
}
function parseServerMode() {
  const mode = findArgument("--serverMode");
  if (!mode)
    return void 0;
  switch (mode.toLowerCase()) {
    case "semantic":
      return 0 /* Semantic */;
    case "partialsemantic":
      return 1 /* PartialSemantic */;
    case "syntactic":
      return 2 /* Syntactic */;
    default:
      return mode;
  }
}
function initializeNodeSystem() {
  const sys2 = Debug.checkDefined(sys);
  const childProcess = require("child_process");
  const fs = require("fs");
  class Logger6 {
    constructor(logFilename, traceToConsole, level) {
      this.logFilename = logFilename;
      this.traceToConsole = traceToConsole;
      this.level = level;
      this.seq = 0;
      this.inGroup = false;
      this.firstInGroup = true;
      this.fd = -1;
      if (this.logFilename) {
        try {
          this.fd = fs.openSync(this.logFilename, "w");
        } catch (_) {
        }
      }
    }
    static padStringRight(str, padding) {
      return (str + padding).slice(0, padding.length);
    }
    close() {
      if (this.fd >= 0) {
        fs.close(this.fd, noop);
      }
    }
    getLogFileName() {
      return this.logFilename;
    }
    perftrc(s) {
      this.msg(s, "Perf" /* Perf */);
    }
    info(s) {
      this.msg(s, "Info" /* Info */);
    }
    err(s) {
      this.msg(s, "Err" /* Err */);
    }
    startGroup() {
      this.inGroup = true;
      this.firstInGroup = true;
    }
    endGroup() {
      this.inGroup = false;
    }
    loggingEnabled() {
      return !!this.logFilename || this.traceToConsole;
    }
    hasLevel(level) {
      return this.loggingEnabled() && this.level >= level;
    }
    msg(s, type = "Err" /* Err */) {
      var _a, _b, _c;
      switch (type) {
        case "Info" /* Info */:
          (_a = perfLogger) == null ? void 0 : _a.logInfoEvent(s);
          break;
        case "Perf" /* Perf */:
          (_b = perfLogger) == null ? void 0 : _b.logPerfEvent(s);
          break;
        default:
          (_c = perfLogger) == null ? void 0 : _c.logErrEvent(s);
          break;
      }
      if (!this.canWrite())
        return;
      s = `[${nowString()}] ${s}
`;
      if (!this.inGroup || this.firstInGroup) {
        const prefix = Logger6.padStringRight(type + " " + this.seq.toString(), "          ");
        s = prefix + s;
      }
      this.write(s, type);
      if (!this.inGroup) {
        this.seq++;
      }
    }
    canWrite() {
      return this.fd >= 0 || this.traceToConsole;
    }
    write(s, _type) {
      if (this.fd >= 0) {
        const buf = sys2.bufferFrom(s);
        fs.writeSync(
          this.fd,
          buf,
          0,
          buf.length,
          /*position*/
          null
        );
      }
      if (this.traceToConsole) {
        console.warn(s);
      }
    }
  }
  const libDirectory = getDirectoryPath(normalizePath(sys2.getExecutingFilePath()));
  const useWatchGuard = process.platform === "win32";
  const originalWatchDirectory = sys2.watchDirectory.bind(sys2);
  const logger = createLogger();
  Debug.loggingHost = {
    log(level, s) {
      switch (level) {
        case 1 /* Error */:
        case 2 /* Warning */:
          return logger.msg(s, "Err" /* Err */);
        case 3 /* Info */:
        case 4 /* Verbose */:
          return logger.msg(s, "Info" /* Info */);
      }
    }
  };
  const pending = createQueue();
  let canWrite = true;
  if (useWatchGuard) {
    const currentDrive = extractWatchDirectoryCacheKey(
      sys2.resolvePath(sys2.getCurrentDirectory()),
      /*currentDriveKey*/
      void 0
    );
    const statusCache = /* @__PURE__ */ new Map();
    sys2.watchDirectory = (path, callback, recursive, options) => {
      const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive);
      let status = cacheKey && statusCache.get(cacheKey);
      if (status === void 0) {
        if (logger.hasLevel(3 /* verbose */)) {
          logger.info(`${cacheKey} for path ${path} not found in cache...`);
        }
        try {
          const args = [combinePaths(libDirectory, "watchGuard.js"), path];
          if (logger.hasLevel(3 /* verbose */)) {
            logger.info(`Starting ${process.execPath} with args:${stringifyIndented(args)}`);
          }
          childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
          status = true;
          if (logger.hasLevel(3 /* verbose */)) {
            logger.info(`WatchGuard for path ${path} returned: OK`);
          }
        } catch (e) {
          status = false;
          if (logger.hasLevel(3 /* verbose */)) {
            logger.info(`WatchGuard for path ${path} returned: ${e.message}`);
          }
        }
        if (cacheKey) {
          statusCache.set(cacheKey, status);
        }
      } else if (logger.hasLevel(3 /* verbose */)) {
        logger.info(`watchDirectory for ${path} uses cached drive information.`);
      }
      if (status) {
        return watchDirectorySwallowingException(path, callback, recursive, options);
      } else {
        return noopFileWatcher;
      }
    };
  } else {
    sys2.watchDirectory = watchDirectorySwallowingException;
  }
  sys2.write = (s) => writeMessage(sys2.bufferFrom(s, "utf8"));
  sys2.setTimeout = setTimeout;
  sys2.clearTimeout = clearTimeout;
  sys2.setImmediate = setImmediate;
  sys2.clearImmediate = clearImmediate;
  if (typeof global !== "undefined" && global.gc) {
    sys2.gc = () => {
      var _a;
      return (_a = global.gc) == null ? void 0 : _a.call(global);
    };
  }
  let cancellationToken;
  try {
    const factory2 = require("./cancellationToken");
    cancellationToken = factory2(sys2.args);
  } catch (e) {
    cancellationToken = nullCancellationToken;
  }
  const localeStr = findArgument("--locale");
  if (localeStr) {
    validateLocaleAndSetLanguage(localeStr, sys2);
  }
  const modeOrUnknown = parseServerMode();
  let serverMode;
  let unknownServerMode;
  if (modeOrUnknown !== void 0) {
    if (typeof modeOrUnknown === "number")
      serverMode = modeOrUnknown;
    else
      unknownServerMode = modeOrUnknown;
  }
  return {
    args: process.argv,
    logger,
    cancellationToken,
    serverMode,
    unknownServerMode,
    startSession: startNodeSession
  };
  function createLogger() {
    const cmdLineLogFileName = findArgument("--logFile");
    const cmdLineVerbosity = getLogLevel(findArgument("--logVerbosity"));
    const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG);
    const unsubstitutedLogFileName = cmdLineLogFileName ? stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || libDirectory + "/.log" + process.pid.toString() : void 0;
    const substitutedLogFileName = unsubstitutedLogFileName ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) : void 0;
    const logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel;
    return new Logger6(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity);
  }
  function writeMessage(buf) {
    if (!canWrite) {
      pending.enqueue(buf);
    } else {
      canWrite = false;
      process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary);
    }
  }
  function setCanWriteFlagAndWriteMessageIfNecessary() {
    canWrite = true;
    if (!pending.isEmpty()) {
      writeMessage(pending.dequeue());
    }
  }
  function extractWatchDirectoryCacheKey(path, currentDriveKey) {
    path = normalizeSlashes(path);
    if (isUNCPath(path)) {
      const firstSlash = path.indexOf(directorySeparator, 2);
      return firstSlash !== -1 ? toFileNameLowerCase(path.substring(0, firstSlash)) : path;
    }
    const rootLength = getRootLength(path);
    if (rootLength === 0) {
      return currentDriveKey;
    }
    if (path.charCodeAt(1) === 58 /* colon */ && path.charCodeAt(2) === 47 /* slash */) {
      return toFileNameLowerCase(path.charAt(0));
    }
    if (path.charCodeAt(0) === 47 /* slash */ && path.charCodeAt(1) !== 47 /* slash */) {
      return currentDriveKey;
    }
    return void 0;
  }
  function isUNCPath(s) {
    return s.length > 2 && s.charCodeAt(0) === 47 /* slash */ && s.charCodeAt(1) === 47 /* slash */;
  }
  function watchDirectorySwallowingException(path, callback, recursive, options) {
    try {
      return originalWatchDirectory(path, callback, recursive, options);
    } catch (e) {
      logger.info(`Exception when creating directory watcher: ${e.message}`);
      return noopFileWatcher;
    }
  }
}
function parseEventPort(eventPortStr) {
  const eventPort = eventPortStr === void 0 ? void 0 : parseInt(eventPortStr);
  return eventPort !== void 0 && !isNaN(eventPort) ? eventPort : void 0;
}
function startNodeSession(options, logger, cancellationToken) {
  const childProcess = require("child_process");
  const os = require("os");
  const net = require("net");
  const readline = require("readline");
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
  });
  const _NodeTypingsInstaller = class {
    constructor(telemetryEnabled2, logger2, host, globalTypingsCacheLocation, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, event) {
      this.telemetryEnabled = telemetryEnabled2;
      this.logger = logger2;
      this.host = host;
      this.globalTypingsCacheLocation = globalTypingsCacheLocation;
      this.typingSafeListLocation = typingSafeListLocation2;
      this.typesMapLocation = typesMapLocation2;
      this.npmLocation = npmLocation2;
      this.validateDefaultNpmLocation = validateDefaultNpmLocation2;
      this.event = event;
      this.activeRequestCount = 0;
      this.requestQueue = createQueue();
      this.requestMap = /* @__PURE__ */ new Map();
      // Maps operation ID to newest requestQueue entry with that ID
      /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */
      this.requestedRegistry = false;
    }
    isKnownTypesPackageName(name) {
      const validationResult = ts_JsTyping_exports.validatePackageName(name);
      if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) {
        return false;
      }
      if (this.requestedRegistry) {
        return !!this.typesRegistryCache && this.typesRegistryCache.has(name);
      }
      this.requestedRegistry = true;
      this.send({ kind: "typesRegistry" });
      return false;
    }
    installPackage(options2) {
      this.send({ kind: "installPackage", ...options2 });
      Debug.assert(this.packageInstalledPromise === void 0);
      return new Promise((resolve, reject) => {
        this.packageInstalledPromise = { resolve, reject };
      });
    }
    attach(projectService) {
      this.projectService = projectService;
      if (this.logger.hasLevel(2 /* requestTime */)) {
        this.logger.info("Binding...");
      }
      const args = [Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation];
      if (this.telemetryEnabled) {
        args.push(Arguments.EnableTelemetry);
      }
      if (this.logger.loggingEnabled() && this.logger.getLogFileName()) {
        args.push(Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName())), `ti-${process.pid}.log`));
      }
      if (this.typingSafeListLocation) {
        args.push(Arguments.TypingSafeListLocation, this.typingSafeListLocation);
      }
      if (this.typesMapLocation) {
        args.push(Arguments.TypesMapLocation, this.typesMapLocation);
      }
      if (this.npmLocation) {
        args.push(Arguments.NpmLocation, this.npmLocation);
      }
      if (this.validateDefaultNpmLocation) {
        args.push(Arguments.ValidateDefaultNpmLocation);
      }
      const execArgv = [];
      for (const arg of process.execArgv) {
        const match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg);
        if (match) {
          const currentPort = match[2] !== void 0 ? +match[2] : match[1].charAt(0) === "d" ? 5858 : 9229;
          execArgv.push(`--${match[1]}=${currentPort + 1}`);
          break;
        }
      }
      const typingsInstaller = combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typingsInstaller.js");
      this.installer = childProcess.fork(typingsInstaller, args, { execArgv });
      this.installer.on("message", (m) => this.handleMessage(m));
      this.host.setImmediate(() => this.event({ pid: this.installer.pid }, "typingsInstallerPid"));
      process.on("exit", () => {
        this.installer.kill();
      });
    }
    onProjectClosed(p) {
      this.send({ projectName: p.getProjectName(), kind: "closeProject" });
    }
    send(rq) {
      this.installer.send(rq);
    }
    enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports) {
      const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
      if (this.logger.hasLevel(3 /* verbose */)) {
        if (this.logger.hasLevel(3 /* verbose */)) {
          this.logger.info(`Scheduling throttled operation:${stringifyIndented(request)}`);
        }
      }
      const operationId = project.getProjectName();
      const operation = () => {
        if (this.logger.hasLevel(3 /* verbose */)) {
          this.logger.info(`Sending request:${stringifyIndented(request)}`);
        }
        this.send(request);
      };
      const queuedRequest = { operationId, operation };
      if (this.activeRequestCount < _NodeTypingsInstaller.maxActiveRequestCount) {
        this.scheduleRequest(queuedRequest);
      } else {
        if (this.logger.hasLevel(3 /* verbose */)) {
          this.logger.info(`Deferring request for: ${operationId}`);
        }
        this.requestQueue.enqueue(queuedRequest);
        this.requestMap.set(operationId, queuedRequest);
      }
    }
    handleMessage(response) {
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`Received response:${stringifyIndented(response)}`);
      }
      switch (response.kind) {
        case EventTypesRegistry:
          this.typesRegistryCache = new Map(Object.entries(response.typesRegistry));
          break;
        case ActionPackageInstalled: {
          const { success, message } = response;
          if (success) {
            this.packageInstalledPromise.resolve({ successMessage: message });
          } else {
            this.packageInstalledPromise.reject(message);
          }
          this.packageInstalledPromise = void 0;
          this.projectService.updateTypingsForProject(response);
          this.event(response, "setTypings");
          break;
        }
        case EventInitializationFailed: {
          const body = {
            message: response.message
          };
          const eventName = "typesInstallerInitializationFailed";
          this.event(body, eventName);
          break;
        }
        case EventBeginInstallTypes: {
          const body = {
            eventId: response.eventId,
            packages: response.packagesToInstall
          };
          const eventName = "beginInstallTypes";
          this.event(body, eventName);
          break;
        }
        case EventEndInstallTypes: {
          if (this.telemetryEnabled) {
            const body2 = {
              telemetryEventName: "typingsInstalled",
              payload: {
                installedPackages: response.packagesToInstall.join(","),
                installSuccess: response.installSuccess,
                typingsInstallerVersion: response.typingsInstallerVersion
              }
            };
            const eventName2 = "telemetry";
            this.event(body2, eventName2);
          }
          const body = {
            eventId: response.eventId,
            packages: response.packagesToInstall,
            success: response.installSuccess
          };
          const eventName = "endInstallTypes";
          this.event(body, eventName);
          break;
        }
        case ActionInvalidate: {
          this.projectService.updateTypingsForProject(response);
          break;
        }
        case ActionSet: {
          if (this.activeRequestCount > 0) {
            this.activeRequestCount--;
          } else {
            Debug.fail("Received too many responses");
          }
          while (!this.requestQueue.isEmpty()) {
            const queuedRequest = this.requestQueue.dequeue();
            if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) {
              this.requestMap.delete(queuedRequest.operationId);
              this.scheduleRequest(queuedRequest);
              break;
            }
            if (this.logger.hasLevel(3 /* verbose */)) {
              this.logger.info(`Skipping defunct request for: ${queuedRequest.operationId}`);
            }
          }
          this.projectService.updateTypingsForProject(response);
          this.event(response, "setTypings");
          break;
        }
        case ActionWatchTypingLocations:
          this.projectService.watchTypingLocations(response);
          break;
        default:
          assertType(response);
      }
    }
    scheduleRequest(request) {
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`Scheduling request for: ${request.operationId}`);
      }
      this.activeRequestCount++;
      this.host.setTimeout(request.operation, _NodeTypingsInstaller.requestDelayMillis);
    }
  };
  let NodeTypingsInstaller = _NodeTypingsInstaller;
  // This number is essentially arbitrary.  Processing more than one typings request
  // at a time makes sense, but having too many in the pipe results in a hang
  // (see https://github.com/nodejs/node/issues/7657).
  // It would be preferable to base our limit on the amount of space left in the
  // buffer, but we have yet to find a way to retrieve that value.
  NodeTypingsInstaller.maxActiveRequestCount = 10;
  NodeTypingsInstaller.requestDelayMillis = 100;
  class IOSession extends Session3 {
    constructor() {
      const event = (body, eventName) => {
        this.event(body, eventName);
      };
      const host = sys;
      const typingsInstaller = disableAutomaticTypingAcquisition ? void 0 : new NodeTypingsInstaller(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event);
      super({
        host,
        cancellationToken,
        ...options,
        typingsInstaller: typingsInstaller || nullTypingsInstaller,
        byteLength: Buffer.byteLength,
        hrtime: process.hrtime,
        logger,
        canUseEvents: true,
        typesMapLocation
      });
      this.eventPort = eventPort;
      if (this.canUseEvents && this.eventPort) {
        const s = net.connect({ port: this.eventPort }, () => {
          this.eventSocket = s;
          if (this.socketEventQueue) {
            for (const event2 of this.socketEventQueue) {
              this.writeToEventSocket(event2.body, event2.eventName);
            }
            this.socketEventQueue = void 0;
          }
        });
      }
      this.constructed = true;
    }
    event(body, eventName) {
      Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession");
      if (this.canUseEvents && this.eventPort) {
        if (!this.eventSocket) {
          if (this.logger.hasLevel(3 /* verbose */)) {
            this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`);
          }
          (this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName });
          return;
        } else {
          Debug.assert(this.socketEventQueue === void 0);
          this.writeToEventSocket(body, eventName);
        }
      } else {
        super.event(body, eventName);
      }
    }
    writeToEventSocket(body, eventName) {
      this.eventSocket.write(formatMessage2(toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8");
    }
    exit() {
      var _a;
      this.logger.info("Exiting...");
      this.projectService.closeLog();
      (_a = tracing) == null ? void 0 : _a.stopTracing();
      process.exit(0);
    }
    listen() {
      rl.on("line", (input) => {
        const message = input.trim();
        this.onMessage(message);
      });
      rl.on("close", () => {
        this.exit();
      });
    }
  }
  class IpcIOSession extends IOSession {
    writeMessage(msg) {
      const verboseLogging = logger.hasLevel(3 /* verbose */);
      if (verboseLogging) {
        const json = JSON.stringify(msg);
        logger.info(`${msg.type}:${indent2(json)}`);
      }
      process.send(msg);
    }
    parseMessage(message) {
      return message;
    }
    toStringMessage(message) {
      return JSON.stringify(message, void 0, 2);
    }
    listen() {
      process.on("message", (e) => {
        this.onMessage(e);
      });
      process.on("disconnect", () => {
        this.exit();
      });
    }
  }
  const eventPort = parseEventPort(findArgument("--eventPort"));
  const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation);
  const typesMapLocation = findArgument(Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json");
  const npmLocation = findArgument(Arguments.NpmLocation);
  const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation);
  const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition");
  const useNodeIpc = hasArgument("--useNodeIpc");
  const telemetryEnabled = hasArgument(Arguments.EnableTelemetry);
  const commandLineTraceDir = findArgument("--traceDirectory");
  const traceDir = commandLineTraceDir ? stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE;
  if (traceDir) {
    startTracing("server", traceDir);
  }
  const ioSession = useNodeIpc ? new IpcIOSession() : new IOSession();
  process.on("uncaughtException", (err) => {
    ioSession.logError(err, "unknown");
  });
  process.noAsar = true;
  ioSession.listen();
  function getGlobalTypingsCacheLocation() {
    switch (process.platform) {
      case "win32": {
        const basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir && os.homedir() || process.env.USERPROFILE || process.env.HOMEDRIVE && process.env.HOMEPATH && normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH) || os.tmpdir();
        return combinePaths(combinePaths(normalizeSlashes(basePath), "Microsoft/TypeScript"), versionMajorMinor);
      }
      case "openbsd":
      case "freebsd":
      case "netbsd":
      case "darwin":
      case "linux":
      case "android": {
        const cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin");
        return combinePaths(combinePaths(cacheLocation, "typescript"), versionMajorMinor);
      }
      default:
        return Debug.fail(`unsupported platform '${process.platform}'`);
    }
  }
  function getNonWindowsCacheLocation(platformIsDarwin) {
    if (process.env.XDG_CACHE_HOME) {
      return process.env.XDG_CACHE_HOME;
    }
    const usersDir = platformIsDarwin ? "Users" : "home";
    const homePath = os.homedir && os.homedir() || process.env.HOME || (process.env.LOGNAME || process.env.USER) && `/${usersDir}/${process.env.LOGNAME || process.env.USER}` || os.tmpdir();
    const cacheFolder = platformIsDarwin ? "Library/Caches" : ".cache";
    return combinePaths(normalizeSlashes(homePath), cacheFolder);
  }
}

// src/tsserver/common.ts
function getLogLevel(level) {
  if (level) {
    const l = level.toLowerCase();
    for (const name in LogLevel2) {
      if (isNaN(+name) && l === name.toLowerCase()) {
        return LogLevel2[name];
      }
    }
  }
  return void 0;
}

// src/tsserver/server.ts
function findArgumentStringArray(argName) {
  const arg = findArgument(argName);
  if (arg === void 0) {
    return emptyArray2;
  }
  return arg.split(",").filter((name) => name !== "");
}
function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }, platform) {
  logger.info(`Starting TS Server`);
  logger.info(`Version: ${version}`);
  logger.info(`Arguments: ${args.join(" ")}`);
  logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${sys.useCaseSensitiveFileNames}`);
  logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`);
  setStackTraceLimit();
  if (Debug.isDebugging) {
    Debug.enableDebugInfo();
  }
  if (sys.tryEnableSourceMapsForHost && /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))) {
    sys.tryEnableSourceMapsForHost();
  }
  console.log = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), "Info" /* Info */);
  console.warn = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), "Err" /* Err */);
  console.error = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), "Err" /* Err */);
  startServer(
    {
      globalPlugins: findArgumentStringArray("--globalPlugins"),
      pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"),
      allowLocalPluginLoads: hasArgument("--allowLocalPluginLoads"),
      useSingleInferredProject: hasArgument("--useSingleInferredProject"),
      useInferredProjectPerProjectRoot: hasArgument("--useInferredProjectPerProjectRoot"),
      suppressDiagnosticEvents: hasArgument("--suppressDiagnosticEvents"),
      noGetErrOnBackgroundUpdate: hasArgument("--noGetErrOnBackgroundUpdate"),
      serverMode
    },
    logger,
    cancellationToken
  );
}
setStackTraceLimit();
start(initializeNodeSystem(), require("os").platform());
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ANONYMOUS,
  AccessFlags,
  AssertionLevel,
  AssignmentDeclarationKind,
  AssignmentKind,
  Associativity,
  BreakpointResolver,
  BuilderFileEmit,
  BuilderProgramKind,
  BuilderState,
  BundleFileSectionKind,
  CallHierarchy,
  CharacterCodes,
  CheckFlags,
  CheckMode,
  ClassificationType,
  ClassificationTypeNames,
  CommentDirectiveType,
  Comparison,
  CompletionInfoFlags,
  CompletionTriggerKind,
  Completions,
  ConfigFileProgramReloadLevel,
  ContextFlags,
  CoreServicesShimHostAdapter,
  Debug,
  DiagnosticCategory,
  Diagnostics,
  DocumentHighlights,
  ElementFlags,
  EmitFlags,
  EmitHint,
  EmitOnly,
  EndOfLineState,
  EnumKind,
  ExitStatus,
  ExportKind,
  Extension,
  ExternalEmitHelpers,
  FileIncludeKind,
  FilePreprocessingDiagnosticsKind,
  FileSystemEntryKind,
  FileWatcherEventKind,
  FindAllReferences,
  FlattenLevel,
  FlowFlags,
  ForegroundColorEscapeSequences,
  FunctionFlags,
  GeneratedIdentifierFlags,
  GetLiteralTextFlags,
  GoToDefinition,
  HighlightSpanKind,
  ImportKind,
  ImportsNotUsedAsValues,
  IndentStyle,
  IndexFlags,
  IndexKind,
  InferenceFlags,
  InferencePriority,
  InlayHintKind,
  InlayHints,
  InternalEmitFlags,
  InternalSymbolName,
  InvalidatedProjectKind,
  JsDoc,
  JsTyping,
  JsxEmit,
  JsxFlags,
  JsxReferenceKind,
  LanguageServiceMode,
  LanguageServiceShimHostAdapter,
  LanguageVariant,
  LexicalEnvironmentFlags,
  ListFormat,
  LogLevel,
  MemberOverrideStatus,
  ModifierFlags,
  ModuleDetectionKind,
  ModuleInstanceState,
  ModuleKind,
  ModuleResolutionKind,
  ModuleSpecifierEnding,
  NavigateTo,
  NavigationBar,
  NewLineKind,
  NodeBuilderFlags,
  NodeCheckFlags,
  NodeFactoryFlags,
  NodeFlags,
  NodeResolutionFeatures,
  ObjectFlags,
  OperationCanceledException,
  OperatorPrecedence,
  OrganizeImports,
  OrganizeImportsMode,
  OuterExpressionKinds,
  OutliningElementsCollector,
  OutliningSpanKind,
  OutputFileType,
  PackageJsonAutoImportPreference,
  PackageJsonDependencyGroup,
  PatternMatchKind,
  PollingInterval,
  PollingWatchKind,
  PragmaKindFlags,
  PrivateIdentifierKind,
  ProcessLevel,
  QuotePreference,
  RelationComparisonResult,
  Rename,
  ScriptElementKind,
  ScriptElementKindModifier,
  ScriptKind,
  ScriptSnapshot,
  ScriptTarget,
  SemanticClassificationFormat,
  SemanticMeaning,
  SemicolonPreference,
  SignatureCheckMode,
  SignatureFlags,
  SignatureHelp,
  SignatureKind,
  SmartSelectionRange,
  SnippetKind,
  SortKind,
  StructureIsReused,
  SymbolAccessibility,
  SymbolDisplay,
  SymbolDisplayPartKind,
  SymbolFlags,
  SymbolFormatFlags,
  SyntaxKind,
  SyntheticSymbolKind,
  Ternary,
  ThrottledCancellationToken,
  TokenClass,
  TokenFlags,
  TransformFlags,
  TypeFacts,
  TypeFlags,
  TypeFormatFlags,
  TypeMapKind,
  TypePredicateKind,
  TypeReferenceSerializationKind,
  TypeScriptServicesFactory,
  UnionReduction,
  UpToDateStatusType,
  VarianceFlags,
  Version,
  VersionRange,
  WatchDirectoryFlags,
  WatchDirectoryKind,
  WatchFileKind,
  WatchLogLevel,
  WatchType,
  accessPrivateIdentifier,
  addEmitFlags,
  addEmitHelper,
  addEmitHelpers,
  addInternalEmitFlags,
  addNodeFactoryPatcher,
  addObjectAllocatorPatcher,
  addRange,
  addRelatedInfo,
  addSyntheticLeadingComment,
  addSyntheticTrailingComment,
  addToSeen,
  advancedAsyncSuperHelper,
  affectsDeclarationPathOptionDeclarations,
  affectsEmitOptionDeclarations,
  allKeysStartWithDot,
  altDirectorySeparator,
  and,
  append,
  appendIfUnique,
  arrayFrom,
  arrayIsEqualTo,
  arrayIsHomogeneous,
  arrayIsSorted,
  arrayOf,
  arrayReverseIterator,
  arrayToMap,
  arrayToMultiMap,
  arrayToNumericMap,
  arraysEqual,
  assertType,
  assign,
  assignHelper,
  asyncDelegator,
  asyncGeneratorHelper,
  asyncSuperHelper,
  asyncValues,
  attachFileToDiagnostics,
  awaitHelper,
  awaiterHelper,
  base64decode,
  base64encode,
  binarySearch,
  binarySearchKey,
  bindSourceFile,
  breakIntoCharacterSpans,
  breakIntoWordSpans,
  buildLinkParts,
  buildOpts,
  buildOverload,
  bundlerModuleNameResolver,
  canBeConvertedToAsync,
  canHaveDecorators,
  canHaveExportModifier,
  canHaveFlowNode,
  canHaveIllegalDecorators,
  canHaveIllegalModifiers,
  canHaveIllegalType,
  canHaveIllegalTypeParameters,
  canHaveJSDoc,
  canHaveLocals,
  canHaveModifiers,
  canHaveSymbol,
  canJsonReportNoInputFiles,
  canProduceDiagnostics,
  canUsePropertyAccess,
  canWatchAffectingLocation,
  canWatchAtTypes,
  canWatchDirectoryOrFile,
  cartesianProduct,
  cast,
  chainBundle,
  chainDiagnosticMessages,
  changeAnyExtension,
  changeCompilerHostLikeToUseCache,
  changeExtension,
  changesAffectModuleResolution,
  changesAffectingProgramStructure,
  childIsDecorated,
  classElementOrClassElementParameterIsDecorated,
  classOrConstructorParameterIsDecorated,
  classPrivateFieldGetHelper,
  classPrivateFieldInHelper,
  classPrivateFieldSetHelper,
  classicNameResolver,
  classifier,
  cleanExtendedConfigCache,
  clear,
  clearMap,
  clearSharedExtendedConfigFileWatcher,
  climbPastPropertyAccess,
  climbPastPropertyOrElementAccess,
  clone,
  cloneCompilerOptions,
  closeFileWatcher,
  closeFileWatcherOf,
  codefix,
  collapseTextChangeRangesAcrossMultipleVersions,
  collectExternalModuleInfo,
  combine,
  combinePaths,
  commentPragmas,
  commonOptionsWithBuild,
  commonPackageFolders,
  compact,
  compareBooleans,
  compareDataObjects,
  compareDiagnostics,
  compareDiagnosticsSkipRelatedInformation,
  compareEmitHelpers,
  compareNumberOfDirectorySeparators,
  comparePaths,
  comparePathsCaseInsensitive,
  comparePathsCaseSensitive,
  comparePatternKeys,
  compareProperties,
  compareStringsCaseInsensitive,
  compareStringsCaseInsensitiveEslintCompatible,
  compareStringsCaseSensitive,
  compareStringsCaseSensitiveUI,
  compareTextSpans,
  compareValues,
  compileOnSaveCommandLineOption,
  compilerOptionsAffectDeclarationPath,
  compilerOptionsAffectEmit,
  compilerOptionsAffectSemanticDiagnostics,
  compilerOptionsDidYouMeanDiagnostics,
  compilerOptionsIndicateEsModules,
  compose,
  computeCommonSourceDirectoryOfFilenames,
  computeLineAndCharacterOfPosition,
  computeLineOfPosition,
  computeLineStarts,
  computePositionOfLineAndCharacter,
  computeSignature,
  computeSignatureWithDiagnostics,
  computeSuggestionDiagnostics,
  concatenate,
  concatenateDiagnosticMessageChains,
  consumesNodeCoreModules,
  contains,
  containsIgnoredPath,
  containsObjectRestOrSpread,
  containsParseError,
  containsPath,
  convertCompilerOptionsForTelemetry,
  convertCompilerOptionsFromJson,
  convertJsonOption,
  convertToBase64,
  convertToJson,
  convertToObject,
  convertToOptionsWithAbsolutePaths,
  convertToRelativePath,
  convertToTSConfig,
  convertTypeAcquisitionFromJson,
  copyComments,
  copyEntries,
  copyLeadingComments,
  copyProperties,
  copyTrailingAsLeadingComments,
  copyTrailingComments,
  couldStartTrivia,
  countWhere,
  createAbstractBuilder,
  createAccessorPropertyBackingField,
  createAccessorPropertyGetRedirector,
  createAccessorPropertySetRedirector,
  createBaseNodeFactory,
  createBinaryExpressionTrampoline,
  createBindingHelper,
  createBuildInfo,
  createBuilderProgram,
  createBuilderProgramUsingProgramBuildInfo,
  createBuilderStatusReporter,
  createCacheWithRedirects,
  createCacheableExportInfoMap,
  createCachedDirectoryStructureHost,
  createClassifier,
  createCommentDirectivesMap,
  createCompilerDiagnostic,
  createCompilerDiagnosticForInvalidCustomType,
  createCompilerDiagnosticFromMessageChain,
  createCompilerHost,
  createCompilerHostFromProgramHost,
  createCompilerHostWorker,
  createDetachedDiagnostic,
  createDiagnosticCollection,
  createDiagnosticForFileFromMessageChain,
  createDiagnosticForNode,
  createDiagnosticForNodeArray,
  createDiagnosticForNodeArrayFromMessageChain,
  createDiagnosticForNodeFromMessageChain,
  createDiagnosticForNodeInSourceFile,
  createDiagnosticForRange,
  createDiagnosticMessageChainFromDiagnostic,
  createDiagnosticReporter,
  createDocumentPositionMapper,
  createDocumentRegistry,
  createDocumentRegistryInternal,
  createEmitAndSemanticDiagnosticsBuilderProgram,
  createEmitHelperFactory,
  createEmptyExports,
  createExpressionForJsxElement,
  createExpressionForJsxFragment,
  createExpressionForObjectLiteralElementLike,
  createExpressionForPropertyName,
  createExpressionFromEntityName,
  createExternalHelpersImportDeclarationIfNeeded,
  createFileDiagnostic,
  createFileDiagnosticFromMessageChain,
  createForOfBindingStatement,
  createGetCanonicalFileName,
  createGetSourceFile,
  createGetSymbolAccessibilityDiagnosticForNode,
  createGetSymbolAccessibilityDiagnosticForNodeName,
  createGetSymbolWalker,
  createIncrementalCompilerHost,
  createIncrementalProgram,
  createInputFiles,
  createInputFilesWithFilePaths,
  createInputFilesWithFileTexts,
  createJsxFactoryExpression,
  createLanguageService,
  createLanguageServiceSourceFile,
  createMemberAccessForPropertyName,
  createModeAwareCache,
  createModeAwareCacheKey,
  createModuleNotFoundChain,
  createModuleResolutionCache,
  createModuleResolutionLoader,
  createModuleSpecifierResolutionHost,
  createMultiMap,
  createNodeConverters,
  createNodeFactory,
  createOptionNameMap,
  createOverload,
  createPackageJsonImportFilter,
  createPackageJsonInfo,
  createParenthesizerRules,
  createPatternMatcher,
  createPrependNodes,
  createPrinter,
  createPrinterWithDefaults,
  createPrinterWithRemoveComments,
  createPrinterWithRemoveCommentsNeverAsciiEscape,
  createPrinterWithRemoveCommentsOmitTrailingSemicolon,
  createProgram,
  createProgramHost,
  createPropertyNameNodeForIdentifierOrLiteral,
  createQueue,
  createRange,
  createRedirectedBuilderProgram,
  createResolutionCache,
  createRuntimeTypeSerializer,
  createScanner,
  createSemanticDiagnosticsBuilderProgram,
  createSet,
  createSolutionBuilder,
  createSolutionBuilderHost,
  createSolutionBuilderWithWatch,
  createSolutionBuilderWithWatchHost,
  createSortedArray,
  createSourceFile,
  createSourceMapGenerator,
  createSourceMapSource,
  createSuperAccessVariableStatement,
  createSymbolTable,
  createSymlinkCache,
  createSystemWatchFunctions,
  createTextChange,
  createTextChangeFromStartLength,
  createTextChangeRange,
  createTextRangeFromNode,
  createTextRangeFromSpan,
  createTextSpan,
  createTextSpanFromBounds,
  createTextSpanFromNode,
  createTextSpanFromRange,
  createTextSpanFromStringLiteralLikeContent,
  createTextWriter,
  createTokenRange,
  createTypeChecker,
  createTypeReferenceDirectiveResolutionCache,
  createTypeReferenceResolutionLoader,
  createUnparsedSourceFile,
  createWatchCompilerHost,
  createWatchCompilerHostOfConfigFile,
  createWatchCompilerHostOfFilesAndCompilerOptions,
  createWatchFactory,
  createWatchHost,
  createWatchProgram,
  createWatchStatusReporter,
  createWriteFileMeasuringIO,
  declarationNameToString,
  decodeMappings,
  decodedTextSpanIntersectsWith,
  decorateHelper,
  deduplicate,
  defaultIncludeSpec,
  defaultInitCompilerOptions,
  defaultMaximumTruncationLength,
  detectSortCaseSensitivity,
  diagnosticCategoryName,
  diagnosticToString,
  directoryProbablyExists,
  directorySeparator,
  displayPart,
  displayPartsToString,
  disposeEmitNodes,
  documentSpansEqual,
  dumpTracingLegend,
  elementAt,
  elideNodes,
  emitComments,
  emitDetachedComments,
  emitFiles,
  emitFilesAndReportErrors,
  emitFilesAndReportErrorsAndGetExitStatus,
  emitModuleKindIsNonNodeESM,
  emitNewLineBeforeLeadingCommentOfPosition,
  emitNewLineBeforeLeadingComments,
  emitNewLineBeforeLeadingCommentsOfPosition,
  emitSkippedWithNoDiagnostics,
  emitUsingBuildInfo,
  emptyArray,
  emptyFileSystemEntries,
  emptyMap,
  emptyOptions,
  emptySet,
  endsWith,
  ensurePathIsNonModuleName,
  ensureScriptKind,
  ensureTrailingDirectorySeparator,
  entityNameToString,
  enumerateInsertsAndDeletes,
  equalOwnProperties,
  equateStringsCaseInsensitive,
  equateStringsCaseSensitive,
  equateValues,
  esDecorateHelper,
  escapeJsxAttributeString,
  escapeLeadingUnderscores,
  escapeNonAsciiString,
  escapeSnippetText,
  escapeString,
  every,
  expandPreOrPostfixIncrementOrDecrementExpression,
  explainFiles,
  explainIfFileIsRedirectAndImpliedFormat,
  exportAssignmentIsAlias,
  exportStarHelper,
  expressionResultIsUnused,
  extend,
  extendsHelper,
  extensionFromPath,
  extensionIsTS,
  extensionsNotSupportingExtensionlessResolution,
  externalHelpersModuleNameText,
  factory,
  fileExtensionIs,
  fileExtensionIsOneOf,
  fileIncludeReasonToDiagnostics,
  fileShouldUseJavaScriptRequire,
  filter,
  filterMutate,
  filterSemanticDiagnostics,
  find,
  findAncestor,
  findBestPatternMatch,
  findChildOfKind,
  findComputedPropertyNameCacheAssignment,
  findConfigFile,
  findContainingList,
  findDiagnosticForNode,
  findFirstNonJsxWhitespaceToken,
  findIndex,
  findLast,
  findLastIndex,
  findListItemInfo,
  findMap,
  findModifier,
  findNextToken,
  findPackageJson,
  findPackageJsons,
  findPrecedingMatchingToken,
  findPrecedingToken,
  findSuperStatementIndex,
  findTokenOnLeftOfPosition,
  findUseStrictPrologue,
  first,
  firstDefined,
  firstDefinedIterator,
  firstIterator,
  firstOrOnly,
  firstOrUndefined,
  firstOrUndefinedIterator,
  fixupCompilerOptions,
  flatMap,
  flatMapIterator,
  flatMapToMutable,
  flatten,
  flattenCommaList,
  flattenDestructuringAssignment,
  flattenDestructuringBinding,
  flattenDiagnosticMessageText,
  forEach,
  forEachAncestor,
  forEachAncestorDirectory,
  forEachChild,
  forEachChildRecursively,
  forEachEmittedFile,
  forEachEnclosingBlockScopeContainer,
  forEachEntry,
  forEachExternalModuleToImportFrom,
  forEachImportClauseDeclaration,
  forEachKey,
  forEachLeadingCommentRange,
  forEachNameInAccessChainWalkingLeft,
  forEachPropertyAssignment,
  forEachResolvedProjectReference,
  forEachReturnStatement,
  forEachRight,
  forEachTrailingCommentRange,
  forEachTsConfigPropArray,
  forEachUnique,
  forEachYieldExpression,
  forSomeAncestorDirectory,
  formatColorAndReset,
  formatDiagnostic,
  formatDiagnostics,
  formatDiagnosticsWithColorAndContext,
  formatGeneratedName,
  formatGeneratedNamePart,
  formatLocation,
  formatMessage,
  formatStringFromArgs,
  formatting,
  fullTripleSlashAMDReferencePathRegEx,
  fullTripleSlashReferencePathRegEx,
  generateDjb2Hash,
  generateTSConfig,
  generatorHelper,
  getAdjustedReferenceLocation,
  getAdjustedRenameLocation,
  getAliasDeclarationFromName,
  getAllAccessorDeclarations,
  getAllDecoratorsOfClass,
  getAllDecoratorsOfClassElement,
  getAllJSDocTags,
  getAllJSDocTagsOfKind,
  getAllKeys,
  getAllProjectOutputs,
  getAllSuperTypeNodes,
  getAllUnscopedEmitHelpers,
  getAllowJSCompilerOption,
  getAllowSyntheticDefaultImports,
  getAncestor,
  getAnyExtensionFromPath,
  getAreDeclarationMapsEnabled,
  getAssignedExpandoInitializer,
  getAssignedName,
  getAssignmentDeclarationKind,
  getAssignmentDeclarationPropertyAccessKind,
  getAssignmentTargetKind,
  getAutomaticTypeDirectiveNames,
  getBaseFileName,
  getBinaryOperatorPrecedence,
  getBuildInfo,
  getBuildInfoFileVersionMap,
  getBuildInfoText,
  getBuildOrderFromAnyBuildOrder,
  getBuilderCreationParameters,
  getBuilderFileEmit,
  getCheckFlags,
  getClassExtendsHeritageElement,
  getClassLikeDeclarationOfSymbol,
  getCombinedLocalAndExportSymbolFlags,
  getCombinedModifierFlags,
  getCombinedNodeFlags,
  getCombinedNodeFlagsAlwaysIncludeJSDoc,
  getCommentRange,
  getCommonSourceDirectory,
  getCommonSourceDirectoryOfConfig,
  getCompilerOptionValue,
  getCompilerOptionsDiffValue,
  getConditions,
  getConfigFileParsingDiagnostics,
  getConstantValue,
  getContainerNode,
  getContainingClass,
  getContainingClassStaticBlock,
  getContainingFunction,
  getContainingFunctionDeclaration,
  getContainingFunctionOrClassStaticBlock,
  getContainingNodeArray,
  getContainingObjectLiteralElement,
  getContextualTypeFromParent,
  getContextualTypeFromParentOrAncestorTypeNode,
  getCurrentTime,
  getDeclarationDiagnostics,
  getDeclarationEmitExtensionForPath,
  getDeclarationEmitOutputFilePath,
  getDeclarationEmitOutputFilePathWorker,
  getDeclarationFromName,
  getDeclarationModifierFlagsFromSymbol,
  getDeclarationOfKind,
  getDeclarationsOfKind,
  getDeclaredExpandoInitializer,
  getDecorators,
  getDefaultCompilerOptions,
  getDefaultExportInfoWorker,
  getDefaultFormatCodeSettings,
  getDefaultLibFileName,
  getDefaultLibFilePath,
  getDefaultLikeExportInfo,
  getDiagnosticText,
  getDiagnosticsWithinSpan,
  getDirectoryPath,
  getDirectoryToWatchFailedLookupLocation,
  getDirectoryToWatchFailedLookupLocationFromTypeRoot,
  getDocumentPositionMapper,
  getESModuleInterop,
  getEditsForFileRename,
  getEffectiveBaseTypeNode,
  getEffectiveConstraintOfTypeParameter,
  getEffectiveContainerForJSDocTemplateTag,
  getEffectiveImplementsTypeNodes,
  getEffectiveInitializer,
  getEffectiveJSDocHost,
  getEffectiveModifierFlags,
  getEffectiveModifierFlagsAlwaysIncludeJSDoc,
  getEffectiveModifierFlagsNoCache,
  getEffectiveReturnTypeNode,
  getEffectiveSetAccessorTypeAnnotationNode,
  getEffectiveTypeAnnotationNode,
  getEffectiveTypeParameterDeclarations,
  getEffectiveTypeRoots,
  getElementOrPropertyAccessArgumentExpressionOrName,
  getElementOrPropertyAccessName,
  getElementsOfBindingOrAssignmentPattern,
  getEmitDeclarations,
  getEmitFlags,
  getEmitHelpers,
  getEmitModuleDetectionKind,
  getEmitModuleKind,
  getEmitModuleResolutionKind,
  getEmitScriptTarget,
  getEnclosingBlockScopeContainer,
  getEncodedSemanticClassifications,
  getEncodedSyntacticClassifications,
  getEndLinePosition,
  getEntityNameFromTypeNode,
  getEntrypointsFromPackageJsonInfo,
  getErrorCountForSummary,
  getErrorSpanForNode,
  getErrorSummaryText,
  getEscapedTextOfIdentifierOrLiteral,
  getEscapedTextOfJsxAttributeName,
  getEscapedTextOfJsxNamespacedName,
  getExpandoInitializer,
  getExportAssignmentExpression,
  getExportInfoMap,
  getExportNeedsImportStarHelper,
  getExpressionAssociativity,
  getExpressionPrecedence,
  getExternalHelpersModuleName,
  getExternalModuleImportEqualsDeclarationExpression,
  getExternalModuleName,
  getExternalModuleNameFromDeclaration,
  getExternalModuleNameFromPath,
  getExternalModuleNameLiteral,
  getExternalModuleRequireArgument,
  getFallbackOptions,
  getFileEmitOutput,
  getFileMatcherPatterns,
  getFileNamesFromConfigSpecs,
  getFileWatcherEventKind,
  getFilesInErrorForSummary,
  getFirstConstructorWithBody,
  getFirstIdentifier,
  getFirstNonSpaceCharacterPosition,
  getFirstProjectOutput,
  getFixableErrorSpanExpression,
  getFormatCodeSettingsForWriting,
  getFullWidth,
  getFunctionFlags,
  getHeritageClause,
  getHostSignatureFromJSDoc,
  getIdentifierAutoGenerate,
  getIdentifierGeneratedImportReference,
  getIdentifierTypeArguments,
  getImmediatelyInvokedFunctionExpression,
  getImpliedNodeFormatForFile,
  getImpliedNodeFormatForFileWorker,
  getImportNeedsImportDefaultHelper,
  getImportNeedsImportStarHelper,
  getIndentSize,
  getIndentString,
  getInferredLibraryNameResolveFrom,
  getInitializedVariables,
  getInitializerOfBinaryExpression,
  getInitializerOfBindingOrAssignmentElement,
  getInterfaceBaseTypeNodes,
  getInternalEmitFlags,
  getInvokedExpression,
  getIsolatedModules,
  getJSDocAugmentsTag,
  getJSDocClassTag,
  getJSDocCommentRanges,
  getJSDocCommentsAndTags,
  getJSDocDeprecatedTag,
  getJSDocDeprecatedTagNoCache,
  getJSDocEnumTag,
  getJSDocHost,
  getJSDocImplementsTags,
  getJSDocOverrideTagNoCache,
  getJSDocParameterTags,
  getJSDocParameterTagsNoCache,
  getJSDocPrivateTag,
  getJSDocPrivateTagNoCache,
  getJSDocProtectedTag,
  getJSDocProtectedTagNoCache,
  getJSDocPublicTag,
  getJSDocPublicTagNoCache,
  getJSDocReadonlyTag,
  getJSDocReadonlyTagNoCache,
  getJSDocReturnTag,
  getJSDocReturnType,
  getJSDocRoot,
  getJSDocSatisfiesExpressionType,
  getJSDocSatisfiesTag,
  getJSDocTags,
  getJSDocTagsNoCache,
  getJSDocTemplateTag,
  getJSDocThisTag,
  getJSDocType,
  getJSDocTypeAliasName,
  getJSDocTypeAssertionType,
  getJSDocTypeParameterDeclarations,
  getJSDocTypeParameterTags,
  getJSDocTypeParameterTagsNoCache,
  getJSDocTypeTag,
  getJSXImplicitImportBase,
  getJSXRuntimeImport,
  getJSXTransformEnabled,
  getKeyForCompilerOptions,
  getLanguageVariant,
  getLastChild,
  getLeadingCommentRanges,
  getLeadingCommentRangesOfNode,
  getLeftmostAccessExpression,
  getLeftmostExpression,
  getLineAndCharacterOfPosition,
  getLineInfo,
  getLineOfLocalPosition,
  getLineOfLocalPositionFromLineMap,
  getLineStartPositionForPosition,
  getLineStarts,
  getLinesBetweenPositionAndNextNonWhitespaceCharacter,
  getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter,
  getLinesBetweenPositions,
  getLinesBetweenRangeEndAndRangeStart,
  getLinesBetweenRangeEndPositions,
  getLiteralText,
  getLocalNameForExternalImport,
  getLocalSymbolForExportDefault,
  getLocaleSpecificMessage,
  getLocaleTimeString,
  getMappedContextSpan,
  getMappedDocumentSpan,
  getMappedLocation,
  getMatchedFileSpec,
  getMatchedIncludeSpec,
  getMeaningFromDeclaration,
  getMeaningFromLocation,
  getMembersOfDeclaration,
  getModeForFileReference,
  getModeForResolutionAtIndex,
  getModeForUsageLocation,
  getModifiedTime,
  getModifiers,
  getModuleInstanceState,
  getModuleNameStringLiteralAt,
  getModuleSpecifierEndingPreference,
  getModuleSpecifierResolverHost,
  getNameForExportedSymbol,
  getNameFromIndexInfo,
  getNameFromPropertyName,
  getNameOfAccessExpression,
  getNameOfCompilerOptionValue,
  getNameOfDeclaration,
  getNameOfExpando,
  getNameOfJSDocTypedef,
  getNameOrArgument,
  getNameTable,
  getNamesForExportedSymbol,
  getNamespaceDeclarationNode,
  getNewLineCharacter,
  getNewLineKind,
  getNewLineOrDefaultFromHost,
  getNewTargetContainer,
  getNextJSDocCommentLocation,
  getNodeForGeneratedName,
  getNodeId,
  getNodeKind,
  getNodeModifiers,
  getNodeModulePathParts,
  getNonAssignedNameOfDeclaration,
  getNonAssignmentOperatorForCompoundAssignment,
  getNonAugmentationDeclaration,
  getNonDecoratorTokenPosOfNode,
  getNormalizedAbsolutePath,
  getNormalizedAbsolutePathWithoutRoot,
  getNormalizedPathComponents,
  getObjectFlags,
  getOperator,
  getOperatorAssociativity,
  getOperatorPrecedence,
  getOptionFromName,
  getOptionsForLibraryResolution,
  getOptionsNameMap,
  getOrCreateEmitNode,
  getOrCreateExternalHelpersModuleNameIfNeeded,
  getOrUpdate,
  getOriginalNode,
  getOriginalNodeId,
  getOriginalSourceFile,
  getOutputDeclarationFileName,
  getOutputExtension,
  getOutputFileNames,
  getOutputPathsFor,
  getOutputPathsForBundle,
  getOwnEmitOutputFilePath,
  getOwnKeys,
  getOwnValues,
  getPackageJsonInfo,
  getPackageJsonTypesVersionsPaths,
  getPackageJsonsVisibleToFile,
  getPackageNameFromTypesPackageName,
  getPackageScopeForPath,
  getParameterSymbolFromJSDoc,
  getParameterTypeNode,
  getParentNodeInSpan,
  getParseTreeNode,
  getParsedCommandLineOfConfigFile,
  getPathComponents,
  getPathComponentsRelativeTo,
  getPathFromPathComponents,
  getPathUpdater,
  getPathsBasePath,
  getPatternFromSpec,
  getPendingEmitKind,
  getPositionOfLineAndCharacter,
  getPossibleGenericSignatures,
  getPossibleOriginalInputExtensionForExtension,
  getPossibleTypeArgumentsInfo,
  getPreEmitDiagnostics,
  getPrecedingNonSpaceCharacterPosition,
  getPrivateIdentifier,
  getProperties,
  getProperty,
  getPropertyArrayElementValue,
  getPropertyAssignmentAliasLikeExpression,
  getPropertyNameForPropertyNameNode,
  getPropertyNameForUniqueESSymbol,
  getPropertyNameOfBindingOrAssignmentElement,
  getPropertySymbolFromBindingElement,
  getPropertySymbolsFromContextualType,
  getQuoteFromPreference,
  getQuotePreference,
  getRangesWhere,
  getRefactorContextSpan,
  getReferencedFileLocation,
  getRegexFromPattern,
  getRegularExpressionForWildcard,
  getRegularExpressionsForWildcards,
  getRelativePathFromDirectory,
  getRelativePathFromFile,
  getRelativePathToDirectoryOrUrl,
  getRenameLocation,
  getReplacementSpanForContextToken,
  getResolutionDiagnostic,
  getResolutionModeOverrideForClause,
  getResolveJsonModule,
  getResolvePackageJsonExports,
  getResolvePackageJsonImports,
  getResolvedExternalModuleName,
  getResolvedModule,
  getResolvedTypeReferenceDirective,
  getRestIndicatorOfBindingOrAssignmentElement,
  getRestParameterElementType,
  getRightMostAssignedExpression,
  getRootDeclaration,
  getRootDirectoryOfResolutionCache,
  getRootLength,
  getRootPathSplitLength,
  getScriptKind,
  getScriptKindFromFileName,
  getScriptTargetFeatures,
  getSelectedEffectiveModifierFlags,
  getSelectedSyntacticModifierFlags,
  getSemanticClassifications,
  getSemanticJsxChildren,
  getSetAccessorTypeAnnotationNode,
  getSetAccessorValueParameter,
  getSetExternalModuleIndicator,
  getShebang,
  getSingleInitializerOfVariableStatementOrPropertyDeclaration,
  getSingleVariableOfVariableStatement,
  getSnapshotText,
  getSnippetElement,
  getSourceFileOfModule,
  getSourceFileOfNode,
  getSourceFilePathInNewDir,
  getSourceFilePathInNewDirWorker,
  getSourceFileVersionAsHashFromText,
  getSourceFilesToEmit,
  getSourceMapRange,
  getSourceMapper,
  getSourceTextOfNodeFromSourceFile,
  getSpanOfTokenAtPosition,
  getSpellingSuggestion,
  getStartPositionOfLine,
  getStartPositionOfRange,
  getStartsOnNewLine,
  getStaticPropertiesAndClassStaticBlock,
  getStrictOptionValue,
  getStringComparer,
  getSuperCallFromStatement,
  getSuperContainer,
  getSupportedCodeFixes,
  getSupportedExtensions,
  getSupportedExtensionsWithJsonIfResolveJsonModule,
  getSwitchedType,
  getSymbolId,
  getSymbolNameForPrivateIdentifier,
  getSymbolTarget,
  getSyntacticClassifications,
  getSyntacticModifierFlags,
  getSyntacticModifierFlagsNoCache,
  getSynthesizedDeepClone,
  getSynthesizedDeepCloneWithReplacements,
  getSynthesizedDeepClones,
  getSynthesizedDeepClonesWithReplacements,
  getSyntheticLeadingComments,
  getSyntheticTrailingComments,
  getTargetLabel,
  getTargetOfBindingOrAssignmentElement,
  getTemporaryModuleResolutionState,
  getTextOfConstantValue,
  getTextOfIdentifierOrLiteral,
  getTextOfJSDocComment,
  getTextOfJsxAttributeName,
  getTextOfJsxNamespacedName,
  getTextOfNode,
  getTextOfNodeFromSourceText,
  getTextOfPropertyName,
  getThisContainer,
  getThisParameter,
  getTokenAtPosition,
  getTokenPosOfNode,
  getTokenSourceMapRange,
  getTouchingPropertyName,
  getTouchingToken,
  getTrailingCommentRanges,
  getTrailingSemicolonDeferringWriter,
  getTransformFlagsSubtreeExclusions,
  getTransformers,
  getTsBuildInfoEmitOutputFilePath,
  getTsConfigObjectLiteralExpression,
  getTsConfigPropArrayElementValue,
  getTypeAnnotationNode,
  getTypeArgumentOrTypeParameterList,
  getTypeKeywordOfTypeOnlyImport,
  getTypeNode,
  getTypeNodeIfAccessible,
  getTypeParameterFromJsDoc,
  getTypeParameterOwner,
  getTypesPackageName,
  getUILocale,
  getUniqueName,
  getUniqueSymbolId,
  getUseDefineForClassFields,
  getWatchErrorSummaryDiagnosticMessage,
  getWatchFactory,
  group,
  groupBy,
  guessIndentation,
  handleNoEmitOptions,
  hasAbstractModifier,
  hasAccessorModifier,
  hasAmbientModifier,
  hasChangesInResolutions,
  hasChildOfKind,
  hasContextSensitiveParameters,
  hasDecorators,
  hasDocComment,
  hasDynamicName,
  hasEffectiveModifier,
  hasEffectiveModifiers,
  hasEffectiveReadonlyModifier,
  hasExtension,
  hasIndexSignature,
  hasInitializer,
  hasInvalidEscape,
  hasJSDocNodes,
  hasJSDocParameterTags,
  hasJSFileExtension,
  hasJsonModuleEmitEnabled,
  hasOnlyExpressionInitializer,
  hasOverrideModifier,
  hasPossibleExternalModuleReference,
  hasProperty,
  hasPropertyAccessExpressionWithName,
  hasQuestionToken,
  hasRecordedExternalHelpers,
  hasRestParameter,
  hasScopeMarker,
  hasStaticModifier,
  hasSyntacticModifier,
  hasSyntacticModifiers,
  hasTSFileExtension,
  hasTabstop,
  hasTrailingDirectorySeparator,
  hasType,
  hasTypeArguments,
  hasZeroOrOneAsteriskCharacter,
  helperString,
  hostGetCanonicalFileName,
  hostUsesCaseSensitiveFileNames,
  idText,
  identifierIsThisKeyword,
  identifierToKeywordKind,
  identity,
  identitySourceMapConsumer,
  ignoreSourceNewlines,
  ignoredPaths,
  importDefaultHelper,
  importFromModuleSpecifier,
  importNameElisionDisabled,
  importStarHelper,
  indexOfAnyCharCode,
  indexOfNode,
  indicesOf,
  inferredTypesContainingFile,
  insertImports,
  insertLeadingStatement,
  insertSorted,
  insertStatementAfterCustomPrologue,
  insertStatementAfterStandardPrologue,
  insertStatementsAfterCustomPrologue,
  insertStatementsAfterStandardPrologue,
  intersperse,
  intrinsicTagNameToString,
  introducesArgumentsExoticObject,
  inverseJsxOptionMap,
  isAbstractConstructorSymbol,
  isAbstractModifier,
  isAccessExpression,
  isAccessibilityModifier,
  isAccessor,
  isAccessorModifier,
  isAliasSymbolDeclaration,
  isAliasableExpression,
  isAmbientModule,
  isAmbientPropertyDeclaration,
  isAnonymousFunctionDefinition,
  isAnyDirectorySeparator,
  isAnyImportOrBareOrAccessedRequire,
  isAnyImportOrReExport,
  isAnyImportSyntax,
  isAnySupportedFileExtension,
  isApplicableVersionedTypesKey,
  isArgumentExpressionOfElementAccess,
  isArray,
  isArrayBindingElement,
  isArrayBindingOrAssignmentElement,
  isArrayBindingOrAssignmentPattern,
  isArrayBindingPattern,
  isArrayLiteralExpression,
  isArrayLiteralOrObjectLiteralDestructuringPattern,
  isArrayTypeNode,
  isArrowFunction,
  isAsExpression,
  isAssertClause,
  isAssertEntry,
  isAssertionExpression,
  isAssertionKey,
  isAssertsKeyword,
  isAssignmentDeclaration,
  isAssignmentExpression,
  isAssignmentOperator,
  isAssignmentPattern,
  isAssignmentTarget,
  isAsteriskToken,
  isAsyncFunction,
  isAsyncModifier,
  isAutoAccessorPropertyDeclaration,
  isAwaitExpression,
  isAwaitKeyword,
  isBigIntLiteral,
  isBinaryExpression,
  isBinaryOperatorToken,
  isBindableObjectDefinePropertyCall,
  isBindableStaticAccessExpression,
  isBindableStaticElementAccessExpression,
  isBindableStaticNameExpression,
  isBindingElement,
  isBindingElementOfBareOrAccessedRequire,
  isBindingName,
  isBindingOrAssignmentElement,
  isBindingOrAssignmentPattern,
  isBindingPattern,
  isBlock,
  isBlockOrCatchScoped,
  isBlockScope,
  isBlockScopedContainerTopLevel,
  isBooleanLiteral,
  isBreakOrContinueStatement,
  isBreakStatement,
  isBuildInfoFile,
  isBuilderProgram,
  isBundle,
  isBundleFileTextLike,
  isCallChain,
  isCallExpression,
  isCallExpressionTarget,
  isCallLikeExpression,
  isCallOrNewExpression,
  isCallOrNewExpressionTarget,
  isCallSignatureDeclaration,
  isCallToHelper,
  isCaseBlock,
  isCaseClause,
  isCaseKeyword,
  isCaseOrDefaultClause,
  isCatchClause,
  isCatchClauseVariableDeclaration,
  isCatchClauseVariableDeclarationOrBindingElement,
  isCheckJsEnabledForFile,
  isChildOfNodeWithKind,
  isCircularBuildOrder,
  isClassDeclaration,
  isClassElement,
  isClassExpression,
  isClassLike,
  isClassMemberModifier,
  isClassOrTypeElement,
  isClassStaticBlockDeclaration,
  isCollapsedRange,
  isColonToken,
  isCommaExpression,
  isCommaListExpression,
  isCommaSequence,
  isCommaToken,
  isComment,
  isCommonJsExportPropertyAssignment,
  isCommonJsExportedExpression,
  isCompoundAssignment,
  isComputedNonLiteralName,
  isComputedPropertyName,
  isConciseBody,
  isConditionalExpression,
  isConditionalTypeNode,
  isConstTypeReference,
  isConstructSignatureDeclaration,
  isConstructorDeclaration,
  isConstructorTypeNode,
  isContextualKeyword,
  isContinueStatement,
  isCustomPrologue,
  isDebuggerStatement,
  isDeclaration,
  isDeclarationBindingElement,
  isDeclarationFileName,
  isDeclarationName,
  isDeclarationNameOfEnumOrNamespace,
  isDeclarationReadonly,
  isDeclarationStatement,
  isDeclarationWithTypeParameterChildren,
  isDeclarationWithTypeParameters,
  isDecorator,
  isDecoratorTarget,
  isDefaultClause,
  isDefaultImport,
  isDefaultModifier,
  isDefaultedExpandoInitializer,
  isDeleteExpression,
  isDeleteTarget,
  isDeprecatedDeclaration,
  isDestructuringAssignment,
  isDiagnosticWithLocation,
  isDiskPathRoot,
  isDoStatement,
  isDotDotDotToken,
  isDottedName,
  isDynamicName,
  isESSymbolIdentifier,
  isEffectiveExternalModule,
  isEffectiveModuleDeclaration,
  isEffectiveStrictModeSourceFile,
  isElementAccessChain,
  isElementAccessExpression,
  isEmittedFileOfProgram,
  isEmptyArrayLiteral,
  isEmptyBindingElement,
  isEmptyBindingPattern,
  isEmptyObjectLiteral,
  isEmptyStatement,
  isEmptyStringLiteral,
  isEntityName,
  isEntityNameExpression,
  isEnumConst,
  isEnumDeclaration,
  isEnumMember,
  isEqualityOperatorKind,
  isEqualsGreaterThanToken,
  isExclamationToken,
  isExcludedFile,
  isExclusivelyTypeOnlyImportOrExport,
  isExportAssignment,
  isExportDeclaration,
  isExportModifier,
  isExportName,
  isExportNamespaceAsDefaultDeclaration,
  isExportOrDefaultModifier,
  isExportSpecifier,
  isExportsIdentifier,
  isExportsOrModuleExportsOrAlias,
  isExpression,
  isExpressionNode,
  isExpressionOfExternalModuleImportEqualsDeclaration,
  isExpressionOfOptionalChainRoot,
  isExpressionStatement,
  isExpressionWithTypeArguments,
  isExpressionWithTypeArgumentsInClassExtendsClause,
  isExternalModule,
  isExternalModuleAugmentation,
  isExternalModuleImportEqualsDeclaration,
  isExternalModuleIndicator,
  isExternalModuleNameRelative,
  isExternalModuleReference,
  isExternalModuleSymbol,
  isExternalOrCommonJsModule,
  isFileLevelUniqueName,
  isFileProbablyExternalModule,
  isFirstDeclarationOfSymbolParameter,
  isFixablePromiseHandler,
  isForInOrOfStatement,
  isForInStatement,
  isForInitializer,
  isForOfStatement,
  isForStatement,
  isFunctionBlock,
  isFunctionBody,
  isFunctionDeclaration,
  isFunctionExpression,
  isFunctionExpressionOrArrowFunction,
  isFunctionLike,
  isFunctionLikeDeclaration,
  isFunctionLikeKind,
  isFunctionLikeOrClassStaticBlockDeclaration,
  isFunctionOrConstructorTypeNode,
  isFunctionOrModuleBlock,
  isFunctionSymbol,
  isFunctionTypeNode,
  isFutureReservedKeyword,
  isGeneratedIdentifier,
  isGeneratedPrivateIdentifier,
  isGetAccessor,
  isGetAccessorDeclaration,
  isGetOrSetAccessorDeclaration,
  isGlobalDeclaration,
  isGlobalScopeAugmentation,
  isGrammarError,
  isHeritageClause,
  isHoistedFunction,
  isHoistedVariableStatement,
  isIdentifier,
  isIdentifierANonContextualKeyword,
  isIdentifierName,
  isIdentifierOrThisTypeNode,
  isIdentifierPart,
  isIdentifierStart,
  isIdentifierText,
  isIdentifierTypePredicate,
  isIdentifierTypeReference,
  isIfStatement,
  isIgnoredFileFromWildCardWatching,
  isImplicitGlob,
  isImportCall,
  isImportClause,
  isImportDeclaration,
  isImportEqualsDeclaration,
  isImportKeyword,
  isImportMeta,
  isImportOrExportSpecifier,
  isImportOrExportSpecifierName,
  isImportSpecifier,
  isImportTypeAssertionContainer,
  isImportTypeNode,
  isImportableFile,
  isInComment,
  isInExpressionContext,
  isInJSDoc,
  isInJSFile,
  isInJSXText,
  isInJsonFile,
  isInNonReferenceComment,
  isInReferenceComment,
  isInRightSideOfInternalImportEqualsDeclaration,
  isInString,
  isInTemplateString,
  isInTopLevelContext,
  isIncrementalCompilation,
  isIndexSignatureDeclaration,
  isIndexedAccessTypeNode,
  isInferTypeNode,
  isInfinityOrNaNString,
  isInitializedProperty,
  isInitializedVariable,
  isInsideJsxElement,
  isInsideJsxElementOrAttribute,
  isInsideNodeModules,
  isInsideTemplateLiteral,
  isInstantiatedModule,
  isInterfaceDeclaration,
  isInternalDeclaration,
  isInternalModuleImportEqualsDeclaration,
  isInternalName,
  isIntersectionTypeNode,
  isIntrinsicJsxName,
  isIterationStatement,
  isJSDoc,
  isJSDocAllType,
  isJSDocAugmentsTag,
  isJSDocAuthorTag,
  isJSDocCallbackTag,
  isJSDocClassTag,
  isJSDocCommentContainingNode,
  isJSDocConstructSignature,
  isJSDocDeprecatedTag,
  isJSDocEnumTag,
  isJSDocFunctionType,
  isJSDocImplementsTag,
  isJSDocIndexSignature,
  isJSDocLikeText,
  isJSDocLink,
  isJSDocLinkCode,
  isJSDocLinkLike,
  isJSDocLinkPlain,
  isJSDocMemberName,
  isJSDocNameReference,
  isJSDocNamepathType,
  isJSDocNamespaceBody,
  isJSDocNode,
  isJSDocNonNullableType,
  isJSDocNullableType,
  isJSDocOptionalParameter,
  isJSDocOptionalType,
  isJSDocOverloadTag,
  isJSDocOverrideTag,
  isJSDocParameterTag,
  isJSDocPrivateTag,
  isJSDocPropertyLikeTag,
  isJSDocPropertyTag,
  isJSDocProtectedTag,
  isJSDocPublicTag,
  isJSDocReadonlyTag,
  isJSDocReturnTag,
  isJSDocSatisfiesExpression,
  isJSDocSatisfiesTag,
  isJSDocSeeTag,
  isJSDocSignature,
  isJSDocTag,
  isJSDocTemplateTag,
  isJSDocThisTag,
  isJSDocThrowsTag,
  isJSDocTypeAlias,
  isJSDocTypeAssertion,
  isJSDocTypeExpression,
  isJSDocTypeLiteral,
  isJSDocTypeTag,
  isJSDocTypedefTag,
  isJSDocUnknownTag,
  isJSDocUnknownType,
  isJSDocVariadicType,
  isJSXTagName,
  isJsonEqual,
  isJsonSourceFile,
  isJsxAttribute,
  isJsxAttributeLike,
  isJsxAttributeName,
  isJsxAttributes,
  isJsxChild,
  isJsxClosingElement,
  isJsxClosingFragment,
  isJsxElement,
  isJsxExpression,
  isJsxFragment,
  isJsxNamespacedName,
  isJsxOpeningElement,
  isJsxOpeningFragment,
  isJsxOpeningLikeElement,
  isJsxOpeningLikeElementTagName,
  isJsxSelfClosingElement,
  isJsxSpreadAttribute,
  isJsxTagNameExpression,
  isJsxText,
  isJumpStatementTarget,
  isKeyword,
  isKeywordOrPunctuation,
  isKnownSymbol,
  isLabelName,
  isLabelOfLabeledStatement,
  isLabeledStatement,
  isLateVisibilityPaintedStatement,
  isLeftHandSideExpression,
  isLeftHandSideOfAssignment,
  isLet,
  isLineBreak,
  isLiteralComputedPropertyDeclarationName,
  isLiteralExpression,
  isLiteralExpressionOfObject,
  isLiteralImportTypeNode,
  isLiteralKind,
  isLiteralLikeAccess,
  isLiteralLikeElementAccess,
  isLiteralNameOfPropertyDeclarationOrIndexAccess,
  isLiteralTypeLikeExpression,
  isLiteralTypeLiteral,
  isLiteralTypeNode,
  isLocalName,
  isLogicalOperator,
  isLogicalOrCoalescingAssignmentExpression,
  isLogicalOrCoalescingAssignmentOperator,
  isLogicalOrCoalescingBinaryExpression,
  isLogicalOrCoalescingBinaryOperator,
  isMappedTypeNode,
  isMemberName,
  isMetaProperty,
  isMethodDeclaration,
  isMethodOrAccessor,
  isMethodSignature,
  isMinusToken,
  isMissingDeclaration,
  isModifier,
  isModifierKind,
  isModifierLike,
  isModuleAugmentationExternal,
  isModuleBlock,
  isModuleBody,
  isModuleDeclaration,
  isModuleExportsAccessExpression,
  isModuleIdentifier,
  isModuleName,
  isModuleOrEnumDeclaration,
  isModuleReference,
  isModuleSpecifierLike,
  isModuleWithStringLiteralName,
  isNameOfFunctionDeclaration,
  isNameOfModuleDeclaration,
  isNamedClassElement,
  isNamedDeclaration,
  isNamedEvaluation,
  isNamedEvaluationSource,
  isNamedExportBindings,
  isNamedExports,
  isNamedImportBindings,
  isNamedImports,
  isNamedImportsOrExports,
  isNamedTupleMember,
  isNamespaceBody,
  isNamespaceExport,
  isNamespaceExportDeclaration,
  isNamespaceImport,
  isNamespaceReexportDeclaration,
  isNewExpression,
  isNewExpressionTarget,
  isNightly,
  isNoSubstitutionTemplateLiteral,
  isNode,
  isNodeArray,
  isNodeArrayMultiLine,
  isNodeDescendantOf,
  isNodeKind,
  isNodeLikeSystem,
  isNodeModulesDirectory,
  isNodeWithPossibleHoistedDeclaration,
  isNonContextualKeyword,
  isNonExportDefaultModifier,
  isNonGlobalAmbientModule,
  isNonGlobalDeclaration,
  isNonNullAccess,
  isNonNullChain,
  isNonNullExpression,
  isNonStaticMethodOrAccessorWithPrivateName,
  isNotEmittedOrPartiallyEmittedNode,
  isNotEmittedStatement,
  isNullishCoalesce,
  isNumber,
  isNumericLiteral,
  isNumericLiteralName,
  isObjectBindingElementWithoutPropertyName,
  isObjectBindingOrAssignmentElement,
  isObjectBindingOrAssignmentPattern,
  isObjectBindingPattern,
  isObjectLiteralElement,
  isObjectLiteralElementLike,
  isObjectLiteralExpression,
  isObjectLiteralMethod,
  isObjectLiteralOrClassExpressionMethodOrAccessor,
  isObjectTypeDeclaration,
  isOctalDigit,
  isOmittedExpression,
  isOptionalChain,
  isOptionalChainRoot,
  isOptionalDeclaration,
  isOptionalJSDocPropertyLikeTag,
  isOptionalTypeNode,
  isOuterExpression,
  isOutermostOptionalChain,
  isOverrideModifier,
  isPackedArrayLiteral,
  isParameter,
  isParameterDeclaration,
  isParameterOrCatchClauseVariable,
  isParameterPropertyDeclaration,
  isParameterPropertyModifier,
  isParenthesizedExpression,
  isParenthesizedTypeNode,
  isParseTreeNode,
  isPartOfTypeNode,
  isPartOfTypeQuery,
  isPartiallyEmittedExpression,
  isPatternMatch,
  isPinnedComment,
  isPlainJsFile,
  isPlusToken,
  isPossiblyTypeArgumentPosition,
  isPostfixUnaryExpression,
  isPrefixUnaryExpression,
  isPrivateIdentifier,
  isPrivateIdentifierClassElementDeclaration,
  isPrivateIdentifierPropertyAccessExpression,
  isPrivateIdentifierSymbol,
  isProgramBundleEmitBuildInfo,
  isProgramUptoDate,
  isPrologueDirective,
  isPropertyAccessChain,
  isPropertyAccessEntityNameExpression,
  isPropertyAccessExpression,
  isPropertyAccessOrQualifiedName,
  isPropertyAccessOrQualifiedNameOrImportTypeNode,
  isPropertyAssignment,
  isPropertyDeclaration,
  isPropertyName,
  isPropertyNameLiteral,
  isPropertySignature,
  isProtoSetter,
  isPrototypeAccess,
  isPrototypePropertyAssignment,
  isPunctuation,
  isPushOrUnshiftIdentifier,
  isQualifiedName,
  isQuestionDotToken,
  isQuestionOrExclamationToken,
  isQuestionOrPlusOrMinusToken,
  isQuestionToken,
  isRawSourceMap,
  isReadonlyKeyword,
  isReadonlyKeywordOrPlusOrMinusToken,
  isRecognizedTripleSlashComment,
  isReferenceFileLocation,
  isReferencedFile,
  isRegularExpressionLiteral,
  isRequireCall,
  isRequireVariableStatement,
  isRestParameter,
  isRestTypeNode,
  isReturnStatement,
  isReturnStatementWithFixablePromiseHandler,
  isRightSideOfAccessExpression,
  isRightSideOfPropertyAccess,
  isRightSideOfQualifiedName,
  isRightSideOfQualifiedNameOrPropertyAccess,
  isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName,
  isRootedDiskPath,
  isSameEntityName,
  isSatisfiesExpression,
  isScopeMarker,
  isSemicolonClassElement,
  isSetAccessor,
  isSetAccessorDeclaration,
  isShebangTrivia,
  isShorthandAmbientModuleSymbol,
  isShorthandPropertyAssignment,
  isSignedNumericLiteral,
  isSimpleCopiableExpression,
  isSimpleInlineableExpression,
  isSingleOrDoubleQuote,
  isSourceFile,
  isSourceFileFromLibrary,
  isSourceFileJS,
  isSourceFileNotJS,
  isSourceFileNotJson,
  isSourceMapping,
  isSpecialPropertyDeclaration,
  isSpreadAssignment,
  isSpreadElement,
  isStatement,
  isStatementButNotDeclaration,
  isStatementOrBlock,
  isStatementWithLocals,
  isStatic,
  isStaticModifier,
  isString,
  isStringAKeyword,
  isStringANonContextualKeyword,
  isStringAndEmptyAnonymousObjectIntersection,
  isStringDoubleQuoted,
  isStringLiteral,
  isStringLiteralLike,
  isStringLiteralOrJsxExpression,
  isStringLiteralOrTemplate,
  isStringOrNumericLiteralLike,
  isStringOrRegularExpressionOrTemplateLiteral,
  isStringTextContainingNode,
  isSuperCall,
  isSuperKeyword,
  isSuperOrSuperProperty,
  isSuperProperty,
  isSupportedSourceFileName,
  isSwitchStatement,
  isSyntaxList,
  isSyntheticExpression,
  isSyntheticReference,
  isTagName,
  isTaggedTemplateExpression,
  isTaggedTemplateTag,
  isTemplateExpression,
  isTemplateHead,
  isTemplateLiteral,
  isTemplateLiteralKind,
  isTemplateLiteralToken,
  isTemplateLiteralTypeNode,
  isTemplateLiteralTypeSpan,
  isTemplateMiddle,
  isTemplateMiddleOrTemplateTail,
  isTemplateSpan,
  isTemplateTail,
  isTextWhiteSpaceLike,
  isThis,
  isThisContainerOrFunctionBlock,
  isThisIdentifier,
  isThisInTypeQuery,
  isThisInitializedDeclaration,
  isThisInitializedObjectBindingExpression,
  isThisProperty,
  isThisTypeNode,
  isThisTypeParameter,
  isThisTypePredicate,
  isThrowStatement,
  isToken,
  isTokenKind,
  isTraceEnabled,
  isTransientSymbol,
  isTrivia,
  isTryStatement,
  isTupleTypeNode,
  isTypeAlias,
  isTypeAliasDeclaration,
  isTypeAssertionExpression,
  isTypeDeclaration,
  isTypeElement,
  isTypeKeyword,
  isTypeKeywordToken,
  isTypeKeywordTokenOrIdentifier,
  isTypeLiteralNode,
  isTypeNode,
  isTypeNodeKind,
  isTypeOfExpression,
  isTypeOnlyExportDeclaration,
  isTypeOnlyImportDeclaration,
  isTypeOnlyImportOrExportDeclaration,
  isTypeOperatorNode,
  isTypeParameterDeclaration,
  isTypePredicateNode,
  isTypeQueryNode,
  isTypeReferenceNode,
  isTypeReferenceType,
  isUMDExportSymbol,
  isUnaryExpression,
  isUnaryExpressionWithWrite,
  isUnicodeIdentifierStart,
  isUnionTypeNode,
  isUnparsedNode,
  isUnparsedPrepend,
  isUnparsedSource,
  isUnparsedTextLike,
  isUrl,
  isValidBigIntString,
  isValidESSymbolDeclaration,
  isValidTypeOnlyAliasUseSite,
  isValueSignatureDeclaration,
  isVarConst,
  isVariableDeclaration,
  isVariableDeclarationInVariableStatement,
  isVariableDeclarationInitializedToBareOrAccessedRequire,
  isVariableDeclarationInitializedToRequire,
  isVariableDeclarationList,
  isVariableLike,
  isVariableLikeOrAccessor,
  isVariableStatement,
  isVoidExpression,
  isWatchSet,
  isWhileStatement,
  isWhiteSpaceLike,
  isWhiteSpaceSingleLine,
  isWithStatement,
  isWriteAccess,
  isWriteOnlyAccess,
  isYieldExpression,
  jsxModeNeedsExplicitImport,
  keywordPart,
  last,
  lastOrUndefined,
  length,
  libMap,
  libs,
  lineBreakPart,
  linkNamePart,
  linkPart,
  linkTextPart,
  listFiles,
  loadModuleFromGlobalCache,
  loadWithModeAwareCache,
  makeIdentifierFromModuleName,
  makeImport,
  makeImportIfNecessary,
  makeStringLiteral,
  mangleScopedPackageName,
  map,
  mapAllOrFail,
  mapDefined,
  mapDefinedEntries,
  mapDefinedIterator,
  mapEntries,
  mapIterator,
  mapOneOrMany,
  mapToDisplayParts,
  matchFiles,
  matchPatternOrExact,
  matchedText,
  matchesExclude,
  maybeBind,
  maybeSetLocalizedDiagnosticMessages,
  memoize,
  memoizeCached,
  memoizeOne,
  memoizeWeak,
  metadataHelper,
  min,
  minAndMax,
  missingFileModifiedTime,
  modifierToFlag,
  modifiersToFlags,
  moduleOptionDeclaration,
  moduleResolutionIsEqualTo,
  moduleResolutionNameAndModeGetter,
  moduleResolutionOptionDeclarations,
  moduleResolutionSupportsPackageJsonExportsAndImports,
  moduleResolutionUsesNodeModules,
  moduleSpecifiers,
  moveEmitHelpers,
  moveRangeEnd,
  moveRangePastDecorators,
  moveRangePastModifiers,
  moveRangePos,
  moveSyntheticComments,
  mutateMap,
  mutateMapSkippingNewValues,
  needsParentheses,
  needsScopeMarker,
  newCaseClauseTracker,
  newPrivateEnvironment,
  noEmitNotification,
  noEmitSubstitution,
  noTransformers,
  noTruncationMaximumTruncationLength,
  nodeCanBeDecorated,
  nodeHasName,
  nodeIsDecorated,
  nodeIsMissing,
  nodeIsPresent,
  nodeIsSynthesized,
  nodeModuleNameResolver,
  nodeModulesPathPart,
  nodeNextJsonConfigResolver,
  nodeOrChildIsDecorated,
  nodeOverlapsWithStartEnd,
  nodePosToString,
  nodeSeenTracker,
  nodeStartsNewLexicalEnvironment,
  nodeToDisplayParts,
  noop,
  noopFileWatcher,
  normalizePath,
  normalizeSlashes,
  not,
  notImplemented,
  notImplementedResolver,
  nullNodeConverters,
  nullParenthesizerRules,
  nullTransformationContext,
  objectAllocator,
  operatorPart,
  optionDeclarations,
  optionMapToObject,
  optionsAffectingProgramStructure,
  optionsForBuild,
  optionsForWatch,
  optionsHaveChanges,
  optionsHaveModuleResolutionChanges,
  or,
  orderedRemoveItem,
  orderedRemoveItemAt,
  outFile,
  packageIdToPackageName,
  packageIdToString,
  padLeft,
  padRight,
  paramHelper,
  parameterIsThisKeyword,
  parameterNamePart,
  parseBaseNodeFactory,
  parseBigInt,
  parseBuildCommand,
  parseCommandLine,
  parseCommandLineWorker,
  parseConfigFileTextToJson,
  parseConfigFileWithSystem,
  parseConfigHostFromCompilerHostLike,
  parseCustomTypeOption,
  parseIsolatedEntityName,
  parseIsolatedJSDocComment,
  parseJSDocTypeExpressionForTests,
  parseJsonConfigFileContent,
  parseJsonSourceFileConfigFileContent,
  parseJsonText,
  parseListTypeOption,
  parseNodeFactory,
  parseNodeModuleFromPath,
  parsePackageName,
  parsePseudoBigInt,
  parseValidBigInt,
  patchWriteFileEnsuringDirectory,
  pathContainsNodeModules,
  pathIsAbsolute,
  pathIsBareSpecifier,
  pathIsRelative,
  patternText,
  perfLogger,
  performIncrementalCompilation,
  performance,
  plainJSErrors,
  positionBelongsToNode,
  positionIsASICandidate,
  positionIsSynthesized,
  positionsAreOnSameLine,
  preProcessFile,
  probablyUsesSemicolons,
  processCommentPragmas,
  processPragmasIntoFields,
  processTaggedTemplateExpression,
  programContainsEsModules,
  programContainsModules,
  projectReferenceIsEqualTo,
  propKeyHelper,
  propertyNamePart,
  pseudoBigIntToString,
  punctuationPart,
  pushIfUnique,
  quote,
  quotePreferenceFromString,
  rangeContainsPosition,
  rangeContainsPositionExclusive,
  rangeContainsRange,
  rangeContainsRangeExclusive,
  rangeContainsStartEnd,
  rangeEndIsOnSameLineAsRangeStart,
  rangeEndPositionsAreOnSameLine,
  rangeEquals,
  rangeIsOnSingleLine,
  rangeOfNode,
  rangeOfTypeParameters,
  rangeOverlapsWithStartEnd,
  rangeStartIsOnSameLineAsRangeEnd,
  rangeStartPositionsAreOnSameLine,
  readBuilderProgram,
  readConfigFile,
  readHelper,
  readJson,
  readJsonConfigFile,
  readJsonOrUndefined,
  realizeDiagnostics,
  reduceEachLeadingCommentRange,
  reduceEachTrailingCommentRange,
  reduceLeft,
  reduceLeftIterator,
  reducePathComponents,
  refactor,
  regExpEscape,
  relativeComplement,
  removeAllComments,
  removeEmitHelper,
  removeExtension,
  removeFileExtension,
  removeIgnoredPath,
  removeMinAndVersionNumbers,
  removeOptionality,
  removePrefix,
  removeSuffix,
  removeTrailingDirectorySeparator,
  repeatString,
  replaceElement,
  resolutionExtensionIsTSOrJson,
  resolveConfigFileProjectName,
  resolveJSModule,
  resolveLibrary,
  resolveModuleName,
  resolveModuleNameFromCache,
  resolvePackageNameToPackageJson,
  resolvePath,
  resolveProjectReferencePath,
  resolveTripleslashReference,
  resolveTypeReferenceDirective,
  resolvingEmptyArray,
  restHelper,
  returnFalse,
  returnNoopFileWatcher,
  returnTrue,
  returnUndefined,
  returnsPromise,
  runInitializersHelper,
  sameFlatMap,
  sameMap,
  sameMapping,
  scanShebangTrivia,
  scanTokenAtPosition,
  scanner,
  screenStartingMessageCodes,
  semanticDiagnosticsOptionDeclarations,
  serializeCompilerOptions,
  server,
  servicesVersion,
  setCommentRange,
  setConfigFileInOptions,
  setConstantValue,
  setEachParent,
  setEmitFlags,
  setFunctionNameHelper,
  setGetSourceFileAsHashVersioned,
  setIdentifierAutoGenerate,
  setIdentifierGeneratedImportReference,
  setIdentifierTypeArguments,
  setInternalEmitFlags,
  setLocalizedDiagnosticMessages,
  setModuleDefaultHelper,
  setNodeFlags,
  setObjectAllocator,
  setOriginalNode,
  setParent,
  setParentRecursive,
  setPrivateIdentifier,
  setResolvedModule,
  setResolvedTypeReferenceDirective,
  setSnippetElement,
  setSourceMapRange,
  setStackTraceLimit,
  setStartsOnNewLine,
  setSyntheticLeadingComments,
  setSyntheticTrailingComments,
  setSys,
  setSysLog,
  setTextRange,
  setTextRangeEnd,
  setTextRangePos,
  setTextRangePosEnd,
  setTextRangePosWidth,
  setTokenSourceMapRange,
  setTypeNode,
  setUILocale,
  setValueDeclaration,
  shouldAllowImportingTsExtension,
  shouldPreserveConstEnums,
  shouldResolveJsRequire,
  shouldUseUriStyleNodeCoreModules,
  showModuleSpecifier,
  signatureHasLiteralTypes,
  signatureHasRestParameter,
  signatureToDisplayParts,
  single,
  singleElementArray,
  singleIterator,
  singleOrMany,
  singleOrUndefined,
  skipAlias,
  skipAssertions,
  skipConstraint,
  skipOuterExpressions,
  skipParentheses,
  skipPartiallyEmittedExpressions,
  skipTrivia,
  skipTypeChecking,
  skipTypeParentheses,
  skipWhile,
  sliceAfter,
  some,
  sort,
  sortAndDeduplicate,
  sortAndDeduplicateDiagnostics,
  sourceFileAffectingCompilerOptions,
  sourceFileMayBeEmitted,
  sourceMapCommentRegExp,
  sourceMapCommentRegExpDontCareLineStart,
  spacePart,
  spanMap,
  spreadArrayHelper,
  stableSort,
  startEndContainsRange,
  startEndOverlapsWithStartEnd,
  startOnNewLine,
  startTracing,
  startsWith,
  startsWithDirectory,
  startsWithUnderscore,
  startsWithUseStrict,
  stringContains,
  stringContainsAt,
  stringToToken,
  stripQuotes,
  supportedDeclarationExtensions,
  supportedJSExtensions,
  supportedJSExtensionsFlat,
  supportedLocaleDirectories,
  supportedTSExtensions,
  supportedTSExtensionsFlat,
  supportedTSImplementationExtensions,
  suppressLeadingAndTrailingTrivia,
  suppressLeadingTrivia,
  suppressTrailingTrivia,
  symbolEscapedNameNoDefault,
  symbolName,
  symbolNameNoDefault,
  symbolPart,
  symbolToDisplayParts,
  syntaxMayBeASICandidate,
  syntaxRequiresTrailingSemicolonOrASI,
  sys,
  sysLog,
  tagNamesAreEquivalent,
  takeWhile,
  targetOptionDeclaration,
  templateObjectHelper,
  testFormatSettings,
  textChangeRangeIsUnchanged,
  textChangeRangeNewSpan,
  textChanges,
  textOrKeywordPart,
  textPart,
  textRangeContainsPositionInclusive,
  textSpanContainsPosition,
  textSpanContainsTextSpan,
  textSpanEnd,
  textSpanIntersection,
  textSpanIntersectsWith,
  textSpanIntersectsWithPosition,
  textSpanIntersectsWithTextSpan,
  textSpanIsEmpty,
  textSpanOverlap,
  textSpanOverlapsWith,
  textSpansEqual,
  textToKeywordObj,
  timestamp,
  toArray,
  toBuilderFileEmit,
  toBuilderStateFileInfoForMultiEmit,
  toEditorSettings,
  toFileNameLowerCase,
  toLowerCase,
  toPath,
  toProgramEmitPending,
  tokenIsIdentifierOrKeyword,
  tokenIsIdentifierOrKeywordOrGreaterThan,
  tokenToString,
  trace,
  tracing,
  tracingEnabled,
  transform,
  transformClassFields,
  transformDeclarations,
  transformECMAScriptModule,
  transformES2015,
  transformES2016,
  transformES2017,
  transformES2018,
  transformES2019,
  transformES2020,
  transformES2021,
  transformES5,
  transformESDecorators,
  transformESNext,
  transformGenerators,
  transformJsx,
  transformLegacyDecorators,
  transformModule,
  transformNodeModule,
  transformNodes,
  transformSystemModule,
  transformTypeScript,
  transpile,
  transpileModule,
  transpileOptionValueCompilerOptions,
  trimString,
  trimStringEnd,
  trimStringStart,
  tryAddToSet,
  tryAndIgnoreErrors,
  tryCast,
  tryDirectoryExists,
  tryExtractTSExtension,
  tryFileExists,
  tryGetClassExtendingExpressionWithTypeArguments,
  tryGetClassImplementingOrExtendingExpressionWithTypeArguments,
  tryGetDirectories,
  tryGetExtensionFromPath,
  tryGetImportFromModuleSpecifier,
  tryGetJSDocSatisfiesTypeNode,
  tryGetModuleNameFromFile,
  tryGetModuleSpecifierFromDeclaration,
  tryGetNativePerformanceHooks,
  tryGetPropertyAccessOrIdentifierToString,
  tryGetPropertyNameOfBindingOrAssignmentElement,
  tryGetSourceMappingURL,
  tryGetTextOfPropertyName,
  tryIOAndConsumeErrors,
  tryParsePattern,
  tryParsePatterns,
  tryParseRawSourceMap,
  tryReadDirectory,
  tryReadFile,
  tryRemoveDirectoryPrefix,
  tryRemoveExtension,
  tryRemovePrefix,
  tryRemoveSuffix,
  typeAcquisitionDeclarations,
  typeAliasNamePart,
  typeDirectiveIsEqualTo,
  typeKeywords,
  typeParameterNamePart,
  typeReferenceResolutionNameAndModeGetter,
  typeToDisplayParts,
  unchangedPollThresholds,
  unchangedTextChangeRange,
  unescapeLeadingUnderscores,
  unmangleScopedPackageName,
  unorderedRemoveItem,
  unorderedRemoveItemAt,
  unreachableCodeIsError,
  unusedLabelIsError,
  unwrapInnermostStatementOfLabel,
  updateErrorForNoInputFiles,
  updateLanguageServiceSourceFile,
  updateMissingFilePathsWatch,
  updatePackageJsonWatch,
  updateResolutionField,
  updateSharedExtendedConfigFileWatcher,
  updateSourceFile,
  updateWatchingWildcardDirectories,
  usesExtensionsOnImports,
  usingSingleLineStringWriter,
  utf16EncodeAsString,
  validateLocaleAndSetLanguage,
  valuesHelper,
  version,
  versionMajorMinor,
  visitArray,
  visitCommaListElements,
  visitEachChild,
  visitFunctionBody,
  visitIterationBody,
  visitLexicalEnvironment,
  visitNode,
  visitNodes,
  visitParameterList,
  walkUpBindingElementsAndPatterns,
  walkUpLexicalEnvironments,
  walkUpOuterExpressions,
  walkUpParenthesizedExpressions,
  walkUpParenthesizedTypes,
  walkUpParenthesizedTypesAndGetParentAndChild,
  whitespaceOrMapCommentRegExp,
  writeCommentRange,
  writeFile,
  writeFileEnsuringDirectories,
  zipToModeAwareCache,
  zipWith
});
//# sourceMappingURL=tsserver.js.map
