(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
  }
  function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
    const unusedImports = /* @__PURE__ */ new Map();
    const unusedDestructures = /* @__PURE__ */ new Map();
    const unusedVariables = /* @__PURE__ */ new Map();
    nodeWithLocals.locals.forEach((local) => {
      if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
        return;
      }
      if (local.declarations) {
        for (const declaration of local.declarations) {
          if (isValidUnusedLocalDeclaration(declaration)) {
            continue;
          }
          if (isImportedDeclaration(declaration)) {
            addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
          } else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) {
            const lastElement = last(declaration.parent.elements);
            if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) {
              addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
            }
          } else if (isVariableDeclaration(declaration)) {
            const blockScopeKind = getCombinedNodeFlagsCached(declaration) & 7 /* BlockScoped */;
            const name = getNameOfDeclaration(declaration);
            if (blockScopeKind !== 4 /* Using */ && blockScopeKind !== 6 /* AwaitUsing */ || !name || !isIdentifierThatStartsWithUnderscore(name)) {
              addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
            }
          } else {
            const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
            const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration);
            if (parameter && name) {
              if (!isParameterPropertyDeclaration(parameter, parameter.parent) && !parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
                if (isBindingElement(declaration) && isArrayBindingPattern(declaration.parent)) {
                  addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
                } else {
                  addDiagnostic(parameter, 1 /* Parameter */, createDiagnosticForNode(name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(local)));
                }
              }
            } else {
              errorUnusedLocal(declaration, symbolName(local), addDiagnostic);
            }
          }
        }
      }
    });
    unusedImports.forEach(([importClause, unuseds]) => {
      const importDecl = importClause.parent;
      const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 274 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0);
      if (nDeclarations === unuseds.length) {
        addDiagnostic(
          importDecl,
          0 /* Local */,
          unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)
        );
      } else {
        for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic);
      }
    });
    unusedDestructures.forEach(([bindingPattern, bindingElements]) => {
      const kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
      if (bindingPattern.elements.length === bindingElements.length) {
        if (bindingElements.length === 1 && bindingPattern.parent.kind === 260 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 261 /* VariableDeclarationList */) {
          addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
        } else {
          addDiagnostic(
            bindingPattern,
            kind,
            bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)
          );
        }
      } else {
        for (const e of bindingElements) {
          addDiagnostic(e, kind, createDiagnosticForNode(e, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
        }
      }
    });
    unusedVariables.forEach(([declarationList, declarations]) => {
      if (declarationList.declarations.length === declarations.length) {
        addDiagnostic(
          declarationList,
          0 /* Local */,
          declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)
        );
      } else {
        for (const decl of declarations) {
          addDiagnostic(decl, 0 /* Local */, createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
        }
      }
    });
  }
  function checkPotentialUncheckedRenamedBindingElementsInTypes() {
    var _a;
    for (const node of potentialUnusedRenamedBindingElementsInTypes) {
      if (!((_a = getSymbolOfDeclaration(node)) == null ? void 0 : _a.isReferenced)) {
        const wrappingDeclaration = walkUpBindingElementsAndPatterns(node);
        Debug.assert(isPartOfParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here");
        const diagnostic = createDiagnosticForNode(node.name, Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, declarationNameToString(node.name), declarationNameToString(node.propertyName));
        if (!wrappingDeclaration.type) {
          addRelatedInfo(
            diagnostic,
            createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 0, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName))
          );
        }
        diagnostics.add(diagnostic);
      }
    }
  }
  function bindingNameText(name) {
    switch (name.kind) {
      case 80 /* Identifier */:
        return idText(name);
      case 207 /* ArrayBindingPattern */:
      case 206 /* ObjectBindingPattern */:
        return bindingNameText(cast(first(name.elements), isBindingElement).name);
      default:
        return Debug.assertNever(name);
    }
  }
  function isImportedDeclaration(node) {
    return node.kind === 273 /* ImportClause */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 274 /* NamespaceImport */;
  }
  function importClauseFromImported(decl) {
    return decl.kind === 273 /* ImportClause */ ? decl : decl.kind === 274 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
  }
  function checkBlock(node) {
    if (node.kind === 241 /* Block */) {
      checkGrammarStatementInAmbientContext(node);
    }
    if (isFunctionOrModuleBlock(node)) {
      const saveFlowAnalysisDisabled = flowAnalysisDisabled;
      forEach(node.statements, checkSourceElement);
      flowAnalysisDisabled = saveFlowAnalysisDisabled;
    } else {
      forEach(node.statements, checkSourceElement);
    }
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkCollisionWithArgumentsInGeneratedCode(node) {
    if (languageVersion >= 2 /* ES2015 */ || !hasRestParameter(node) || node.flags & 33554432 /* Ambient */ || nodeIsMissing(node.body)) {
      return;
    }
    forEach(node.parameters, (p) => {
      if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
        errorSkippedOn("noEmit", p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
      }
    });
  }
  function needCollisionCheckForIdentifier(node, identifier, name) {
    if ((identifier == null ? void 0 : identifier.escapedText) !== name) {
      return false;
    }
    if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ || node.kind === 303 /* PropertyAssignment */) {
      return false;
    }
    if (node.flags & 33554432 /* Ambient */) {
      return false;
    }
    if (isImportClause(node) || isImportEqualsDeclaration(node) || isImportSpecifier(node)) {
      if (isTypeOnlyImportOrExportDeclaration(node)) {
        return false;
      }
    }
    const root = getRootDeclaration(node);
    if (isParameter(root) && nodeIsMissing(root.parent.body)) {
      return false;
    }
    return true;
  }
  function checkIfThisIsCapturedInEnclosingScope(node) {
    findAncestor(node, (current) => {
      if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
        const isDeclaration2 = node.kind !== 80 /* Identifier */;
        if (isDeclaration2) {
          error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
        } else {
          error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
        }
        return true;
      }
      return false;
    });
  }
  function checkIfNewTargetIsCapturedInEnclosingScope(node) {
    findAncestor(node, (current) => {
      if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
        const isDeclaration2 = node.kind !== 80 /* Identifier */;
        if (isDeclaration2) {
          error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
        } else {
          error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
        }
        return true;
      }
      return false;
    });
  }
  function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
    if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) >= 5 /* ES2015 */) {
      return;
    }
    if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
      return;
    }
    if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */) {
      return;
    }
    const parent = getDeclarationContainer(node);
    if (parent.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(parent)) {
      errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name));
    }
  }
  function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
    if (!name || languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
      return;
    }
    if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */) {
      return;
    }
    const parent = getDeclarationContainer(node);
    if (parent.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(parent) && parent.flags & 4096 /* HasAsyncFunctions */) {
      errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name));
    }
  }
  function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) {
    if (languageVersion <= 8 /* ES2021 */ && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) {
      potentialWeakMapSetCollisions.push(node);
    }
  }
  function checkWeakMapSetCollision(node) {
    const enclosingBlockScope = getEnclosingBlockScopeContainer(node);
    if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) {
      Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier");
      errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText);
    }
  }
  function recordPotentialCollisionWithReflectInGeneratedCode(node, name) {
    if (name && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && needCollisionCheckForIdentifier(node, name, "Reflect")) {
      potentialReflectCollisions.push(node);
    }
  }
  function checkReflectCollision(node) {
    let hasCollision = false;
    if (isClassExpression(node)) {
      for (const member of node.members) {
        if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) {
          hasCollision = true;
          break;
        }
      }
    } else if (isFunctionExpression(node)) {
      if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) {
        hasCollision = true;
      }
    } else {
      const container = getEnclosingBlockScopeContainer(node);
      if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) {
        hasCollision = true;
      }
    }
    if (hasCollision) {
      Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier");
      errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, declarationNameToString(node.name), "Reflect");
    }
  }
  function checkCollisionsForDeclarationName(node, name) {
    if (!name) return;
    checkCollisionWithRequireExportsInGeneratedCode(node, name);
    checkCollisionWithGlobalPromiseInGeneratedCode(node, name);
    recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name);
    recordPotentialCollisionWithReflectInGeneratedCode(node, name);
    if (isClassLike(node)) {
      checkTypeNameIsReserved(name, Diagnostics.Class_name_cannot_be_0);
      if (!(node.flags & 33554432 /* Ambient */)) {
        checkClassNameCollisionWithObject(name);
      }
    } else if (isEnumDeclaration(node)) {
      checkTypeNameIsReserved(name, Diagnostics.Enum_name_cannot_be_0);
    }
  }
  function checkVarDeclaredNamesNotShadowed(node) {
    if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isPartOfParameterDeclaration(node)) {
      return;
    }
    const symbol = getSymbolOfDeclaration(node);
    if (symbol.flags & 1 /* FunctionScopedVariable */) {
      if (!isIdentifier(node.name)) return Debug.fail();
      const localDeclarationSymbol = resolveName(
        node,
        node.name.escapedText,
        3 /* Variable */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
      if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
        if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 7 /* BlockScoped */) {
          const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, 261 /* VariableDeclarationList */);
          const container = varDeclList.parent.kind === 243 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : void 0;
          const namesShareScope = container && (container.kind === 241 /* Block */ && isFunctionLike(container.parent) || container.kind === 268 /* ModuleBlock */ || container.kind === 267 /* ModuleDeclaration */ || container.kind === 307 /* SourceFile */);
          if (!namesShareScope) {
            const name = symbolToString(localDeclarationSymbol);
            error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
          }
        }
      }
    }
  }
  function convertAutoToAny(type) {
    return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
  }
  function checkVariableLikeDeclaration(node) {
    var _a;
    checkDecorators(node);
    if (!isBindingElement(node)) {
      checkSourceElement(node.type);
    }
    if (!node.name) {
      return;
    }
    if (node.name.kind === 167 /* ComputedPropertyName */) {
      checkComputedPropertyName(node.name);
      if (hasOnlyExpressionInitializer(node) && node.initializer) {
        checkExpressionCached(node.initializer);
      }
    }
    if (isBindingElement(node)) {
      if (node.propertyName && isIdentifier(node.name) && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) {
        potentialUnusedRenamedBindingElementsInTypes.push(node);
        return;
      }
      if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) {
        checkExternalEmitHelpers(node, 4 /* Rest */);
      }
      if (node.propertyName && node.propertyName.kind === 167 /* ComputedPropertyName */) {
        checkComputedPropertyName(node.propertyName);
      }
      const parent = node.parent.parent;
      const parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */;
      const parentType = getTypeForBindingElementParent(parent, parentCheckMode);
      const name = node.propertyName || node.name;
      if (parentType && !isBindingPattern(name)) {
        const exprType = getLiteralTypeFromPropertyName(name);
        if (isTypeUsableAsPropertyName(exprType)) {
          const nameText = getPropertyNameFromType(exprType);
          const property = getPropertyOfType(parentType, nameText);
          if (property) {
            markPropertyAsReferenced(
              property,
              /*nodeForCheckWriteOnly*/
              void 0,
              /*isSelfTypeAccess*/
              false
            );
            checkPropertyAccessibility(
              node,
              !!parent.initializer && parent.initializer.kind === 108 /* SuperKeyword */,
              /*writing*/
              false,
              parentType,
              property
            );
          }
        }
      }
    }
    if (isBindingPattern(node.name)) {
      if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < LanguageFeatureMinimumTarget.BindingPatterns && compilerOptions.downlevelIteration) {
        checkExternalEmitHelpers(node, 512 /* Read */);
      }
      forEach(node.name.elements, checkSourceElement);
    }
    if (node.initializer && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) {
      error(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
      return;
    }
    if (isBindingPattern(node.name)) {
      if (isInAmbientOrTypeNode(node)) {
        return;
      }
      const needCheckInitializer = hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 249 /* ForInStatement */;
      const needCheckWidenedType = !some(node.name.elements, not(isOmittedExpression));
      if (needCheckInitializer || needCheckWidenedType) {
        const widenedType = getWidenedTypeForVariableLikeDeclaration(node);
        if (needCheckInitializer) {
          const initializerType = checkExpressionCached(node.initializer);
          if (strictNullChecks && needCheckWidenedType) {
            checkNonNullNonVoidType(initializerType, node);
          } else {
            checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
          }
        }
        if (needCheckWidenedType) {
          if (isArrayBindingPattern(node.name)) {
            checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
          } else if (strictNullChecks) {
            checkNonNullNonVoidType(widenedType, node);
          }
        }
      }
      return;
    }
    const symbol = getSymbolOfDeclaration(node);
    if (symbol.flags & 2097152 /* Alias */ && (isVariableDeclarationInitializedToBareOrAccessedRequire(node) || isBindingElementOfBareOrAccessedRequire(node))) {
      checkAliasSymbol(node);
      return;
    }
    if (node.name.kind === 10 /* BigIntLiteral */) {
      error(node.name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name);
    }
    const type = convertAutoToAny(getTypeOfSymbol(symbol));
    if (node === symbol.valueDeclaration) {
      const initializer = hasOnlyExpressionInitializer(node) && getEffectiveInitializer(node);
      if (initializer) {
        const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!((_a = symbol.exports) == null ? void 0 : _a.size);
        if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 249 /* ForInStatement */) {
          const initializerType = checkExpressionCached(initializer);
          checkTypeAssignableToAndOptionallyElaborate(
            initializerType,
            type,
            node,
            initializer,
            /*headMessage*/
            void 0
          );
          const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */;
          if (blockScopeKind === 6 /* AwaitUsing */) {
            const globalAsyncDisposableType = getGlobalAsyncDisposableType(
              /*reportErrors*/
              true
            );
            const globalDisposableType = getGlobalDisposableType(
              /*reportErrors*/
              true
            );
            if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) {
              const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]);
              checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined);
            }
          } else if (blockScopeKind === 4 /* Using */) {
            const globalDisposableType = getGlobalDisposableType(
              /*reportErrors*/
              true
            );
            if (globalDisposableType !== emptyObjectType) {
              const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]);
              checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined);
            }
          }
        }
      }
      if (symbol.declarations && symbol.declarations.length > 1) {
        if (some(symbol.declarations, (d) => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) {
          error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name));
        }
      }
    } else {
      const declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
      if (!isErrorType(type) && !isErrorType(declarationType) && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* Assignment */)) {
        errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
      }
      if (hasOnlyExpressionInitializer(node) && node.initializer) {
        checkTypeAssignableToAndOptionallyElaborate(
          checkExpressionCached(node.initializer),
          declarationType,
          node,
          node.initializer,
          /*headMessage*/
          void 0
        );
      }
      if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
        error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name));
      }
    }
    if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */) {
      checkExportsOnMergedDeclarations(node);
      if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */) {
        checkVarDeclaredNamesNotShadowed(node);
      }
      checkCollisionsForDeclarationName(node, node.name);
    }
  }
  function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
    const nextDeclarationName = getNameOfDeclaration(nextDeclaration);
    const message = nextDeclaration.kind === 172 /* PropertyDeclaration */ || nextDeclaration.kind === 171 /* PropertySignature */ ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
    const declName = declarationNameToString(nextDeclarationName);
    const err = error(
      nextDeclarationName,
      message,
      declName,
      typeToString(firstType),
      typeToString(nextType)
    );
    if (firstDeclaration) {
      addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName));
    }
  }
  function areDeclarationFlagsIdentical(left, right) {
    if (left.kind === 169 /* Parameter */ && right.kind === 260 /* VariableDeclaration */ || left.kind === 260 /* VariableDeclaration */ && right.kind === 169 /* Parameter */) {
      return true;
    }
    if (hasQuestionToken(left) !== hasQuestionToken(right)) {
      return false;
    }
    const interestingFlags = 2 /* Private */ | 4 /* Protected */ | 1024 /* Async */ | 64 /* Abstract */ | 8 /* Readonly */ | 256 /* Static */;
    return getSelectedEffectiveModifierFlags(left, interestingFlags) === getSelectedEffectiveModifierFlags(right, interestingFlags);
  }
  function checkVariableDeclaration(node) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    checkGrammarVariableDeclaration(node);
    checkVariableLikeDeclaration(node);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  function checkBindingElement(node) {
    checkGrammarBindingElement(node);
    return checkVariableLikeDeclaration(node);
  }
  function checkVariableDeclarationList(node) {
    const blockScopeKind = getCombinedNodeFlags(node) & 7 /* BlockScoped */;
    if ((blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */) && languageVersion < LanguageFeatureMinimumTarget.UsingAndAwaitUsing) {
      checkExternalEmitHelpers(node, 16777216 /* AddDisposableResourceAndDisposeResources */);
    }
    forEach(node.declarations, checkSourceElement);
  }
  function checkVariableStatement(node) {
    if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node);
    checkVariableDeclarationList(node.declarationList);
  }
  function checkExpressionStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkExpression(node.expression);
  }
  function checkIfStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    const type = checkTruthinessExpression(node.expression);
    checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.expression, type, node.thenStatement);
    checkSourceElement(node.thenStatement);
    if (node.thenStatement.kind === 242 /* EmptyStatement */) {
      error(node.thenStatement, Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
    }
    checkSourceElement(node.elseStatement);
  }
  function checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr, condType, body) {
    if (!strictNullChecks) return;
    bothHelper(condExpr, body);
    function bothHelper(condExpr2, body2) {
      condExpr2 = skipParentheses(condExpr2);
      helper(condExpr2, body2);
      while (isBinaryExpression(condExpr2) && (condExpr2.operatorToken.kind === 57 /* BarBarToken */ || condExpr2.operatorToken.kind === 61 /* QuestionQuestionToken */)) {
        condExpr2 = skipParentheses(condExpr2.left);
        helper(condExpr2, body2);
      }
    }
    function helper(condExpr2, body2) {
      const location = isLogicalOrCoalescingBinaryExpression(condExpr2) ? skipParentheses(condExpr2.right) : condExpr2;
      if (isModuleExportsAccessExpression(location)) {
        return;
      }
      if (isLogicalOrCoalescingBinaryExpression(location)) {
        bothHelper(location, body2);
        return;
      }
      const type = location === condExpr2 ? condType : checkExpression(location);
      if (type.flags & 1024 /* EnumLiteral */ && isPropertyAccessExpression(location) && (getNodeLinks(location.expression).resolvedSymbol ?? unknownSymbol).flags & 384 /* Enum */) {
        error(location, Diagnostics.This_condition_will_always_return_0, !!type.value ? "true" : "false");
        return;
      }
      const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression);
      if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return;
      const callSignatures = getSignaturesOfType(type, 0 /* Call */);
      const isPromise = !!getAwaitedTypeOfPromise(type);
      if (callSignatures.length === 0 && !isPromise) {
        return;
      }
      const testedNode = isIdentifier(location) ? location : isPropertyAccessExpression(location) ? location.name : void 0;
      const testedSymbol = testedNode && getSymbolAtLocation(testedNode);
      if (!testedSymbol && !isPromise) {
        return;
      }
      const isUsed = testedSymbol && isBinaryExpression(condExpr2.parent) && isSymbolUsedInBinaryExpressionChain(condExpr2.parent, testedSymbol) || testedSymbol && body2 && isSymbolUsedInConditionBody(condExpr2, body2, testedNode, testedSymbol);
      if (!isUsed) {
        if (isPromise) {
          errorAndMaybeSuggestAwait(
            location,
            /*maybeMissingAwait*/
            true,
            Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined,
            getTypeNameForErrorDisplay(type)
          );
        } else {
          error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead);
        }
      }
    }
  }
  function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) {
    return !!forEachChild(body, function check(childNode) {
      if (isIdentifier(childNode)) {
        const childSymbol = getSymbolAtLocation(childNode);
        if (childSymbol && childSymbol === testedSymbol) {
          if (isIdentifier(expr) || isIdentifier(testedNode) && isBinaryExpression(testedNode.parent)) {
            return true;
          }
          let testedExpression = testedNode.parent;
          let childExpression = childNode.parent;
          while (testedExpression && childExpression) {
            if (isIdentifier(testedExpression) && isIdentifier(childExpression) || testedExpression.kind === 110 /* ThisKeyword */ && childExpression.kind === 110 /* ThisKeyword */) {
              return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
            } else if (isPropertyAccessExpression(testedExpression) && isPropertyAccessExpression(childExpression)) {
              if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
                return false;
              }
              childExpression = childExpression.expression;
              testedExpression = testedExpression.expression;
            } else if (isCallExpression(testedExpression) && isCallExpression(childExpression)) {
              childExpression = childExpression.expression;
              testedExpression = testedExpression.expression;
            } else {
              return false;
            }
          }
        }
      }
      return forEachChild(childNode, check);
    });
  }
  function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) {
    while (isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
      const isUsed = forEachChild(node.right, function visit(child) {
        if (isIdentifier(child)) {
          const symbol = getSymbolAtLocation(child);
          if (symbol && symbol === testedSymbol) {
            return true;
          }
        }
        return forEachChild(child, visit);
      });
      if (isUsed) {
        return true;
      }
      node = node.parent;
    }
    return false;
  }
  function checkDoStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkSourceElement(node.statement);
    checkTruthinessExpression(node.expression);
  }
  function checkWhileStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkTruthinessExpression(node.expression);
    checkSourceElement(node.statement);
  }
  function checkTruthinessOfType(type, node) {
    if (type.flags & 16384 /* Void */) {
      error(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
    } else {
      const semantics = getSyntacticTruthySemantics(node);
      if (semantics !== 3 /* Sometimes */) {
        error(
          node,
          semantics === 1 /* Always */ ? Diagnostics.This_kind_of_expression_is_always_truthy : Diagnostics.This_kind_of_expression_is_always_falsy
        );
      }
    }
    return type;
  }
  function getSyntacticTruthySemantics(node) {
    node = skipOuterExpressions(node);
    switch (node.kind) {
      case 9 /* NumericLiteral */:
        if (node.text === "0" || node.text === "1") {
          return 3 /* Sometimes */;
        }
        return 1 /* Always */;
      case 209 /* ArrayLiteralExpression */:
      case 219 /* ArrowFunction */:
      case 10 /* BigIntLiteral */:
      case 231 /* ClassExpression */:
      case 218 /* FunctionExpression */:
      case 284 /* JsxElement */:
      case 285 /* JsxSelfClosingElement */:
      case 210 /* ObjectLiteralExpression */:
      case 14 /* RegularExpressionLiteral */:
        return 1 /* Always */;
      case 222 /* VoidExpression */:
      case 106 /* NullKeyword */:
        return 2 /* Never */;
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */:
        return !!node.text ? 1 /* Always */ : 2 /* Never */;
      case 227 /* ConditionalExpression */:
        return getSyntacticTruthySemantics(node.whenTrue) | getSyntacticTruthySemantics(node.whenFalse);
      case 80 /* Identifier */:
        if (getResolvedSymbol(node) === undefinedSymbol) {
          return 2 /* Never */;
        }
        return 3 /* Sometimes */;
    }
    return 3 /* Sometimes */;
  }
  function checkTruthinessExpression(node, checkMode) {
    return checkTruthinessOfType(checkExpression(node, checkMode), node);
  }
  function checkForStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (node.initializer && node.initializer.kind === 261 /* VariableDeclarationList */) {
        checkGrammarVariableDeclarationList(node.initializer);
      }
    }
    if (node.initializer) {
      if (node.initializer.kind === 261 /* VariableDeclarationList */) {
        checkVariableDeclarationList(node.initializer);
      } else {
        checkExpression(node.initializer);
      }
    }
    if (node.condition) checkTruthinessExpression(node.condition);
    if (node.incrementor) checkExpression(node.incrementor);
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkForOfStatement(node) {
    checkGrammarForInOrForOfStatement(node);
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (node.awaitModifier) {
      if (container && isClassStaticBlockDeclaration(container)) {
        grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block);
      } else {
        const functionFlags = getFunctionFlags(container);
        if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.ForAwaitOf) {
          checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
        }
      }
    } else if (compilerOptions.downlevelIteration && languageVersion < LanguageFeatureMinimumTarget.ForOf) {
      checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
    }
    if (node.initializer.kind === 261 /* VariableDeclarationList */) {
      checkVariableDeclarationList(node.initializer);
    } else {
      const varExpr = node.initializer;
      const iteratedType = checkRightHandSideOfForOf(node);
      if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */) {
        checkDestructuringAssignment(varExpr, iteratedType || errorType);
      } else {
        const leftType = checkExpression(varExpr);
        checkReferenceExpression(
          varExpr,
          Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access,
          Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access
        );
        if (iteratedType) {
          checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
        }
      }
    }
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkForInStatement(node) {
    checkGrammarForInOrForOfStatement(node);
    const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
    if (node.initializer.kind === 261 /* VariableDeclarationList */) {
      const variable = node.initializer.declarations[0];
      if (variable && isBindingPattern(variable.name)) {
        error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
      }
      checkVariableDeclarationList(node.initializer);
    } else {
      const varExpr = node.initializer;
      const leftType = checkExpression(varExpr);
      if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */) {
        error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
      } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
        error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
      } else {
        checkReferenceExpression(
          varExpr,
          Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access,
          Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access
        );
      }
    }
    if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
      error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType));
    }
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkRightHandSideOfForOf(statement) {
    const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
    return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
  }
  function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
    if (isTypeAny(inputType)) {
      return inputType;
    }
    return getIteratedTypeOrElementType(
      use,
      inputType,
      sentType,
      errorNode,
      /*checkAssignability*/
      true
    ) || anyType;
  }
  function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
    const allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
    if (inputType === neverType) {
      if (errorNode) {
        reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables);
      }
      return void 0;
    }
    const uplevelIteration = languageVersion >= 2 /* ES2015 */;
    const downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
    const possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
    if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
      const iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : void 0);
      if (checkAssignability) {
        if (iterationTypes) {
          const diagnostic = use & 8 /* ForOfFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : use & 32 /* SpreadFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : use & 64 /* DestructuringFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : use & 16 /* YieldStarFlag */ ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : void 0;
          if (diagnostic) {
            checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
          }
        }
      }
      if (iterationTypes || uplevelIteration) {
        return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : iterationTypes && iterationTypes.yieldType;
      }
    }
    let arrayType = inputType;
    let hasStringConstituent = false;
    if (use & 4 /* AllowsStringInputFlag */) {
      if (arrayType.flags & 1048576 /* Union */) {
        const arrayTypes = inputType.types;
        const filteredTypes = filter(arrayTypes, (t) => !(t.flags & 402653316 /* StringLike */));
        if (filteredTypes !== arrayTypes) {
          arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
        }
      } else if (arrayType.flags & 402653316 /* StringLike */) {
        arrayType = neverType;
      }
      hasStringConstituent = arrayType !== inputType;
      if (hasStringConstituent) {
        if (arrayType.flags & 131072 /* Never */) {
          return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
        }
      }
    }
    if (!isArrayLikeType(arrayType)) {
      if (errorNode) {
        const allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent;
        const [defaultDiagnostic, maybeMissingAwait] = getIterationDiagnosticDetails(allowsStrings, downlevelIteration);
        errorAndMaybeSuggestAwait(
          errorNode,
          maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType),
          defaultDiagnostic,
          typeToString(arrayType)
        );
      }
      return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : void 0;
    }
    const arrayElementType = getIndexTypeOfType(arrayType, numberType);
    if (hasStringConstituent && arrayElementType) {
      if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) {
        return stringType;
      }
      return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */);
    }
    return use & 128 /* PossiblyOutOfBounds */ ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
    function getIterationDiagnosticDetails(allowsStrings, downlevelIteration2) {
      var _a;
      if (downlevelIteration2) {
        return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] : [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true];
      }
      const yieldType = getIterationTypeOfIterable(
        use,
        0 /* Yield */,
        inputType,
        /*errorNode*/
        void 0
      );
      if (yieldType) {
        return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, false];
      }
      if (isES2015OrLaterIterable((_a = inputType.symbol) == null ? void 0 : _a.escapedName)) {
        return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true];
      }
      return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] : [Diagnostics.Type_0_is_not_an_array_type, true];
    }
  }
  function isES2015OrLaterIterable(n) {
    switch (n) {
      case "Float32Array":
      case "Float64Array":
      case "Int16Array":
      case "Int32Array":
      case "Int8Array":
      case "NodeList":
      case "Uint16Array":
      case "Uint32Array":
      case "Uint8Array":
      case "Uint8ClampedArray":
        return true;
    }
    return false;
  }
  function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
    if (isTypeAny(inputType)) {
      return void 0;
    }
    const iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
    return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
  }
  function createIterationTypes(yieldType = neverType, returnType = neverType, nextType = unknownType) {
    if (yieldType.flags & 67359327 /* Intrinsic */ && returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) && nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
      const id = getTypeListId([yieldType, returnType, nextType]);
      let iterationTypes = iterationTypesCache.get(id);
      if (!iterationTypes) {
        iterationTypes = { yieldType, returnType, nextType };
        iterationTypesCache.set(id, iterationTypes);
      }
      return iterationTypes;
    }
    return { yieldType, returnType, nextType };
  }
  function combineIterationTypes(array) {
    let yieldTypes;
    let returnTypes;
    let nextTypes;
    for (const iterationTypes of array) {
      if (iterationTypes === void 0 || iterationTypes === noIterationTypes) {
        continue;
      }
      if (iterationTypes === anyIterationTypes) {
        return anyIterationTypes;
      }
      yieldTypes = append(yieldTypes, iterationTypes.yieldType);
      returnTypes = append(returnTypes, iterationTypes.returnType);
      nextTypes = append(nextTypes, iterationTypes.nextType);
    }
    if (yieldTypes || returnTypes || nextTypes) {
      return createIterationTypes(
        yieldTypes && getUnionType(yieldTypes),
        returnTypes && getUnionType(returnTypes),
        nextTypes && getIntersectionType(nextTypes)
      );
    }
    return noIterationTypes;
  }
  function getCachedIterationTypes(type, cacheKey) {
    return type[cacheKey];
  }
  function setCachedIterationTypes(type, cacheKey, cachedTypes2) {
    return type[cacheKey] = cachedTypes2;
  }
  function getIterationTypesOfIterable(type, use, errorNode) {
    var _a, _b;
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    if (!(type.flags & 1048576 /* Union */)) {
      const errorOutputContainer = errorNode ? { errors: void 0, skipLogging: true } : void 0;
      const iterationTypes2 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer);
      if (iterationTypes2 === noIterationTypes) {
        if (errorNode) {
          const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
          if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) {
            addRelatedInfo(rootDiag, ...errorOutputContainer.errors);
          }
        }
        return void 0;
      } else if ((_a = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _a.length) {
        for (const diag2 of errorOutputContainer.errors) {
          diagnostics.add(diag2);
        }
      }
      return iterationTypes2;
    }
    const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
    const cachedTypes2 = getCachedIterationTypes(type, cacheKey);
    if (cachedTypes2) return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2;
    let allIterationTypes;
    for (const constituent of type.types) {
      const errorOutputContainer = errorNode ? { errors: void 0 } : void 0;
      const iterationTypes2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer);
      if (iterationTypes2 === noIterationTypes) {
        if (errorNode) {
          const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
          if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) {
            addRelatedInfo(rootDiag, ...errorOutputContainer.errors);
          }
        }
        setCachedIterationTypes(type, cacheKey, noIterationTypes);
        return void 0;
      } else if ((_b = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _b.length) {
        for (const diag2 of errorOutputContainer.errors) {
          diagnostics.add(diag2);
        }
      }
      allIterationTypes = append(allIterationTypes, iterationTypes2);
    }
    const iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
    setCachedIterationTypes(type, cacheKey, iterationTypes);
    return iterationTypes === noIterationTypes ? void 0 : iterationTypes;
  }
  function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
    if (iterationTypes === noIterationTypes) return noIterationTypes;
    if (iterationTypes === anyIterationTypes) return anyIterationTypes;
    const { yieldType, returnType, nextType } = iterationTypes;
    if (errorNode) {
      getGlobalAwaitedSymbol(
        /*reportErrors*/
        true
      );
    }
    return createIterationTypes(
      getAwaitedType(yieldType, errorNode) || anyType,
      getAwaitedType(returnType, errorNode) || anyType,
      nextType
    );
  }
  function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    let noCache = false;
    if (use & 2 /* AllowsAsyncIterablesFlag */) {
      const iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
      if (iterationTypes) {
        if (iterationTypes === noIterationTypes && errorNode) {
          noCache = true;
        } else {
          return use & 8 /* ForOfFlag */ ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : iterationTypes;
        }
      }
    }
    if (use & 1 /* AllowsSyncIterablesFlag */) {
      let iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
      if (iterationTypes) {
        if (iterationTypes === noIterationTypes && errorNode) {
          noCache = true;
        } else {
          if (use & 2 /* AllowsAsyncIterablesFlag */) {
            if (iterationTypes !== noIterationTypes) {
              iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode);
              return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes);
            }
          } else {
            return iterationTypes;
          }
        }
      }
    }
    if (use & 2 /* AllowsAsyncIterablesFlag */) {
      const iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache);
      if (iterationTypes !== noIterationTypes) {
        return iterationTypes;
      }
    }
    if (use & 1 /* AllowsSyncIterablesFlag */) {
      let iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache);
      if (iterationTypes !== noIterationTypes) {
        if (use & 2 /* AllowsAsyncIterablesFlag */) {
          iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode);
          return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes);
        } else {
          return iterationTypes;
        }
      }
    }
    return noIterationTypes;
  }
  function getIterationTypesOfIterableCached(type, resolver) {
    return getCachedIterationTypes(type, resolver.iterableCacheKey);
  }
  function getIterationTypesOfIterableFast(type, resolver) {
    if (isReferenceToType(type, resolver.getGlobalIterableType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIterableIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    ))) {
      const [yieldType, returnType, nextType] = getTypeArguments(type);
      return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(
        yieldType,
        /*errorNode*/
        void 0
      ) || yieldType, resolver.resolveIterationType(
        returnType,
        /*errorNode*/
        void 0
      ) || returnType, nextType));
    }
    if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) {
      const [yieldType] = getTypeArguments(type);
      const returnType = getBuiltinIteratorReturnType();
      const nextType = unknownType;
      return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(
        yieldType,
        /*errorNode*/
        void 0
      ) || yieldType, resolver.resolveIterationType(
        returnType,
        /*errorNode*/
        void 0
      ) || returnType, nextType));
    }
  }
  function getPropertyNameForKnownSymbolName(symbolName2) {
    const ctorType = getGlobalESSymbolConstructorSymbol(
      /*reportErrors*/
      false
    );
    const uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), escapeLeadingUnderscores(symbolName2));
    return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName2}`;
  }
  function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) {
    const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
    const methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : void 0;
    if (isTypeAny(methodType)) {
      return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
    }
    const allSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : void 0;
    const validSignatures = filter(allSignatures, (sig) => getMinArgumentCount(sig) === 0);
    if (!some(validSignatures)) {
      if (errorNode && some(allSignatures)) {
        checkTypeAssignableTo(
          type,
          resolver.getGlobalIterableType(
            /*reportErrors*/
            true
          ),
          errorNode,
          /*headMessage*/
          void 0,
          /*containingMessageChain*/
          void 0,
          errorOutputContainer
        );
      }
      return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
    }
    const iteratorType = getIntersectionType(map(validSignatures, getReturnTypeOfSignature));
    const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes;
    return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
  }
  function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
    const message = allowAsyncIterables ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
    const suggestAwait = (
      // for (const x of Promise<...>) or [...Promise<...>]
      !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      ) !== emptyGenericType && isTypeAssignableTo(type, createTypeFromGenericGlobalType(getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      ), [anyType, anyType, anyType]))
    );
    return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type));
  }
  function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) {
    return getIterationTypesOfIteratorWorker(
      type,
      resolver,
      errorNode,
      errorOutputContainer,
      /*noCache*/
      false
    );
  }
  function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    let iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || getIterationTypesOfIteratorFast(type, resolver);
    if (iterationTypes === noIterationTypes && errorNode) {
      iterationTypes = void 0;
      noCache = true;
    }
    iterationTypes ?? (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache));
    return iterationTypes === noIterationTypes ? void 0 : iterationTypes;
  }
  function getIterationTypesOfIteratorCached(type, resolver) {
    return getCachedIterationTypes(type, resolver.iteratorCacheKey);
  }
  function getIterationTypesOfIteratorFast(type, resolver) {
    if (isReferenceToType(type, resolver.getGlobalIterableIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    ))) {
      const [yieldType, returnType, nextType] = getTypeArguments(type);
      return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
    }
    if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) {
      const [yieldType] = getTypeArguments(type);
      const returnType = getBuiltinIteratorReturnType();
      const nextType = unknownType;
      return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
    }
  }
  function isIteratorResult(type, kind) {
    const doneType = getTypeOfPropertyOfType(type, "done") || falseType;
    return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
  }
  function isYieldIteratorResult(type) {
    return isIteratorResult(type, 0 /* Yield */);
  }
  function isReturnIteratorResult(type) {
    return isIteratorResult(type, 1 /* Return */);
  }
  function getIterationTypesOfIteratorResult(type) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    const cachedTypes2 = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
    if (cachedTypes2) {
      return cachedTypes2;
    }
    if (isReferenceToType(type, getGlobalIteratorYieldResultType(
      /*reportErrors*/
      false
    ))) {
      const yieldType2 = getTypeArguments(type)[0];
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
        yieldType2,
        /*returnType*/
        void 0,
        /*nextType*/
        void 0
      ));
    }
    if (isReferenceToType(type, getGlobalIteratorReturnResultType(
      /*reportErrors*/
      false
    ))) {
      const returnType2 = getTypeArguments(type)[0];
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
        /*yieldType*/
        void 0,
        returnType2,
        /*nextType*/
        void 0
      ));
    }
    const yieldIteratorResult = filterType(type, isYieldIteratorResult);
    const yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : void 0;
    const returnIteratorResult = filterType(type, isReturnIteratorResult);
    const returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : void 0;
    if (!yieldType && !returnType) {
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
    }
    return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
      yieldType,
      returnType || voidType,
      /*nextType*/
      void 0
    ));
  }
  function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) {
    var _a, _b, _c, _d;
    const method = getPropertyOfType(type, methodName);
    if (!method && methodName !== "next") {
      return void 0;
    }
    const methodType = method && !(methodName === "next" && method.flags & 16777216 /* Optional */) ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */) : void 0;
    if (isTypeAny(methodType)) {
      return anyIterationTypes;
    }
    const methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : emptyArray;
    if (methodSignatures.length === 0) {
      if (errorNode) {
        const diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic;
        if (errorOutputContainer) {
          errorOutputContainer.errors ?? (errorOutputContainer.errors = []);
          errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, diagnostic, methodName));
        } else {
          error(errorNode, diagnostic, methodName);
        }
      }
      return methodName === "next" ? noIterationTypes : void 0;
    }
    if ((methodType == null ? void 0 : methodType.symbol) && methodSignatures.length === 1) {
      const globalGeneratorType = resolver.getGlobalGeneratorType(
        /*reportErrors*/
        false
      );
      const globalIteratorType = resolver.getGlobalIteratorType(
        /*reportErrors*/
        false
      );
      const isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) == null ? void 0 : _a.members) == null ? void 0 : _b.get(methodName)) === methodType.symbol;
      const isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) == null ? void 0 : _c.members) == null ? void 0 : _d.get(methodName)) === methodType.symbol;
      if (isGeneratorMethod || isIteratorMethod) {
        const globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
        const { mapper } = methodType;
        return createIterationTypes(
          getMappedType(globalType.typeParameters[0], mapper),
          getMappedType(globalType.typeParameters[1], mapper),
          methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0
        );
      }
    }
    let methodParameterTypes;
    let methodReturnTypes;
    for (const signature of methodSignatures) {
      if (methodName !== "throw" && some(signature.parameters)) {
        methodParameterTypes = append(methodParameterTypes, getTypeAtPosition(signature, 0));
      }
      methodReturnTypes = append(methodReturnTypes, getReturnTypeOfSignature(signature));
    }
    let returnTypes;
    let nextType;
    if (methodName !== "throw") {
      const methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
      if (methodName === "next") {
        nextType = methodParameterType;
      } else if (methodName === "return") {
        const resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
        returnTypes = append(returnTypes, resolvedMethodParameterType);
      }
    }
    let yieldType;
    const methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
    const resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
    const iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
    if (iterationTypes === noIterationTypes) {
      if (errorNode) {
        if (errorOutputContainer) {
          errorOutputContainer.errors ?? (errorOutputContainer.errors = []);
          errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName));
        } else {
          error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
        }
      }
      yieldType = anyType;
      returnTypes = append(returnTypes, anyType);
    } else {
      yieldType = iterationTypes.yieldType;
      returnTypes = append(returnTypes, iterationTypes.returnType);
    }
    return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
  }
  function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) {
    const iterationTypes = combineIterationTypes([
      getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer),
      getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer),
      getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer)
    ]);
    return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
  }
  function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
    if (isTypeAny(returnType)) {
      return void 0;
    }
    const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
    return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
  }
  function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    const use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
    const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
    return getIterationTypesOfIterable(
      type,
      use,
      /*errorNode*/
      void 0
    ) || getIterationTypesOfIterator(
      type,
      resolver,
      /*errorNode*/
      void 0,
      /*errorOutputContainer*/
      void 0
    );
  }
  function checkBreakOrContinueStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node);
  }
  function unwrapReturnType(returnType, functionFlags) {
    const isGenerator = !!(functionFlags & 1 /* Generator */);
    const isAsync = !!(functionFlags & 2 /* Async */);
    if (isGenerator) {
      const returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync);
      if (!returnIterationType) {
        return errorType;
      }
      return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType;
    }
    return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType;
  }
  function isUnwrappedReturnTypeUndefinedVoidOrAny(func, returnType) {
    const type = unwrapReturnType(returnType, getFunctionFlags(func));
    return !!(type && (maybeTypeOfKind(type, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */)));
  }
  function checkReturnStatement(node) {
    if (checkGrammarStatementInAmbientContext(node)) {
      return;
    }
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (container && isClassStaticBlockDeclaration(container)) {
      grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block);
      return;
    }
    if (!container) {
      grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
      return;
    }
    const signature = getSignatureFromDeclaration(container);
    const returnType = getReturnTypeOfSignature(signature);
    const functionFlags = getFunctionFlags(container);
    if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
      const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
      if (container.kind === 178 /* SetAccessor */) {
        if (node.expression) {
          error(node, Diagnostics.Setters_cannot_return_a_value);
        }
      } else if (container.kind === 176 /* Constructor */) {
        if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
          error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
        }
      } else if (getReturnTypeFromAnnotation(container)) {
        const unwrappedReturnType = unwrapReturnType(returnType, functionFlags) ?? returnType;
        const unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(
          exprType,
          /*withAlias*/
          false,
          node,
          Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
        ) : exprType;
        if (unwrappedReturnType) {
          checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
        }
      }
    } else if (container.kind !== 176 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeUndefinedVoidOrAny(container, returnType)) {
      error(node, Diagnostics.Not_all_code_paths_return_a_value);
    }
  }
  function checkWithStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (node.flags & 65536 /* AwaitContext */) {
        grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
      }
    }
    checkExpression(node.expression);
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const start = getSpanOfTokenAtPosition(sourceFile, node.pos).start;
      const end = node.statement.pos;
      grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
    }
  }
  function checkSwitchStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    let firstDefaultClause;
    let hasDuplicateDefaultClause = false;
    const expressionType = checkExpression(node.expression);
    forEach(node.caseBlock.clauses, (clause) => {
      if (clause.kind === 297 /* DefaultClause */ && !hasDuplicateDefaultClause) {
        if (firstDefaultClause === void 0) {
          firstDefaultClause = clause;
        } else {
          grammarErrorOnNode(clause, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
          hasDuplicateDefaultClause = true;
        }
      }
      if (clause.kind === 296 /* CaseClause */) {
        addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause));
      }
      forEach(clause.statements, checkSourceElement);
      if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
        error(clause, Diagnostics.Fallthrough_case_in_switch);
      }
      function createLazyCaseClauseDiagnostics(clause2) {
        return () => {
          const caseType = checkExpression(clause2.expression);
          if (!isTypeEqualityComparableTo(expressionType, caseType)) {
            checkTypeComparableTo(
              caseType,
              expressionType,
              clause2.expression,
              /*headMessage*/
              void 0
            );
          }
        };
      }
    });
    if (node.caseBlock.locals) {
      registerForUnusedIdentifiersCheck(node.caseBlock);
    }
  }
  function checkLabeledStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      findAncestor(node.parent, (current) => {
        if (isFunctionLike(current)) {
          return "quit";
        }
        if (current.kind === 256 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
          grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label));
          return true;
        }
        return false;
      });
    }
    checkSourceElement(node.statement);
  }
  function checkThrowStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (isIdentifier(node.expression) && !node.expression.escapedText) {
        grammarErrorAfterFirstToken(node, Diagnostics.Line_break_not_permitted_here);
      }
    }
    if (node.expression) {
      checkExpression(node.expression);
    }
  }
  function checkTryStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkBlock(node.tryBlock);
    const catchClause = node.catchClause;
    if (catchClause) {
      if (catchClause.variableDeclaration) {
        const declaration = catchClause.variableDeclaration;
        checkVariableLikeDeclaration(declaration);
        const typeNode = getEffectiveTypeAnnotationNode(declaration);
        if (typeNode) {
          const type = getTypeFromTypeNode(typeNode);
          if (type && !(type.flags & 3 /* AnyOrUnknown */)) {
            grammarErrorOnFirstToken(typeNode, Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
          }
        } else if (declaration.initializer) {
          grammarErrorOnFirstToken(declaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
        } else {
          const blockLocals = catchClause.block.locals;
          if (blockLocals) {
            forEachKey(catchClause.locals, (caughtName) => {
              const blockLocal = blockLocals.get(caughtName);
              if ((blockLocal == null ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
                grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, unescapeLeadingUnderscores(caughtName));
              }
            });
          }
        }
      }
      checkBlock(catchClause.block);
    }
    if (node.finallyBlock) {
      checkBlock(node.finallyBlock);
    }
  }
  function checkIndexConstraints(type, symbol, isStaticIndex) {
    const indexInfos = getIndexInfosOfType(type);
    if (indexInfos.length === 0) {
      return;
    }
    for (const prop of getPropertiesOfObjectType(type)) {
      if (!(isStaticIndex && prop.flags & 4194304 /* Prototype */)) {
        checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(
          prop,
          8576 /* StringOrNumberLiteralOrUnique */,
          /*includeNonPublic*/
          true
        ), getNonMissingTypeOfSymbol(prop));
      }
    }
    const typeDeclaration = symbol.valueDeclaration;
    if (typeDeclaration && isClassLike(typeDeclaration)) {
      for (const member of typeDeclaration.members) {
        if (!isStatic(member) && !hasBindableName(member)) {
          const symbol2 = getSymbolOfDeclaration(member);
          checkIndexConstraintForProperty(type, symbol2, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol2));
        }
      }
    }
    if (indexInfos.length > 1) {
      for (const info of indexInfos) {
        checkIndexConstraintForIndexSignature(type, info);
      }
    }
  }
  function checkIndexConstraintForProperty(type, prop, propNameType, propType) {
    const declaration = prop.valueDeclaration;
    const name = getNameOfDeclaration(declaration);
    if (name && isPrivateIdentifier(name)) {
      return;
    }
    const indexInfos = getApplicableIndexInfos(type, propNameType);
    const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0;
    const propDeclaration = declaration && declaration.kind === 226 /* BinaryExpression */ || name && name.kind === 167 /* ComputedPropertyName */ ? declaration : void 0;
    const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : void 0;
    for (const info of indexInfos) {
      const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0;
      const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0);
      if (errorNode && !isTypeAssignableTo(propType, info.type)) {
        const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type));
        if (propDeclaration && errorNode !== propDeclaration) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(propDeclaration, Diagnostics._0_is_declared_here, symbolToString(prop)));
        }
        diagnostics.add(diagnostic);
      }
    }
  }
  function checkIndexConstraintForIndexSignature(type, checkInfo) {
    const declaration = checkInfo.declaration;
    const indexInfos = getApplicableIndexInfos(type, checkInfo.keyType);
    const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0;
    const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0;
    for (const info of indexInfos) {
      if (info === checkInfo) continue;
      const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0;
      const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0);
      if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) {
        error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type));
      }
    }
  }
  function checkTypeNameIsReserved(name, message) {
    switch (name.escapedText) {
      case "any":
      case "unknown":
      case "never":
      case "number":
      case "bigint":
      case "boolean":
      case "string":
      case "symbol":
      case "void":
      case "object":
      case "undefined":
        error(name, message, name.escapedText);
    }
  }
  function checkClassNameCollisionWithObject(name) {
    if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && host.getEmitModuleFormatOfFile(getSourceFileOfNode(name)) < 5 /* ES2015 */) {
      error(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]);
    }
  }
  function checkUnmatchedJSDocParameters(node) {
    const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag);
    if (!length(jsdocParameters)) return;
    const isJs = isInJSFile(node);
    const parameters = /* @__PURE__ */ new Set();
    const excludedParameters = /* @__PURE__ */ new Set();
    forEach(node.parameters, ({ name }, index) => {
      if (isIdentifier(name)) {
        parameters.add(name.escapedText);
      }
      if (isBindingPattern(name)) {
        excludedParameters.add(index);
      }
    });
    const containsArguments = containsArgumentsReference(node);
    if (containsArguments) {
      const lastJSDocParamIndex = jsdocParameters.length - 1;
      const lastJSDocParam = jsdocParameters[lastJSDocParamIndex];
      if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) {
        error(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name));
      }
    } else {
      forEach(jsdocParameters, ({ name, isNameFirst }, index) => {
        if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) {
          return;
        }
        if (isQualifiedName(name)) {
          if (isJs) {
            error(name, Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), entityNameToString(name.left));
          }
        } else {
          if (!isNameFirst) {
            errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name));
          }
        }
      });
    }
  }
  function checkTypeParameters(typeParameterDeclarations) {
    let seenDefault = false;
    if (typeParameterDeclarations) {
      for (let i = 0; i < typeParameterDeclarations.length; i++) {
        const node = typeParameterDeclarations[i];
        checkTypeParameter(node);
        addLazyDiagnostic(createCheckTypeParameterDiagnostic(node, i));
      }
    }
    function createCheckTypeParameterDiagnostic(node, i) {
      return () => {
        if (node.default) {
          seenDefault = true;
          checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
        } else if (seenDefault) {
          error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
        }
        for (let j = 0; j < i; j++) {
          if (typeParameterDeclarations[j].symbol === node.symbol) {
            error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name));
          }
        }
      };
    }
  }
  function checkTypeParametersNotReferenced(root, typeParameters, index) {
    visit(root);
    function visit(node) {
      if (node.kind === 183 /* TypeReference */) {
        const type = getTypeFromTypeReference(node);
        if (type.flags & 262144 /* TypeParameter */) {
          for (let i = index; i < typeParameters.length; i++) {
            if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) {
              error(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
            }
          }
        }
      }
      forEachChild(node, visit);
    }
  }
  function checkTypeParameterListsIdentical(symbol) {
    if (symbol.declarations && symbol.declarations.length === 1) {
      return;
    }
    const links = getSymbolLinks(symbol);
    if (!links.typeParametersChecked) {
      links.typeParametersChecked = true;
      const declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
      if (!declarations || declarations.length <= 1) {
        return;
      }
      const type = getDeclaredTypeOfSymbol(symbol);
      if (!areTypeParametersIdentical(declarations, type.localTypeParameters, getEffectiveTypeParameterDeclarations)) {
        const name = symbolToString(symbol);
        for (const declaration of declarations) {
          error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
        }
      }
    }
  }
  function areTypeParametersIdentical(declarations, targetParameters, getTypeParameterDeclarations) {
    const maxTypeArgumentCount = length(targetParameters);
    const minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
    for (const declaration of declarations) {
      const sourceParameters = getTypeParameterDeclarations(declaration);
      const numTypeParameters = sourceParameters.length;
      if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
        return false;
      }
      for (let i = 0; i < numTypeParameters; i++) {
        const source = sourceParameters[i];
        const target = targetParameters[i];
        if (source.name.escapedText !== target.symbol.escapedName) {
          return false;
        }
        const constraint = getEffectiveConstraintOfTypeParameter(source);
        const sourceConstraint = constraint && getTypeFromTypeNode(constraint);
        const targetConstraint = getConstraintOfTypeParameter(target);
        if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
          return false;
        }
        const sourceDefault = source.default && getTypeFromTypeNode(source.default);
        const targetDefault = getDefaultFromTypeParameter(target);
        if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
          return false;
        }
      }
    }
    return true;
  }
  function getFirstTransformableStaticClassElement(node) {
    const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    );
    const willTransformPrivateElementsOrClassStaticBlocks = languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators;
    const willTransformInitializers = !emitStandardClassFields;
    if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) {
      for (const member of node.members) {
        if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated(
          /*useLegacyDecorators*/
          false,
          member,
          node
        )) {
          return firstOrUndefined(getDecorators(node)) ?? node;
        } else if (willTransformPrivateElementsOrClassStaticBlocks) {
          if (isClassStaticBlockDeclaration(member)) {
            return member;
          } else if (isStatic(member)) {
            if (isPrivateIdentifierClassElementDeclaration(member) || willTransformInitializers && isInitializedProperty(member)) {
              return member;
            }
          }
        }
      }
    }
  }
  function checkClassExpressionExternalHelpers(node) {
    if (node.name) return;
    const parent = walkUpOuterExpressions(node);
    if (!isNamedEvaluationSource(parent)) return;
    const willTransformESDecorators = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators;
    let location;
    if (willTransformESDecorators && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    )) {
      location = firstOrUndefined(getDecorators(node)) ?? node;
    } else {
      location = getFirstTransformableStaticClassElement(node);
    }
    if (location) {
      checkExternalEmitHelpers(location, 4194304 /* SetFunctionName */);
      if ((isPropertyAssignment(parent) || isPropertyDeclaration(parent) || isBindingElement(parent)) && isComputedPropertyName(parent.name)) {
        checkExternalEmitHelpers(location, 8388608 /* PropKey */);
      }
    }
  }
  function checkClassExpression(node) {
    checkClassLikeDeclaration(node);
    checkNodeDeferred(node);
    checkClassExpressionExternalHelpers(node);
    return getTypeOfSymbol(getSymbolOfDeclaration(node));
  }
  function checkClassExpressionDeferred(node) {
    forEach(node.members, checkSourceElement);
    registerForUnusedIdentifiersCheck(node);
  }
  function checkClassDeclaration(node) {
    const firstDecorator = find(node.modifiers, isDecorator);
    if (legacyDecorators && firstDecorator && some(node.members, (p) => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) {
      grammarErrorOnNode(firstDecorator, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator);
    }
    if (!node.name && !hasSyntacticModifier(node, 2048 /* Default */)) {
      grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
    }
    checkClassLikeDeclaration(node);
    forEach(node.members, checkSourceElement);
    registerForUnusedIdentifiersCheck(node);
  }
  function checkClassLikeDeclaration(node) {
    checkGrammarClassLikeDeclaration(node);
    checkDecorators(node);
    checkCollisionsForDeclarationName(node, node.name);
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
    checkExportsOnMergedDeclarations(node);
    const symbol = getSymbolOfDeclaration(node);
    const type = getDeclaredTypeOfSymbol(symbol);
    const typeWithThis = getTypeWithThisArgument(type);
    const staticType = getTypeOfSymbol(symbol);
    checkTypeParameterListsIdentical(symbol);
    checkFunctionOrConstructorSymbol(symbol);
    checkClassForDuplicateDeclarations(node);
    const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */);
    if (!nodeInAmbientContext) {
      checkClassForStaticPropertyNameConflicts(node);
    }
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    if (baseTypeNode) {
      forEach(baseTypeNode.typeArguments, checkSourceElement);
      if (languageVersion < LanguageFeatureMinimumTarget.Classes) {
        checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
      }
      const extendsNode = getClassExtendsHeritageElement(node);
      if (extendsNode && extendsNode !== baseTypeNode) {
        checkExpression(extendsNode.expression);
      }
      const baseTypes = getBaseTypes(type);
      if (baseTypes.length) {
        addLazyDiagnostic(() => {
          const baseType = baseTypes[0];
          const baseConstructorType = getBaseConstructorTypeOfClass(type);
          const staticBaseType = getApparentType(baseConstructorType);
          checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
          checkSourceElement(baseTypeNode.expression);
          if (some(baseTypeNode.typeArguments)) {
            forEach(baseTypeNode.typeArguments, checkSourceElement);
            for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) {
              if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
                break;
              }
            }
          }
          const baseWithThis = getTypeWithThisArgument(baseType, type.thisType);
          if (!checkTypeAssignableTo(
            typeWithThis,
            baseWithThis,
            /*errorNode*/
            void 0
          )) {
            issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1);
          } else {
            checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
          }
          if (baseConstructorType.flags & 8650752 /* TypeVariable */) {
            if (!isMixinConstructorType(staticType)) {
              error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
            } else {
              const constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
              if (constructSignatures.some((signature) => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 64 /* Abstract */)) {
                error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract);
              }
            }
          }
          if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
            const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
            if (forEach(constructors, (sig) => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) {
              error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type);
            }
          }
          checkKindsOfPropertyMemberOverrides(type, baseType);
        });
      }
    }
    checkMembersForOverrideModifier(node, type, typeWithThis, staticType);
    const implementedTypeNodes = getEffectiveImplementsTypeNodes(node);
    if (implementedTypeNodes) {
      for (const typeRefNode of implementedTypeNodes) {
        if (!isEntityNameExpression(typeRefNode.expression) || isOptionalChain(typeRefNode.expression)) {
          error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
        }
        checkTypeReferenceNode(typeRefNode);
        addLazyDiagnostic(createImplementsDiagnostics(typeRefNode));
      }
    }
    addLazyDiagnostic(() => {
      checkIndexConstraints(type, symbol);
      checkIndexConstraints(
        staticType,
        symbol,
        /*isStaticIndex*/
        true
      );
      checkTypeForDuplicateIndexSignatures(node);
      checkPropertyInitialization(node);
    });
    function createImplementsDiagnostics(typeRefNode) {
      return () => {
        const t = getReducedType(getTypeFromTypeNode(typeRefNode));
        if (!isErrorType(t)) {
          if (isValidBaseType(t)) {
            const genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : Diagnostics.Class_0_incorrectly_implements_interface_1;
            const baseWithThis = getTypeWithThisArgument(t, type.thisType);
            if (!checkTypeAssignableTo(
              typeWithThis,
              baseWithThis,
              /*errorNode*/
              void 0
            )) {
              issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
            }
          } else {
            error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
          }
        }
      };
    }
  }
  function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) {
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    const baseTypes = baseTypeNode && getBaseTypes(type);
    const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0;
    const baseStaticType = getBaseConstructorTypeOfClass(type);
    for (const member of node.members) {
      if (hasAmbientModifier(member)) {
        continue;
      }
      if (isConstructorDeclaration(member)) {
        forEach(member.parameters, (param) => {
          if (isParameterPropertyDeclaration(param, member)) {
            checkExistingMemberForOverrideModifier(
              node,
              staticType,
              baseStaticType,
              baseWithThis,
              type,
              typeWithThis,
              param,
              /*memberIsParameterProperty*/
              true
            );
          }
        });
      }
      checkExistingMemberForOverrideModifier(
        node,
        staticType,
        baseStaticType,
        baseWithThis,
        type,
        typeWithThis,
        member,
        /*memberIsParameterProperty*/
        false
      );
    }
  }
  function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors2 = true) {
    const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
    if (!declaredProp) {
      return 0 /* Ok */;
    }
    return checkMemberForOverrideModifier(
      node,
      staticType,
      baseStaticType,
      baseWithThis,
      type,
      typeWithThis,
      hasOverrideModifier(member),
      hasAbstractModifier(member),
      isStatic(member),
      memberIsParameterProperty,
      declaredProp,
      reportErrors2 ? member : void 0
    );
  }
  function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, member, errorNode) {
    const isJs = isInJSFile(node);
    const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */);
    if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) {
      const thisType = memberIsStatic ? staticType : typeWithThis;
      const baseType = memberIsStatic ? baseStaticType : baseWithThis;
      const prop = getPropertyOfType(thisType, member.escapedName);
      const baseProp = getPropertyOfType(baseType, member.escapedName);
      const baseClassName = typeToString(baseWithThis);
      if (prop && !baseProp && memberHasOverrideModifier) {
        if (errorNode) {
          const suggestion = getSuggestedSymbolForNonexistentClassMember(symbolName(member), baseType);
          suggestion ? error(
            errorNode,
            isJs ? 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 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1,
            baseClassName,
            symbolToString(suggestion)
          ) : error(
            errorNode,
            isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0,
            baseClassName
          );
        }
        return 2 /* HasInvalidOverride */;
      } else if (prop && (baseProp == null ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) {
        const baseHasAbstract = some(baseProp.declarations, hasAbstractModifier);
        if (memberHasOverrideModifier) {
          return 0 /* Ok */;
        }
        if (!baseHasAbstract) {
          if (errorNode) {
            const diag2 = memberIsParameterProperty ? isJs ? Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0;
            error(errorNode, diag2, baseClassName);
          }
          return 1 /* NeedsOverride */;
        } else if (memberHasAbstractModifier && baseHasAbstract) {
          if (errorNode) {
            error(errorNode, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName);
          }
          return 1 /* NeedsOverride */;
        }
      }
    } else if (memberHasOverrideModifier) {
      if (errorNode) {
        const className = typeToString(type);
        error(
          errorNode,
          isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class,
          className
        );
      }
      return 2 /* HasInvalidOverride */;
    }
    return 0 /* Ok */;
  }
  function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
    let issuedMemberError = false;
    for (const member of node.members) {
      if (isStatic(member)) {
        continue;
      }
      const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
      if (declaredProp) {
        const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
        const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
        if (prop && baseProp) {
          const rootChain = () => chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2,
            symbolToString(declaredProp),
            typeToString(typeWithThis),
            typeToString(baseWithThis)
          );
          if (!checkTypeAssignableTo(
            getTypeOfSymbol(prop),
            getTypeOfSymbol(baseProp),
            member.name || member,
            /*headMessage*/
            void 0,
            rootChain
          )) {
            issuedMemberError = true;
          }
        }
      }
    }
    if (!issuedMemberError) {
      checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
    }
  }
  function checkBaseTypeAccessibility(type, node) {
    const signatures = getSignaturesOfType(type, 1 /* Construct */);
    if (signatures.length) {
      const declaration = signatures[0].declaration;
      if (declaration && hasEffectiveModifier(declaration, 2 /* Private */)) {
        const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
        if (!isNodeWithinClass(node, typeClassDeclaration)) {
          error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
        }
      }
    }
  }
  function getMemberOverrideModifierStatus(node, member, memberSymbol) {
    if (!member.name) {
      return 0 /* Ok */;
    }
    const classSymbol = getSymbolOfDeclaration(node);
    const type = getDeclaredTypeOfSymbol(classSymbol);
    const typeWithThis = getTypeWithThisArgument(type);
    const staticType = getTypeOfSymbol(classSymbol);
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    const baseTypes = baseTypeNode && getBaseTypes(type);
    const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0;
    const baseStaticType = getBaseConstructorTypeOfClass(type);
    const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16 /* Override */);
    return checkMemberForOverrideModifier(
      node,
      staticType,
      baseStaticType,
      baseWithThis,
      type,
      typeWithThis,
      memberHasOverrideModifier,
      hasAbstractModifier(member),
      isStatic(member),
      /*memberIsParameterProperty*/
      false,
      memberSymbol
    );
  }
  function getTargetSymbol(s) {
    return getCheckFlags(s) & 1 /* Instantiated */ ? s.links.target : s;
  }
  function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
    return filter(symbol.declarations, (d) => d.kind === 263 /* ClassDeclaration */ || d.kind === 264 /* InterfaceDeclaration */);
  }
  function checkKindsOfPropertyMemberOverrides(type, baseType) {
    var _a, _b, _c, _d, _e;
    const baseProperties = getPropertiesOfType(baseType);
    const notImplementedInfo = /* @__PURE__ */ new Map();
    basePropertyCheck: for (const baseProperty of baseProperties) {
      const base = getTargetSymbol(baseProperty);
      if (base.flags & 4194304 /* Prototype */) {
        continue;
      }
      const baseSymbol = getPropertyOfObjectType(type, base.escapedName);
      if (!baseSymbol) {
        continue;
      }
      const derived = getTargetSymbol(baseSymbol);
      const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base);
      Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
      if (derived === base) {
        const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol);
        if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) {
          for (const otherBaseType of getBaseTypes(type)) {
            if (otherBaseType === baseType) continue;
            const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName);
            const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2);
            if (derivedElsewhere && derivedElsewhere !== base) {
              continue basePropertyCheck;
            }
          }
          const baseTypeName = typeToString(baseType);
          const typeName = typeToString(type);
          const basePropertyName = symbolToString(baseProperty);
          const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName);
          notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties });
        }
      } else {
        const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived);
        if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) {
          continue;
        }
        let errorMessage;
        const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
        const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
        if (basePropertyFlags && derivedPropertyFlags) {
          if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) {
            continue;
          }
          const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
          const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
          if (overriddenInstanceProperty || overriddenInstanceAccessor) {
            const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
            error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type));
          } else if (useDefineForClassFields) {
            const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer);
            if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) {
              const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol));
              const propName = uninitialized.name;
              if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) {
                const errorMessage2 = 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;
                error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType));
              }
            }
          }
          continue;
        } else if (isPrototypeProperty(base)) {
          if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
            continue;
          } else {
            Debug.assert(!!(derived.flags & 98304 /* Accessor */));
            errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
          }
        } else if (base.flags & 98304 /* Accessor */) {
          errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
        } else {
          errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
        }
        error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
      }
    }
    for (const [errorNode, memberInfo] of notImplementedInfo) {
      if (length(memberInfo.missedProperties) === 1) {
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, first(memberInfo.missedProperties), memberInfo.baseTypeName);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, memberInfo.typeName, first(memberInfo.missedProperties), memberInfo.baseTypeName);
        }
      } else if (length(memberInfo.missedProperties) > 5) {
        const missedProperties = map(memberInfo.missedProperties.slice(0, 4), (prop) => `'${prop}'`).join(", ");
        const remainingMissedProperties = length(memberInfo.missedProperties) - 4;
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more, memberInfo.baseTypeName, missedProperties, remainingMissedProperties);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more, memberInfo.typeName, memberInfo.baseTypeName, missedProperties, remainingMissedProperties);
        }
      } else {
        const missedProperties = map(memberInfo.missedProperties, (prop) => `'${prop}'`).join(", ");
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1, memberInfo.baseTypeName, missedProperties);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2, memberInfo.typeName, memberInfo.baseTypeName, missedProperties);
        }
      }
    }
  }
  function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) {
    return baseDeclarationFlags & 64 /* Abstract */ && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent);
  }
  function getNonInheritedProperties(type, baseTypes, properties) {
    if (!length(baseTypes)) {
      return properties;
    }
    const seen = /* @__PURE__ */ new Map();
    forEach(properties, (p) => {
      seen.set(p.escapedName, p);
    });
    for (const base of baseTypes) {
      const properties2 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
      for (const prop of properties2) {
        const existing = seen.get(prop.escapedName);
        if (existing && prop.parent === existing.parent) {
          seen.delete(prop.escapedName);
        }
      }
    }
    return arrayFrom(seen.values());
  }
  function checkInheritedPropertiesAreIdentical(type, typeNode) {
    const baseTypes = getBaseTypes(type);
    if (baseTypes.length < 2) {
      return true;
    }
    const seen = /* @__PURE__ */ new Map();
    forEach(resolveDeclaredMembers(type).declaredProperties, (p) => {
      seen.set(p.escapedName, { prop: p, containingType: type });
    });
    let ok = true;
    for (const base of baseTypes) {
      const properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
      for (const prop of properties) {
        const existing = seen.get(prop.escapedName);
        if (!existing) {
          seen.set(prop.escapedName, { prop, containingType: base });
        } else {
          const isInheritedProperty = existing.containingType !== type;
          if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
            ok = false;
            const typeName1 = typeToString(existing.containingType);
            const typeName2 = typeToString(base);
            let errorInfo = chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical,
              symbolToString(prop),
              typeName1,
              typeName2
            );
            errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
            diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(typeNode), typeNode, errorInfo));
          }
        }
      }
    }
    return ok;
  }
  function checkPropertyInitialization(node) {
    if (!strictNullChecks || !strictPropertyInitialization || node.flags & 33554432 /* Ambient */) {
      return;
    }
    const constructor = findConstructorDeclaration(node);
    for (const member of node.members) {
      if (getEffectiveModifierFlags(member) & 128 /* Ambient */) {
        continue;
      }
      if (!isStatic(member) && isPropertyWithoutInitializer(member)) {
        const propName = member.name;
        if (isIdentifier(propName) || isPrivateIdentifier(propName) || isComputedPropertyName(propName)) {
          const type = getTypeOfSymbol(getSymbolOfDeclaration(member));
          if (!(type.flags & 3 /* AnyOrUnknown */ || containsUndefinedType(type))) {
            if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
              error(member.name, Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, declarationNameToString(propName));
            }
          }
        }
      }
    }
  }
  function isPropertyWithoutInitializer(node) {
    return node.kind === 172 /* PropertyDeclaration */ && !hasAbstractModifier(node) && !node.exclamationToken && !node.initializer;
  }
  function isPropertyInitializedInStaticBlocks(propName, propType, staticBlocks, startPos, endPos) {
    for (const staticBlock of staticBlocks) {
      if (staticBlock.pos >= startPos && staticBlock.pos <= endPos) {
        const reference = factory.createPropertyAccessExpression(factory.createThis(), propName);
        setParent(reference.expression, reference);
        setParent(reference, staticBlock);
        reference.flowNode = staticBlock.returnFlowNode;
        const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
        if (!containsUndefinedType(flowType)) {
          return true;
        }
      }
    }
    return false;
  }
  function isPropertyInitializedInConstructor(propName, propType, constructor) {
    const reference = isComputedPropertyName(propName) ? factory.createElementAccessExpression(factory.createThis(), propName.expression) : factory.createPropertyAccessExpression(factory.createThis(), propName);
    setParent(reference.expression, reference);
    setParent(reference, constructor);
    reference.flowNode = constructor.returnFlowNode;
    const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
    return !containsUndefinedType(flowType);
  }
  function checkInterfaceDeclaration(node) {
    if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node);
    if (!allowBlockDeclarations(node.parent)) {
      grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "interface");
    }
    checkTypeParameters(node.typeParameters);
    addLazyDiagnostic(() => {
      checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0);
      checkExportsOnMergedDeclarations(node);
      const symbol = getSymbolOfDeclaration(node);
      checkTypeParameterListsIdentical(symbol);
      const firstInterfaceDecl = getDeclarationOfKind(symbol, 264 /* InterfaceDeclaration */);
      if (node === firstInterfaceDecl) {
        const type = getDeclaredTypeOfSymbol(symbol);
        const typeWithThis = getTypeWithThisArgument(type);
        if (checkInheritedPropertiesAreIdentical(type, node.name)) {
          for (const baseType of getBaseTypes(type)) {
            checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1);
          }
          checkIndexConstraints(type, symbol);
        }
      }
      checkObjectTypeForDuplicateDeclarations(node);
    });
    forEach(getInterfaceBaseTypeNodes(node), (heritageElement) => {
      if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) {
        error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
      }
      checkTypeReferenceNode(heritageElement);
    });
    forEach(node.members, checkSourceElement);
    addLazyDiagnostic(() => {
      checkTypeForDuplicateIndexSignatures(node);
      registerForUnusedIdentifiersCheck(node);
    });
  }
  function checkTypeAliasDeclaration(node) {
    checkGrammarModifiers(node);
    checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0);
    if (!allowBlockDeclarations(node.parent)) {
      grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "type");
    }
    checkExportsOnMergedDeclarations(node);
    checkTypeParameters(node.typeParameters);
    if (node.type.kind === 141 /* IntrinsicKeyword */) {
      const typeParameterCount = length(node.typeParameters);
      const valid = typeParameterCount === 0 ? node.name.escapedText === "BuiltinIteratorReturn" : typeParameterCount === 1 && intrinsicTypeKinds.has(node.name.escapedText);
      if (!valid) {
        error(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
      }
    } else {
      checkSourceElement(node.type);
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function computeEnumMemberValues(node) {
    const nodeLinks2 = getNodeLinks(node);
    if (!(nodeLinks2.flags & 1024 /* EnumValuesComputed */)) {
      nodeLinks2.flags |= 1024 /* EnumValuesComputed */;
      let autoValue = 0;
      let previous;
      for (const member of node.members) {
        const result = computeEnumMemberValue(member, autoValue, previous);
        getNodeLinks(member).enumMemberValue = result;
        autoValue = typeof result.value === "number" ? result.value + 1 : void 0;
        previous = member;
      }
    }
  }
  function computeEnumMemberValue(member, autoValue, previous) {
    if (isComputedNonLiteralName(member.name)) {
      error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums);
    } else {
      const text = getTextOfPropertyName(member.name);
      if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
        error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name);
      }
    }
    if (member.initializer) {
      return computeConstantEnumMemberValue(member);
    }
    if (member.parent.flags & 33554432 /* Ambient */ && !isEnumConst(member.parent)) {
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (autoValue === void 0) {
      error(member.name, Diagnostics.Enum_member_must_have_initializer);
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (getIsolatedModules(compilerOptions) && (previous == null ? void 0 : previous.initializer)) {
      const prevValue = getEnumMemberValue(previous);
      if (!(typeof prevValue.value === "number" && !prevValue.resolvedOtherFiles)) {
        error(
          member.name,
          Diagnostics.Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled
        );
      }
    }
    return evaluatorResult(autoValue);
  }
  function computeConstantEnumMemberValue(member) {
    const isConstEnum = isEnumConst(member.parent);
    const initializer = member.initializer;
    const result = evaluate(initializer, member);
    if (result.value !== void 0) {
      if (isConstEnum && typeof result.value === "number" && !isFinite(result.value)) {
        error(
          initializer,
          isNaN(result.value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value
        );
      } else if (getIsolatedModules(compilerOptions) && typeof result.value === "string" && !result.isSyntacticallyString) {
        error(
          initializer,
          Diagnostics._0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled,
          `${idText(member.parent.name)}.${getTextOfPropertyName(member.name)}`
        );
      }
    } else if (isConstEnum) {
      error(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions);
    } else if (member.parent.flags & 33554432 /* Ambient */) {
      error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
    } else {
      checkTypeAssignableTo(checkExpression(initializer), numberType, initializer, Diagnostics.Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values);
    }
    return result;
  }
  function evaluateEntityNameExpression(expr, location) {
    const symbol = resolveEntityName(
      expr,
      111551 /* Value */,
      /*ignoreErrors*/
      true
    );
    if (!symbol) return evaluatorResult(
      /*value*/
      void 0
    );
    if (expr.kind === 80 /* Identifier */) {
      const identifier = expr;
      if (isInfinityOrNaNString(identifier.escapedText) && symbol === getGlobalSymbol(
        identifier.escapedText,
        111551 /* Value */,
        /*diagnostic*/
        void 0
      )) {
        return evaluatorResult(
          +identifier.escapedText,
          /*isSyntacticallyString*/
          false
        );
      }
    }
    if (symbol.flags & 8 /* EnumMember */) {
      return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration);
    }
    if (isConstantVariable(symbol)) {
      const declaration = symbol.valueDeclaration;
      if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) {
        const result = evaluate(declaration.initializer, declaration);
        if (location && getSourceFileOfNode(location) !== getSourceFileOfNode(declaration)) {
          return evaluatorResult(
            result.value,
            /*isSyntacticallyString*/
            false,
            /*resolvedOtherFiles*/
            true,
            /*hasExternalReferences*/
            true
          );
        }
        return evaluatorResult(
          result.value,
          result.isSyntacticallyString,
          result.resolvedOtherFiles,
          /*hasExternalReferences*/
          true
        );
      }
    }
    return evaluatorResult(
      /*value*/
      void 0
    );
  }
  function evaluateElementAccessExpression(expr, location) {
    const root = expr.expression;
    if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) {
      const rootSymbol = resolveEntityName(
        root,
        111551 /* Value */,
        /*ignoreErrors*/
        true
      );
      if (rootSymbol && rootSymbol.flags & 384 /* Enum */) {
        const name = escapeLeadingUnderscores(expr.argumentExpression.text);
        const member = rootSymbol.exports.get(name);
        if (member) {
          Debug.assert(getSourceFileOfNode(member.valueDeclaration) === getSourceFileOfNode(rootSymbol.valueDeclaration));
          return location ? evaluateEnumMember(expr, member, location) : getEnumMemberValue(member.valueDeclaration);
        }
      }
    }
    return evaluatorResult(
      /*value*/
      void 0
    );
  }
  function evaluateEnumMember(expr, symbol, location) {
    const declaration = symbol.valueDeclaration;
    if (!declaration || declaration === location) {
      error(expr, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(symbol));
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (!isBlockScopedNameDeclaredBeforeUse(declaration, location)) {
      error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
      return evaluatorResult(
        /*value*/
        0
      );
    }
    const value = getEnumMemberValue(declaration);
    if (location.parent !== declaration.parent) {
      return evaluatorResult(
        value.value,
        value.isSyntacticallyString,
        value.resolvedOtherFiles,
        /*hasExternalReferences*/
        true
      );
    }
    return value;
  }
  function checkEnumDeclaration(node) {
    addLazyDiagnostic(() => checkEnumDeclarationWorker(node));
  }
  function checkEnumDeclarationWorker(node) {
    checkGrammarModifiers(node);
    checkCollisionsForDeclarationName(node, node.name);
    checkExportsOnMergedDeclarations(node);
    node.members.forEach(checkEnumMember);
    computeEnumMemberValues(node);
    const enumSymbol = getSymbolOfDeclaration(node);
    const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind);
    if (node === firstDeclaration) {
      if (enumSymbol.declarations && enumSymbol.declarations.length > 1) {
        const enumIsConst = isEnumConst(node);
        forEach(enumSymbol.declarations, (decl) => {
          if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) {
            error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
          }
        });
      }
      let seenEnumMissingInitialInitializer = false;
      forEach(enumSymbol.declarations, (declaration) => {
        if (declaration.kind !== 266 /* EnumDeclaration */) {
          return false;
        }
        const enumDeclaration = declaration;
        if (!enumDeclaration.members.length) {
          return false;
        }
        const firstEnumMember = enumDeclaration.members[0];
        if (!firstEnumMember.initializer) {
          if (seenEnumMissingInitialInitializer) {
            error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
          } else {
            seenEnumMissingInitialInitializer = true;
          }
        }
      });
    }
  }
  function checkEnumMember(node) {
    if (isPrivateIdentifier(node.name)) {
      error(node, Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
    }
    if (node.initializer) {
      checkExpression(node.initializer);
    }
  }
  function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
    const declarations = symbol.declarations;
    if (declarations) {
      for (const declaration of declarations) {
        if ((declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 262 /* FunctionDeclaration */ && nodeIsPresent(declaration.body)) && !(declaration.flags & 33554432 /* Ambient */)) {
          return declaration;
        }
      }
    }
    return void 0;
  }
  function inSameLexicalScope(node1, node2) {
    const container1 = getEnclosingBlockScopeContainer(node1);
    const container2 = getEnclosingBlockScopeContainer(node2);
    if (isGlobalSourceFile(container1)) {
      return isGlobalSourceFile(container2);
    } else if (isGlobalSourceFile(container2)) {
      return false;
    } else {
      return container1 === container2;
    }
  }
  function checkModuleDeclaration(node) {
    if (node.body) {
      checkSourceElement(node.body);
      if (!isGlobalScopeAugmentation(node)) {
        registerForUnusedIdentifiersCheck(node);
      }
    }
    addLazyDiagnostic(checkModuleDeclarationDiagnostics);
    function checkModuleDeclarationDiagnostics() {
      var _a, _b;
      const isGlobalAugmentation = isGlobalScopeAugmentation(node);
      const inAmbientContext = node.flags & 33554432 /* Ambient */;
      if (isGlobalAugmentation && !inAmbientContext) {
        error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
      }
      const isAmbientExternalModule = isAmbientModule(node);
      const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module;
      if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
        return;
      }
      if (!checkGrammarModifiers(node)) {
        if (!inAmbientContext && node.name.kind === 11 /* StringLiteral */) {
          grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names);
        }
      }
      if (isIdentifier(node.name)) {
        checkCollisionsForDeclarationName(node, node.name);
        if (!(node.flags & (32 /* Namespace */ | 2048 /* GlobalAugmentation */))) {
          const sourceFile = getSourceFileOfNode(node);
          const pos = getNonModifierTokenPosOfNode(node);
          const span = getSpanOfTokenAtPosition(sourceFile, pos);
          suggestionDiagnostics.add(
            createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead)
          );
        }
      }
      checkExportsOnMergedDeclarations(node);
      const symbol = getSymbolOfDeclaration(node);
      if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions))) {
        if (getIsolatedModules(compilerOptions) && !getSourceFileOfNode(node).externalModuleIndicator) {
          error(node.name, Diagnostics.Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement, isolatedModulesLikeFlagName);
        }
        if (((_a = symbol.declarations) == null ? void 0 : _a.length) > 1) {
          const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
          if (firstNonAmbientClassOrFunc) {
            if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
              error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
            } else if (node.pos < firstNonAmbientClassOrFunc.pos) {
              error(node.name, Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
            }
          }
          const mergedClass = getDeclarationOfKind(symbol, 263 /* ClassDeclaration */);
          if (mergedClass && inSameLexicalScope(node, mergedClass)) {
            getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */;
          }
        }
        if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(node.parent) === 1 /* CommonJS */) {
          const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m) => m.kind === 95 /* ExportKeyword */);
          if (exportModifier) {
            error(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
          }
        }
      }
      if (isAmbientExternalModule) {
        if (isExternalModuleAugmentation(node)) {
          const checkBody = isGlobalAugmentation || getSymbolOfDeclaration(node).flags & 33554432 /* Transient */;
          if (checkBody && node.body) {
            for (const statement of node.body.statements) {
              checkModuleAugmentationElement(statement, isGlobalAugmentation);
            }
          }
        } else if (isGlobalSourceFile(node.parent)) {
          if (isGlobalAugmentation) {
            error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
          } else if (isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(node.name))) {
            error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
          }
        } else {
          if (isGlobalAugmentation) {
            error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
          } else {
            error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
          }
        }
      }
    }
  }
  function checkModuleAugmentationElement(node, isGlobalAugmentation) {
    switch (node.kind) {
      case 243 /* VariableStatement */:
        for (const decl of node.declarationList.declarations) {
          checkModuleAugmentationElement(decl, isGlobalAugmentation);
        }
        break;
      case 277 /* ExportAssignment */:
      case 278 /* ExportDeclaration */:
        grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
        break;
      case 271 /* ImportEqualsDeclaration */:
        if (isInternalModuleImportEqualsDeclaration(node)) break;
      // falls through
      case 272 /* ImportDeclaration */:
        grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
        break;
      case 208 /* BindingElement */:
      case 260 /* VariableDeclaration */:
        const name = node.name;
        if (isBindingPattern(name)) {
          for (const el of name.elements) {
            checkModuleAugmentationElement(el, isGlobalAugmentation);
          }
          break;
        }
      // falls through
      case 263 /* ClassDeclaration */:
      case 266 /* EnumDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 267 /* ModuleDeclaration */:
      case 265 /* TypeAliasDeclaration */:
        if (isGlobalAugmentation) {
          return;
        }
        break;
    }
  }
  function getFirstNonModuleExportsIdentifier(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return node;
      case 166 /* QualifiedName */:
        do {
          node = node.left;
        } while (node.kind !== 80 /* Identifier */);
        return node;
      case 211 /* PropertyAccessExpression */:
        do {
          if (isModuleExportsAccessExpression(node.expression) && !isPrivateIdentifier(node.name)) {
            return node.name;
          }
          node = node.expression;
        } while (node.kind !== 80 /* Identifier */);
        return node;
    }
  }
  function checkExternalImportOrExportDeclaration(node) {
    const moduleName = getExternalModuleName(node);
    if (!moduleName || nodeIsMissing(moduleName)) {
      return false;
    }
    if (!isStringLiteral(moduleName)) {
      error(moduleName, Diagnostics.String_literal_expected);
      return false;
    }
    const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent);
    if (node.parent.kind !== 307 /* SourceFile */ && !inAmbientExternalModule) {
      error(
        moduleName,
        node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module
      );
      return false;
    }
    if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) {
      if (!isTopLevelInExternalModuleAugmentation(node)) {
        error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
        return false;
      }
    }
    if (!isImportEqualsDeclaration(node) && node.attributes) {
      const diagnostic = node.attributes.token === 118 /* WithKeyword */ ? Diagnostics.Import_attribute_values_must_be_string_literal_expressions : Diagnostics.Import_assertion_values_must_be_string_literal_expressions;
      let hasError = false;
      for (const attr of node.attributes.elements) {
        if (!isStringLiteral(attr.value)) {
          hasError = true;
          error(attr.value, diagnostic);
        }
      }
      return !hasError;
    }
    return true;
  }
  function checkModuleExportName(name, allowStringLiteral = true) {
    if (name === void 0 || name.kind !== 11 /* StringLiteral */) {
      return;
    }
    if (!allowStringLiteral) {
      grammarErrorOnNode(name, Diagnostics.Identifier_expected);
    } else if (moduleKind === 5 /* ES2015 */ || moduleKind === 6 /* ES2020 */) {
      grammarErrorOnNode(name, Diagnostics.String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020);
    }
  }
  function checkAliasSymbol(node) {
    var _a, _b, _c, _d;
    let symbol = getSymbolOfDeclaration(node);
    const target = resolveAlias(symbol);
    if (target !== unknownSymbol) {
      symbol = getMergedSymbol(symbol.exportSymbol || symbol);
      if (isInJSFile(node) && !(target.flags & 111551 /* Value */) && !isTypeOnlyImportOrExportDeclaration(node)) {
        const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : isNamedDeclaration(node) ? node.name : node;
        Debug.assert(node.kind !== 280 /* NamespaceExport */);
        if (node.kind === 281 /* ExportSpecifier */) {
          const diag2 = error(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files);
          const alreadyExportedSymbol = (_b = (_a = getSourceFileOfNode(node).symbol) == null ? void 0 : _a.exports) == null ? void 0 : _b.get(moduleExportNameTextEscaped(node.propertyName || node.name));
          if (alreadyExportedSymbol === target) {
            const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode);
            if (exportingDeclaration) {
              addRelatedInfo(
                diag2,
                createDiagnosticForNode(
                  exportingDeclaration,
                  Diagnostics._0_is_automatically_exported_here,
                  unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName)
                )
              );
            }
          }
        } else {
          Debug.assert(node.kind !== 260 /* VariableDeclaration */);
          const importDeclaration = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration));
          const moduleSpecifier = (importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) ?? "...";
          const importedIdentifier = unescapeLeadingUnderscores(isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName);
          error(
            errorNode,
            Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation,
            importedIdentifier,
            `import("${moduleSpecifier}").${importedIdentifier}`
          );
        }
        return;
      }
      const targetFlags = getSymbolFlags(target);
      const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
      if (targetFlags & excludedMeanings) {
        const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
        error(node, message, symbolToString(symbol));
      } else if (node.kind !== 281 /* ExportSpecifier */) {
        const appearsValueyToTranspiler = compilerOptions.isolatedModules && !findAncestor(node, isTypeOnlyImportOrExportDeclaration);
        if (appearsValueyToTranspiler && symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */)) {
          error(
            node,
            Diagnostics.Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled,
            symbolToString(symbol),
            isolatedModulesLikeFlagName
          );
        }
      }
      if (getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */)) {
        const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol);
        const isType = !(targetFlags & 111551 /* Value */);
        if (isType || typeOnlyAlias) {
          switch (node.kind) {
            case 273 /* ImportClause */:
            case 276 /* ImportSpecifier */:
            case 271 /* ImportEqualsDeclaration */: {
              if (compilerOptions.verbatimModuleSyntax) {
                Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name");
                const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled;
                const name = moduleExportNameTextUnescaped(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name);
                addTypeOnlyDeclarationRelatedInfo(
                  error(node, message, name),
                  isType ? void 0 : typeOnlyAlias,
                  name
                );
              }
              if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 32 /* Export */)) {
                error(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName);
              }
              break;
            }
            case 281 /* ExportSpecifier */: {
              if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) {
                const name = moduleExportNameTextUnescaped(node.propertyName || node.name);
                const diagnostic = isType ? error(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName);
                addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name);
                break;
              }
            }
          }
        }
        if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) {
          error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
        } else if (moduleKind === 200 /* Preserve */ && node.kind !== 271 /* ImportEqualsDeclaration */ && node.kind !== 260 /* VariableDeclaration */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) {
          error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve);
        }
        if (compilerOptions.verbatimModuleSyntax && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */) && targetFlags & 128 /* ConstEnum */) {
          const constEnumDeclaration = target.valueDeclaration;
          const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
          if (constEnumDeclaration.flags & 33554432 /* Ambient */ && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
            error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName);
          }
        }
      }
      if (isImportSpecifier(node)) {
        const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node);
        if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) {
          addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName);
        }
      }
    }
  }
  function resolveAliasWithDeprecationCheck(symbol, location) {
    if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) {
      return symbol;
    }
    const targetSymbol = resolveAlias(symbol);
    if (targetSymbol === unknownSymbol) return targetSymbol;
    while (symbol.flags & 2097152 /* Alias */) {
      const target = getImmediateAliasedSymbol(symbol);
      if (target) {
        if (target === targetSymbol) break;
        if (target.declarations && length(target.declarations)) {
          if (isDeprecatedSymbol(target)) {
            addDeprecatedSuggestion(location, target.declarations, target.escapedName);
            break;
          } else {
            if (symbol === targetSymbol) break;
            symbol = target;
          }
        }
      } else {
        break;
      }
    }
    return targetSymbol;
  }
  function checkImportBinding(node) {
    checkCollisionsForDeclarationName(node, node.name);
    checkAliasSymbol(node);
    if (node.kind === 276 /* ImportSpecifier */) {
      checkModuleExportName(node.propertyName);
      if (moduleExportNameIsDefault(node.propertyName || node.name) && getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) {
        checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
      }
    }
  }
  function checkImportAttributes(declaration) {
    var _a;
    const node = declaration.attributes;
    if (node) {
      const importAttributesType = getGlobalImportAttributesType(
        /*reportErrors*/
        true
      );
      if (importAttributesType !== emptyObjectType) {
        checkTypeAssignableTo(getTypeFromImportAttributes(node), getNullableType(importAttributesType, 32768 /* Undefined */), node);
      }
      const validForTypeAttributes = isExclusivelyTypeOnlyImportOrExport(declaration);
      const override = getResolutionModeOverride(node, validForTypeAttributes ? grammarErrorOnNode : void 0);
      const isImportAttributes2 = declaration.attributes.token === 118 /* WithKeyword */;
      if (validForTypeAttributes && override) {
        return;
      }
      const mode = moduleKind === 199 /* NodeNext */ && declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier);
      if (mode !== 99 /* ESNext */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 200 /* Preserve */) {
        const message = isImportAttributes2 ? moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve : moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve;
        return grammarErrorOnNode(node, message);
      }
      const isTypeOnly = isJSDocImportTag(declaration) || (isImportDeclaration(declaration) ? (_a = declaration.importClause) == null ? void 0 : _a.isTypeOnly : declaration.isTypeOnly);
      if (isTypeOnly) {
        return grammarErrorOnNode(node, isImportAttributes2 ? Diagnostics.Import_attributes_cannot_be_used_with_type_only_imports_or_exports : Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports);
      }
      if (override) {
        return grammarErrorOnNode(node, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports);
      }
    }
  }
  function checkImportAttribute(node) {
    return getRegularTypeOfLiteralType(checkExpressionCached(node.value));
  }
  function checkImportDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    if (!checkGrammarModifiers(node) && node.modifiers) {
      grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers);
    }
    if (checkExternalImportOrExportDeclaration(node)) {
      let resolvedModule;
      const importClause = node.importClause;
      if (importClause && !checkGrammarImportClause(importClause)) {
        if (importClause.name) {
          checkImportBinding(importClause);
        }
        if (importClause.namedBindings) {
          if (importClause.namedBindings.kind === 274 /* NamespaceImport */) {
            checkImportBinding(importClause.namedBindings);
            if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && getESModuleInterop(compilerOptions)) {
              checkExternalEmitHelpers(node, 65536 /* ImportStar */);
            }
          } else {
            resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
            if (resolvedModule) {
              forEach(importClause.namedBindings.elements, checkImportBinding);
            }
          }
        }
        if (!importClause.isTypeOnly && moduleKind === 199 /* NodeNext */ && isOnlyImportableAsDefault(node.moduleSpecifier, resolvedModule) && !hasTypeJsonImportAttribute(node)) {
          error(node.moduleSpecifier, Diagnostics.Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_module_is_set_to_0, ModuleKind[moduleKind]);
        }
      } else if (noUncheckedSideEffectImports && !importClause) {
        void resolveExternalModuleName(node, node.moduleSpecifier);
      }
    }
    checkImportAttributes(node);
  }
  function hasTypeJsonImportAttribute(node) {
    return !!node.attributes && node.attributes.elements.some((attr) => {
      var _a;
      return getTextOfIdentifierOrLiteral(attr.name) === "type" && ((_a = tryCast(attr.value, isStringLiteralLike)) == null ? void 0 : _a.text) === "json";
    });
  }
  function checkImportEqualsDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    checkGrammarModifiers(node);
    if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
      checkImportBinding(node);
      markLinkedReferences(node, 6 /* ExportImportEquals */);
      if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) {
        const target = resolveAlias(getSymbolOfDeclaration(node));
        if (target !== unknownSymbol) {
          const targetFlags = getSymbolFlags(target);
          if (targetFlags & 111551 /* Value */) {
            const moduleName = getFirstIdentifier(node.moduleReference);
            if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
              error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName));
            }
          }
          if (targetFlags & 788968 /* Type */) {
            checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0);
          }
        }
        if (node.isTypeOnly) {
          grammarErrorOnNode(node, Diagnostics.An_import_alias_cannot_use_import_type);
        }
      } else {
        if (5 /* ES2015 */ <= moduleKind && moduleKind <= 99 /* ESNext */ && !node.isTypeOnly && !(node.flags & 33554432 /* Ambient */)) {
          grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
        }
      }
    }
  }
  function checkExportDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    if (!checkGrammarModifiers(node) && hasSyntacticModifiers(node)) {
      grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers);
    }
    checkGrammarExportDeclaration(node);
    if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
      if (node.exportClause && !isNamespaceExport(node.exportClause)) {
        forEach(node.exportClause.elements, checkExportSpecifier);
        const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent);
        const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 268 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 33554432 /* Ambient */;
        if (node.parent.kind !== 307 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
          error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
        }
      } else {
        const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
        if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
          error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
        } else if (node.exportClause) {
          checkAliasSymbol(node.exportClause);
          checkModuleExportName(node.exportClause.name);
        }
        if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) {
          if (node.exportClause) {
            if (getESModuleInterop(compilerOptions)) {
              checkExternalEmitHelpers(node, 65536 /* ImportStar */);
            }
          } else {
            checkExternalEmitHelpers(node, 32768 /* ExportStar */);
          }
        }
      }
    }
    checkImportAttributes(node);
  }
  function checkGrammarExportDeclaration(node) {
    var _a;
    if (node.isTypeOnly && ((_a = node.exportClause) == null ? void 0 : _a.kind) === 279 /* NamedExports */) {
      return checkGrammarNamedImportsOrExports(node.exportClause);
    }
    return false;
  }
  function checkGrammarModuleElementContext(node, errorMessage) {
    const isInAppropriateContext = node.parent.kind === 307 /* SourceFile */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 267 /* ModuleDeclaration */;
    if (!isInAppropriateContext) {
      grammarErrorOnFirstToken(node, errorMessage);
    }
    return !isInAppropriateContext;
  }
  function checkExportSpecifier(node) {
    checkAliasSymbol(node);
    const hasModuleSpecifier = node.parent.parent.moduleSpecifier !== void 0;
    checkModuleExportName(node.propertyName, hasModuleSpecifier);
    checkModuleExportName(node.name);
    if (getEmitDeclarations(compilerOptions)) {
      collectLinkedAliases(
        node.propertyName || node.name,
        /*setVisibility*/
        true
      );
    }
    if (!hasModuleSpecifier) {
      const exportedName = node.propertyName || node.name;
      if (exportedName.kind === 11 /* StringLiteral */) {
        return;
      }
      const symbol = resolveName(
        exportedName,
        exportedName.escapedText,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
        error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName));
      } else {
        markLinkedReferences(node, 7 /* ExportSpecifier */);
      }
    } else {
      if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && moduleExportNameIsDefault(node.propertyName || node.name)) {
        checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
      }
    }
  }
  function checkExportAssignment(node) {
    const illegalContextMessage = node.isExportEquals ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration;
    if (checkGrammarModuleElementContext(node, illegalContextMessage)) {
      return;
    }
    const container = node.parent.kind === 307 /* SourceFile */ ? node.parent : node.parent.parent;
    if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) {
      if (node.isExportEquals) {
        error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
      } else {
        error(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
      }
      return;
    }
    if (!checkGrammarModifiers(node) && hasEffectiveModifiers(node)) {
      grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers);
    }
    const typeAnnotationNode = getEffectiveTypeAnnotationNode(node);
    if (typeAnnotationNode) {
      checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression);
    }
    const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */;
    if (node.expression.kind === 80 /* Identifier */) {
      const id = node.expression;
      const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(
        id,
        -1 /* All */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        node
      ));
      if (sym) {
        markLinkedReferences(node, 3 /* ExportAssignment */);
        const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(sym, 111551 /* Value */);
        if (getSymbolFlags(sym) & 111551 /* Value */) {
          checkExpressionCached(id);
          if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && typeOnlyDeclaration) {
            error(
              id,
              node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration,
              idText(id)
            );
          }
        } else if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax) {
          error(
            id,
            node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type,
            idText(id)
          );
        }
        if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && getIsolatedModules(compilerOptions) && !(sym.flags & 111551 /* Value */)) {
          const nonLocalMeanings = getSymbolFlags(
            sym,
            /*excludeTypeOnlyMeanings*/
            false,
            /*excludeLocalMeanings*/
            true
          );
          if (sym.flags & 2097152 /* Alias */ && nonLocalMeanings & 788968 /* Type */ && !(nonLocalMeanings & 111551 /* Value */) && (!typeOnlyDeclaration || getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node))) {
            error(
              id,
              node.isExportEquals ? Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default,
              idText(id),
              isolatedModulesLikeFlagName
            );
          } else if (typeOnlyDeclaration && getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node)) {
            addTypeOnlyDeclarationRelatedInfo(
              error(
                id,
                node.isExportEquals ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default,
                idText(id),
                isolatedModulesLikeFlagName
              ),
              typeOnlyDeclaration,
              idText(id)
            );
          }
        }
      } else {
        checkExpressionCached(id);
      }
      if (getEmitDeclarations(compilerOptions)) {
        collectLinkedAliases(
          id,
          /*setVisibility*/
          true
        );
      }
    } else {
      checkExpressionCached(node.expression);
    }
    if (isIllegalExportDefaultInCJS) {
      error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
    }
    checkExternalModuleExports(container);
    if (node.flags & 33554432 /* Ambient */ && !isEntityNameExpression(node.expression)) {
      grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
    }
    if (node.isExportEquals) {
      if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) {
        grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
      } else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */)) {
        grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
      }
    }
  }
  function hasExportedMembers(moduleSymbol) {
    return forEachEntry(moduleSymbol.exports, (_, id) => id !== "export=");
  }
  function checkExternalModuleExports(node) {
    const moduleSymbol = getSymbolOfDeclaration(node);
    const links = getSymbolLinks(moduleSymbol);
    if (!links.exportsChecked) {
      const exportEqualsSymbol = moduleSymbol.exports.get("export=");
      if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
        const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
        if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) {
          error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
        }
      }
      const exports2 = getExportsOfModule(moduleSymbol);
      if (exports2) {
        exports2.forEach(({ declarations, flags }, id) => {
          if (id === "__export") {
            return;
          }
          if (flags & (1920 /* Namespace */ | 384 /* Enum */)) {
            return;
          }
          const exportedDeclarationsCount = countWhere(declarations, and(isNotOverloadAndNotAccessor, not(isInterfaceDeclaration)));
          if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
            return;
          }
          if (exportedDeclarationsCount > 1) {
            if (!isDuplicatedCommonJSExport(declarations)) {
              for (const declaration of declarations) {
                if (isNotOverload(declaration)) {
                  diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id)));
                }
              }
            }
          }
        });
      }
      links.exportsChecked = true;
    }
  }
  function isDuplicatedCommonJSExport(declarations) {
    return declarations && declarations.length > 1 && declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression)));
  }
  function checkSourceElement(node) {
    if (node) {
      const saveCurrentNode = currentNode;
      currentNode = node;
      instantiationCount = 0;
      checkSourceElementWorker(node);
      currentNode = saveCurrentNode;
    }
  }
  function checkSourceElementWorker(node) {
    if (getNodeCheckFlags(node) & 8388608 /* PartiallyTypeChecked */) {
      return;
    }
    if (canHaveJSDoc(node)) {
      forEach(node.jsDoc, ({ comment, tags }) => {
        checkJSDocCommentWorker(comment);
        forEach(tags, (tag) => {
          checkJSDocCommentWorker(tag.comment);
          if (isInJSFile(node)) {
            checkSourceElement(tag);
          }
        });
      });
    }
    const kind = node.kind;
    if (cancellationToken) {
      switch (kind) {
        case 267 /* ModuleDeclaration */:
        case 263 /* ClassDeclaration */:
        case 264 /* InterfaceDeclaration */:
        case 262 /* FunctionDeclaration */:
          cancellationToken.throwIfCancellationRequested();
      }
    }
    if (kind >= 243 /* FirstStatement */ && kind <= 259 /* LastStatement */ && canHaveFlowNode(node) && node.flowNode && !isReachableFlowNode(node.flowNode)) {
      errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, Diagnostics.Unreachable_code_detected);
    }
    switch (kind) {
      case 168 /* TypeParameter */:
        return checkTypeParameter(node);
      case 169 /* Parameter */:
        return checkParameter(node);
      case 172 /* PropertyDeclaration */:
        return checkPropertyDeclaration(node);
      case 171 /* PropertySignature */:
        return checkPropertySignature(node);
      case 185 /* ConstructorType */:
      case 184 /* FunctionType */:
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 181 /* IndexSignature */:
        return checkSignatureDeclaration(node);
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        return checkMethodDeclaration(node);
      case 175 /* ClassStaticBlockDeclaration */:
        return checkClassStaticBlockDeclaration(node);
      case 176 /* Constructor */:
        return checkConstructorDeclaration(node);
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return checkAccessorDeclaration(node);
      case 183 /* TypeReference */:
        return checkTypeReferenceNode(node);
      case 182 /* TypePredicate */:
        return checkTypePredicate(node);
      case 186 /* TypeQuery */:
        return checkTypeQuery(node);
      case 187 /* TypeLiteral */:
        return checkTypeLiteral(node);
      case 188 /* ArrayType */:
        return checkArrayType(node);
      case 189 /* TupleType */:
        return checkTupleType(node);
      case 192 /* UnionType */:
      case 193 /* IntersectionType */:
        return checkUnionOrIntersectionType(node);
      case 196 /* ParenthesizedType */:
      case 190 /* OptionalType */:
      case 191 /* RestType */:
        return checkSourceElement(node.type);
      case 197 /* ThisType */:
        return checkThisType(node);
      case 198 /* TypeOperator */:
        return checkTypeOperator(node);
      case 194 /* ConditionalType */:
        return checkConditionalType(node);
      case 195 /* InferType */:
        return checkInferType(node);
      case 203 /* TemplateLiteralType */:
        return checkTemplateLiteralType(node);
      case 205 /* ImportType */:
        return checkImportType(node);
      case 202 /* NamedTupleMember */:
        return checkNamedTupleMember(node);
      case 328 /* JSDocAugmentsTag */:
        return checkJSDocAugmentsTag(node);
      case 329 /* JSDocImplementsTag */:
        return checkJSDocImplementsTag(node);
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
      case 340 /* JSDocEnumTag */:
        return checkJSDocTypeAliasTag(node);
      case 345 /* JSDocTemplateTag */:
        return checkJSDocTemplateTag(node);
      case 344 /* JSDocTypeTag */:
        return checkJSDocTypeTag(node);
      case 324 /* JSDocLink */:
      case 325 /* JSDocLinkCode */:
      case 326 /* JSDocLinkPlain */:
        return checkJSDocLinkLikeTag(node);
      case 341 /* JSDocParameterTag */:
        return checkJSDocParameterTag(node);
      case 348 /* JSDocPropertyTag */:
        return checkJSDocPropertyTag(node);
      case 317 /* JSDocFunctionType */:
        checkJSDocFunctionType(node);
      // falls through
      case 315 /* JSDocNonNullableType */:
      case 314 /* JSDocNullableType */:
      case 312 /* JSDocAllType */:
      case 313 /* JSDocUnknownType */:
      case 322 /* JSDocTypeLiteral */:
        checkJSDocTypeIsInJsFile(node);
        forEachChild(node, checkSourceElement);
        return;
      case 318 /* JSDocVariadicType */:
        checkJSDocVariadicType(node);
        return;
      case 309 /* JSDocTypeExpression */:
        return checkSourceElement(node.type);
      case 333 /* JSDocPublicTag */:
      case 335 /* JSDocProtectedTag */:
      case 334 /* JSDocPrivateTag */:
        return checkJSDocAccessibilityModifiers(node);
      case 350 /* JSDocSatisfiesTag */:
        return checkJSDocSatisfiesTag(node);
      case 343 /* JSDocThisTag */:
        return checkJSDocThisTag(node);
      case 351 /* JSDocImportTag */:
        return checkJSDocImportTag(node);
      case 199 /* IndexedAccessType */:
        return checkIndexedAccessType(node);
      case 200 /* MappedType */:
        return checkMappedType(node);
      case 262 /* FunctionDeclaration */:
        return checkFunctionDeclaration(node);
      case 241 /* Block */:
      case 268 /* ModuleBlock */:
        return checkBlock(node);
      case 243 /* VariableStatement */:
        return checkVariableStatement(node);
      case 244 /* ExpressionStatement */:
        return checkExpressionStatement(node);
      case 245 /* IfStatement */:
        return checkIfStatement(node);
      case 246 /* DoStatement */:
        return checkDoStatement(node);
      case 247 /* WhileStatement */:
        return checkWhileStatement(node);
      case 248 /* ForStatement */:
        return checkForStatement(node);
      case 249 /* ForInStatement */:
        return checkForInStatement(node);
      case 250 /* ForOfStatement */:
        return checkForOfStatement(node);
      case 251 /* ContinueStatement */:
      case 252 /* BreakStatement */:
        return checkBreakOrContinueStatement(node);
      case 253 /* ReturnStatement */:
        return checkReturnStatement(node);
      case 254 /* WithStatement */:
        return checkWithStatement(node);
      case 255 /* SwitchStatement */:
        return checkSwitchStatement(node);
      case 256 /* LabeledStatement */:
        return checkLabeledStatement(node);
      case 257 /* ThrowStatement */:
        return checkThrowStatement(node);
      case 258 /* TryStatement */:
        return checkTryStatement(node);
      case 260 /* VariableDeclaration */:
        return checkVariableDeclaration(node);
      case 208 /* BindingElement */:
        return checkBindingElement(node);
      case 263 /* ClassDeclaration */:
        return checkClassDeclaration(node);
      case 264 /* InterfaceDeclaration */:
        return checkInterfaceDeclaration(node);
      case 265 /* TypeAliasDeclaration */:
        return checkTypeAliasDeclaration(node);
      case 266 /* EnumDeclaration */:
        return checkEnumDeclaration(node);
      case 267 /* ModuleDeclaration */:
        return checkModuleDeclaration(node);
      case 272 /* ImportDeclaration */:
        return checkImportDeclaration(node);
      case 271 /* ImportEqualsDeclaration */:
        return checkImportEqualsDeclaration(node);
      case 278 /* ExportDeclaration */:
        return checkExportDeclaration(node);
      case 277 /* ExportAssignment */:
        return checkExportAssignment(node);
      case 242 /* EmptyStatement */:
      case 259 /* DebuggerStatement */:
        checkGrammarStatementInAmbientContext(node);
        return;
      case 282 /* MissingDeclaration */:
        return checkMissingDeclaration(node);
    }
  }
  function checkJSDocCommentWorker(node) {
    if (isArray(node)) {
      forEach(node, (tag) => {
        if (isJSDocLinkLike(tag)) {
          checkSourceElement(tag);
        }
      });
    }
  }
  function checkJSDocTypeIsInJsFile(node) {
    if (!isInJSFile(node)) {
      if (isJSDocNonNullableType(node) || isJSDocNullableType(node)) {
        const token = tokenToString(isJSDocNonNullableType(node) ? 54 /* ExclamationToken */ : 58 /* QuestionToken */);
        const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1;
        const typeNode = node.type;
        const type = getTypeFromTypeNode(typeNode);
        grammarErrorOnNode(
          node,
          diagnostic,
          token,
          typeToString(
            isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type
          )
        );
      } else {
        grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
      }
    }
  }
  function checkJSDocVariadicType(node) {
    checkJSDocTypeIsInJsFile(node);
    checkSourceElement(node.type);
    const { parent } = node;
    if (isParameter(parent) && isJSDocFunctionType(parent.parent)) {
      if (last(parent.parent.parameters) !== parent) {
        error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
      }
      return;
    }
    if (!isJSDocTypeExpression(parent)) {
      error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
    }
    const paramTag = node.parent.parent;
    if (!isJSDocParameterTag(paramTag)) {
      error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
      return;
    }
    const param = getParameterSymbolFromJSDoc(paramTag);
    if (!param) {
      return;
    }
    const host2 = getHostSignatureFromJSDoc(paramTag);
    if (!host2 || last(host2.parameters).symbol !== param) {
      error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
    }
  }
  function getTypeFromJSDocVariadicType(node) {
    const type = getTypeFromTypeNode(node.type);
    const { parent } = node;
    const paramTag = node.parent.parent;
    if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) {
      const host2 = getHostSignatureFromJSDoc(paramTag);
      const isCallbackTag = isJSDocCallbackTag(paramTag.parent.parent);
      if (host2 || isCallbackTag) {
        const lastParamDeclaration = isCallbackTag ? lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) : lastOrUndefined(host2.parameters);
        const symbol = getParameterSymbolFromJSDoc(paramTag);
        if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration)) {
          return createArrayType(type);
        }
      }
    }
    if (isParameter(parent) && isJSDocFunctionType(parent.parent)) {
      return createArrayType(type);
    }
    return addOptionality(type);
  }
  function checkNodeDeferred(node) {
    const enclosingFile = getSourceFileOfNode(node);
    const links = getNodeLinks(enclosingFile);
    if (!(links.flags & 1 /* TypeChecked */)) {
      links.deferredNodes || (links.deferredNodes = /* @__PURE__ */ new Set());
      links.deferredNodes.add(node);
    } else {
      Debug.assert(!links.deferredNodes, "A type-checked file should have no deferred nodes.");
    }
  }
  function checkDeferredNodes(context) {
    const links = getNodeLinks(context);
    if (links.deferredNodes) {
      links.deferredNodes.forEach(checkDeferredNode);
    }
    links.deferredNodes = void 0;
  }
  function checkDeferredNode(node) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    const saveCurrentNode = currentNode;
    currentNode = node;
    instantiationCount = 0;
    switch (node.kind) {
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
      case 215 /* TaggedTemplateExpression */:
      case 170 /* Decorator */:
      case 286 /* JsxOpeningElement */:
        resolveUntypedCall(node);
        break;
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
        break;
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        checkAccessorDeclaration(node);
        break;
      case 231 /* ClassExpression */:
        checkClassExpressionDeferred(node);
        break;
      case 168 /* TypeParameter */:
        checkTypeParameterDeferred(node);
        break;
      case 285 /* JsxSelfClosingElement */:
        checkJsxSelfClosingElementDeferred(node);
        break;
      case 284 /* JsxElement */:
        checkJsxElementDeferred(node);
        break;
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
      case 217 /* ParenthesizedExpression */:
        checkAssertionDeferred(node);
        break;
      case 222 /* VoidExpression */:
        checkExpression(node.expression);
        break;
      case 226 /* BinaryExpression */:
        if (isInstanceOfExpression(node)) {
          resolveUntypedCall(node);
        }
        break;
    }
    currentNode = saveCurrentNode;
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  function checkSourceFile(node, nodesToCheck) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(
      tracing.Phase.Check,
      nodesToCheck ? "checkSourceFileNodes" : "checkSourceFile",
      { path: node.path },
      /*separateBeginAndEnd*/
      true
    );
    const beforeMark = nodesToCheck ? "beforeCheckNodes" : "beforeCheck";
    const afterMark = nodesToCheck ? "afterCheckNodes" : "afterCheck";
    mark(beforeMark);
    nodesToCheck ? checkSourceFileNodesWorker(node, nodesToCheck) : checkSourceFileWorker(node);
    mark(afterMark);
    measure("Check", beforeMark, afterMark);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  function unusedIsError(kind, isAmbient) {
    if (isAmbient) {
      return false;
    }
    switch (kind) {
      case 0 /* Local */:
        return !!compilerOptions.noUnusedLocals;
      case 1 /* Parameter */:
        return !!compilerOptions.noUnusedParameters;
      default:
        return Debug.assertNever(kind);
    }
  }
  function getPotentiallyUnusedIdentifiers(sourceFile) {
    return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || emptyArray;
  }
  function checkSourceFileWorker(node) {
    const links = getNodeLinks(node);
    if (!(links.flags & 1 /* TypeChecked */)) {
      if (skipTypeChecking(node, compilerOptions, host)) {
        return;
      }
      checkGrammarSourceFile(node);
      clear(potentialThisCollisions);
      clear(potentialNewTargetCollisions);
      clear(potentialWeakMapSetCollisions);
      clear(potentialReflectCollisions);
      clear(potentialUnusedRenamedBindingElementsInTypes);
      if (links.flags & 8388608 /* PartiallyTypeChecked */) {
        potentialThisCollisions = links.potentialThisCollisions;
        potentialNewTargetCollisions = links.potentialNewTargetCollisions;
        potentialWeakMapSetCollisions = links.potentialWeakMapSetCollisions;
        potentialReflectCollisions = links.potentialReflectCollisions;
        potentialUnusedRenamedBindingElementsInTypes = links.potentialUnusedRenamedBindingElementsInTypes;
      }
      forEach(node.statements, checkSourceElement);
      checkSourceElement(node.endOfFileToken);
      checkDeferredNodes(node);
      if (isExternalOrCommonJsModule(node)) {
        registerForUnusedIdentifiersCheck(node);
      }
      addLazyDiagnostic(() => {
        if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
          checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag2) => {
            if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) {
              diagnostics.add(diag2);
            }
          });
        }
        if (!node.isDeclarationFile) {
          checkPotentialUncheckedRenamedBindingElementsInTypes();
        }
      });
      if (isExternalOrCommonJsModule(node)) {
        checkExternalModuleExports(node);
      }
      if (potentialThisCollisions.length) {
        forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
        clear(potentialThisCollisions);
      }
      if (potentialNewTargetCollisions.length) {
        forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
        clear(potentialNewTargetCollisions);
      }
      if (potentialWeakMapSetCollisions.length) {
        forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision);
        clear(potentialWeakMapSetCollisions);
      }
      if (potentialReflectCollisions.length) {
        forEach(potentialReflectCollisions, checkReflectCollision);
        clear(potentialReflectCollisions);
      }
      links.flags |= 1 /* TypeChecked */;
    }
  }
  function checkSourceFileNodesWorker(file, nodes) {
    const links = getNodeLinks(file);
    if (!(links.flags & 1 /* TypeChecked */)) {
      if (skipTypeChecking(file, compilerOptions, host)) {
        return;
      }
      checkGrammarSourceFile(file);
      clear(potentialThisCollisions);
      clear(potentialNewTargetCollisions);
      clear(potentialWeakMapSetCollisions);
      clear(potentialReflectCollisions);
      clear(potentialUnusedRenamedBindingElementsInTypes);
      forEach(nodes, checkSourceElement);
      checkDeferredNodes(file);
      (links.potentialThisCollisions || (links.potentialThisCollisions = [])).push(...potentialThisCollisions);
      (links.potentialNewTargetCollisions || (links.potentialNewTargetCollisions = [])).push(...potentialNewTargetCollisions);
      (links.potentialWeakMapSetCollisions || (links.potentialWeakMapSetCollisions = [])).push(...potentialWeakMapSetCollisions);
      (links.potentialReflectCollisions || (links.potentialReflectCollisions = [])).push(...potentialReflectCollisions);
      (links.potentialUnusedRenamedBindingElementsInTypes || (links.potentialUnusedRenamedBindingElementsInTypes = [])).push(
        ...potentialUnusedRenamedBindingElementsInTypes
      );
      links.flags |= 8388608 /* PartiallyTypeChecked */;
      for (const node of nodes) {
        const nodeLinks2 = getNodeLinks(node);
        nodeLinks2.flags |= 8388608 /* PartiallyTypeChecked */;
      }
    }
  }
  function getDiagnostics(sourceFile, ct, nodesToCheck) {
    try {
      cancellationToken = ct;
      return getDiagnosticsWorker(sourceFile, nodesToCheck);
    } finally {
      cancellationToken = void 0;
    }
  }
  function ensurePendingDiagnosticWorkComplete() {
    for (const cb of deferredDiagnosticsCallbacks) {
      cb();
    }
    deferredDiagnosticsCallbacks = [];
  }
  function checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck) {
    ensurePendingDiagnosticWorkComplete();
    const oldAddLazyDiagnostics = addLazyDiagnostic;
    addLazyDiagnostic = (cb) => cb();
    checkSourceFile(sourceFile, nodesToCheck);
    addLazyDiagnostic = oldAddLazyDiagnostics;
  }
  function getDiagnosticsWorker(sourceFile, nodesToCheck) {
    if (sourceFile) {
      ensurePendingDiagnosticWorkComplete();
      const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
      const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
      checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck);
      const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
      if (nodesToCheck) {
        return semanticDiagnostics;
      }
      const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
      if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
        const deferredGlobalDiagnostics = relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, compareDiagnostics);
        return concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
      } else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
        return concatenate(currentGlobalDiagnostics, semanticDiagnostics);
      }
      return semanticDiagnostics;
    }
    forEach(host.getSourceFiles(), (file) => checkSourceFileWithEagerDiagnostics(file));
    return diagnostics.getDiagnostics();
  }
  function getGlobalDiagnostics() {
    ensurePendingDiagnosticWorkComplete();
    return diagnostics.getGlobalDiagnostics();
  }
  function getSymbolsInScope(location, meaning) {
    if (location.flags & 67108864 /* InWithStatement */) {
      return [];
    }
    const symbols = createSymbolTable();
    let isStaticSymbol = false;
    populateSymbols();
    symbols.delete("this" /* This */);
    return symbolsToArray(symbols);
    function populateSymbols() {
      while (location) {
        if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
          copySymbols(location.locals, meaning);
        }
        switch (location.kind) {
          case 307 /* SourceFile */:
            if (!isExternalModule(location)) break;
          // falls through
          case 267 /* ModuleDeclaration */:
            copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */);
            break;
          case 266 /* EnumDeclaration */:
            copySymbols(getSymbolOfDeclaration(location).exports, meaning & 8 /* EnumMember */);
            break;
          case 231 /* ClassExpression */:
            const className = location.name;
            if (className) {
              copySymbol(location.symbol, meaning);
            }
          // this fall-through is necessary because we would like to handle
          // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
          // falls through
          case 263 /* ClassDeclaration */:
          case 264 /* InterfaceDeclaration */:
            if (!isStaticSymbol) {
              copySymbols(getMembersOfSymbol(getSymbolOfDeclaration(location)), meaning & 788968 /* Type */);
            }
            break;
          case 218 /* FunctionExpression */:
            const funcName = location.name;
            if (funcName) {
              copySymbol(location.symbol, meaning);
            }
            break;
        }
        if (introducesArgumentsExoticObject(location)) {
          copySymbol(argumentsSymbol, meaning);
        }
        isStaticSymbol = isStatic(location);
        location = location.parent;
      }
      copySymbols(globals, meaning);
    }
    function copySymbol(symbol, meaning2) {
      if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning2) {
        const id = symbol.escapedName;
        if (!symbols.has(id)) {
          symbols.set(id, symbol);
        }
      }
    }
    function copySymbols(source, meaning2) {
      if (meaning2) {
        source.forEach((symbol) => {
          copySymbol(symbol, meaning2);
        });
      }
    }
    function copyLocallyVisibleExportSymbols(source, meaning2) {
      if (meaning2) {
        source.forEach((symbol) => {
          if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) {
            copySymbol(symbol, meaning2);
          }
        });
      }
    }
  }
  function isTypeDeclarationName(name) {
    return name.kind === 80 /* Identifier */ && isTypeDeclaration(name.parent) && getNameOfDeclaration(name.parent) === name;
  }
  function isTypeReferenceIdentifier(node) {
    while (node.parent.kind === 166 /* QualifiedName */) {
      node = node.parent;
    }
    return node.parent.kind === 183 /* TypeReference */;
  }
  function isInNameOfExpressionWithTypeArguments(node) {
    while (node.parent.kind === 211 /* PropertyAccessExpression */) {
      node = node.parent;
    }
    return node.parent.kind === 233 /* ExpressionWithTypeArguments */;
  }
  function forEachEnclosingClass(node, callback) {
    let result;
    let containingClass = getContainingClass(node);
    while (containingClass) {
      if (result = callback(containingClass)) break;
      containingClass = getContainingClass(containingClass);
    }
    return result;
  }
  function isNodeUsedDuringClassInitialization(node) {
    return !!findAncestor(node, (element) => {
      if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) {
        return true;
      } else if (isClassLike(element) || isFunctionLikeDeclaration(element)) {
        return "quit";
      }
      return false;
    });
  }
  function isNodeWithinClass(node, classDeclaration) {
    return !!forEachEnclosingClass(node, (n) => n === classDeclaration);
  }
  function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
    while (nodeOnRightSide.parent.kind === 166 /* QualifiedName */) {
      nodeOnRightSide = nodeOnRightSide.parent;
    }
    if (nodeOnRightSide.parent.kind === 271 /* ImportEqualsDeclaration */) {
      return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : void 0;
    }
    if (nodeOnRightSide.parent.kind === 277 /* ExportAssignment */) {
      return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : void 0;
    }
    return void 0;
  }
  function isInRightSideOfImportOrExportAssignment(node) {
    return getLeftSideOfImportEqualsOrExportAssignment(node) !== void 0;
  }
  function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
    const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent);
    switch (specialPropertyAssignmentKind) {
      case 1 /* ExportsProperty */:
      case 3 /* PrototypeProperty */:
        return getSymbolOfNode(entityName.parent);
      case 5 /* Property */:
        if (isPropertyAccessExpression(entityName.parent) && getLeftmostAccessExpression(entityName.parent) === entityName) {
          return void 0;
        }
      // falls through
      case 4 /* ThisProperty */:
      case 2 /* ModuleExports */:
        return getSymbolOfDeclaration(entityName.parent.parent);
    }
  }
  function isImportTypeQualifierPart(node) {
    let parent = node.parent;
    while (isQualifiedName(parent)) {
      node = parent;
      parent = parent.parent;
    }
    if (parent && parent.kind === 205 /* ImportType */ && parent.qualifier === node) {
      return parent;
    }
    return void 0;
  }
  function isThisPropertyAndThisTyped(node) {
    if (node.expression.kind === 110 /* ThisKeyword */) {
      const container = getThisContainer(
        node,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (isFunctionLike(container)) {
        const containingLiteral = getContainingObjectLiteral(container);
        if (containingLiteral) {
          const contextualType = getApparentTypeOfContextualType(
            containingLiteral,
            /*contextFlags*/
            void 0
          );
          const type = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType);
          return type && !isTypeAny(type);
        }
      }
    }
  }
  function getSymbolOfNameOrPropertyAccessExpression(name) {
    if (isDeclarationName(name)) {
      return getSymbolOfNode(name.parent);
    }
    if (isInJSFile(name) && name.parent.kind === 211 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) {
      if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent)) {
        const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
        if (specialPropertyAssignmentSymbol) {
          return specialPropertyAssignmentSymbol;
        }
      }
    }
    if (name.parent.kind === 277 /* ExportAssignment */ && isEntityNameExpression(name)) {
      const success = resolveEntityName(
        name,
        /*all meanings*/
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*ignoreErrors*/
        true
      );
      if (success && success !== unknownSymbol) {
        return success;
      }
    } else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) {
      const importEqualsDeclaration = getAncestor(name, 271 /* ImportEqualsDeclaration */);
      Debug.assert(importEqualsDeclaration !== void 0);
      return getSymbolOfPartOfRightHandSideOfImportEquals(
        name,
        /*dontResolveAlias*/
        true
      );
    }
    if (isEntityName(name)) {
      const possibleImportNode = isImportTypeQualifierPart(name);
      if (possibleImportNode) {
        getTypeFromTypeNode(possibleImportNode);
        const sym = getNodeLinks(name).resolvedSymbol;
        return sym === unknownSymbol ? void 0 : sym;
      }
    }
    while (isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name)) {
      name = name.parent;
    }
    if (isInNameOfExpressionWithTypeArguments(name)) {
      let meaning = 0 /* None */;
      if (name.parent.kind === 233 /* ExpressionWithTypeArguments */) {
        meaning = isPartOfTypeNode(name) ? 788968 /* Type */ : 111551 /* Value */;
        if (isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
          meaning |= 111551 /* Value */;
        }
      } else {
        meaning = 1920 /* Namespace */;
      }
      meaning |= 2097152 /* Alias */;
      const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        true
      ) : void 0;
      if (entityNameSymbol) {
        return entityNameSymbol;
      }
    }
    if (name.parent.kind === 341 /* JSDocParameterTag */) {
      return getParameterSymbolFromJSDoc(name.parent);
    }
    if (name.parent.kind === 168 /* TypeParameter */ && name.parent.parent.kind === 345 /* JSDocTemplateTag */) {
      Debug.assert(!isInJSFile(name));
      const typeParameter = getTypeParameterFromJsDoc(name.parent);
      return typeParameter && typeParameter.symbol;
    }
    if (isExpressionNode(name)) {
      if (nodeIsMissing(name)) {
        return void 0;
      }
      const isJSDoc2 = findAncestor(name, or(isJSDocLinkLike, isJSDocNameReference, isJSDocMemberName));
      const meaning = isJSDoc2 ? 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */ : 111551 /* Value */;
      if (name.kind === 80 /* Identifier */) {
        if (isJSXTagName(name) && isJsxIntrinsicTagName(name)) {
          const symbol = getIntrinsicTagSymbol(name.parent);
          return symbol === unknownSymbol ? void 0 : symbol;
        }
        const result = resolveEntityName(
          name,
          meaning,
          /*ignoreErrors*/
          true,
          /*dontResolveAlias*/
          true,
          getHostSignatureFromJSDoc(name)
        );
        if (!result && isJSDoc2) {
          const container = findAncestor(name, or(isClassLike, isInterfaceDeclaration));
          if (container) {
            return resolveJSDocMemberName(
              name,
              /*ignoreErrors*/
              true,
              getSymbolOfDeclaration(container)
            );
          }
        }
        if (result && isJSDoc2) {
          const container = getJSDocHost(name);
          if (container && isEnumMember(container) && container === result.valueDeclaration) {
            return resolveEntityName(
              name,
              meaning,
              /*ignoreErrors*/
              true,
              /*dontResolveAlias*/
              true,
              getSourceFileOfNode(container)
            ) || result;
          }
        }
        return result;
      } else if (isPrivateIdentifier(name)) {
        return getSymbolForPrivateIdentifierExpression(name);
      } else if (name.kind === 211 /* PropertyAccessExpression */ || name.kind === 166 /* QualifiedName */) {
        const links = getNodeLinks(name);
        if (links.resolvedSymbol) {
          return links.resolvedSymbol;
        }
        if (name.kind === 211 /* PropertyAccessExpression */) {
          checkPropertyAccessExpression(name, 0 /* Normal */);
          if (!links.resolvedSymbol) {
            links.resolvedSymbol = getApplicableIndexSymbol(checkExpressionCached(name.expression), getLiteralTypeFromPropertyName(name.name));
          }
        } else {
          checkQualifiedName(name, 0 /* Normal */);
        }
        if (!links.resolvedSymbol && isJSDoc2 && isQualifiedName(name)) {
          return resolveJSDocMemberName(name);
        }
        return links.resolvedSymbol;
      } else if (isJSDocMemberName(name)) {
        return resolveJSDocMemberName(name);
      }
    } else if (isEntityName(name) && isTypeReferenceIdentifier(name)) {
      const meaning = name.parent.kind === 183 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
      const symbol = resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        false,
        /*dontResolveAlias*/
        true
      );
      return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name);
    }
    if (name.parent.kind === 182 /* TypePredicate */) {
      return resolveEntityName(
        name,
        /*meaning*/
        1 /* FunctionScopedVariable */
      );
    }
    return void 0;
  }
  function getApplicableIndexSymbol(type, keyType) {
    const infos = getApplicableIndexInfos(type, keyType);
    if (infos.length && type.members) {
      const symbol = getIndexSymbolFromSymbolTable(resolveStructuredTypeMembers(type).members);
      if (infos === getIndexInfosOfType(type)) {
        return symbol;
      } else if (symbol) {
        const symbolLinks2 = getSymbolLinks(symbol);
        const declarationList = mapDefined(infos, (i) => i.declaration);
        const nodeListId = map(declarationList, getNodeId).join(",");
        if (!symbolLinks2.filteredIndexSymbolCache) {
          symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map();
        }
        if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) {
          return symbolLinks2.filteredIndexSymbolCache.get(nodeListId);
        } else {
          const copy = createSymbol(131072 /* Signature */, "__index" /* Index */);
          copy.declarations = mapDefined(infos, (i) => i.declaration);
          copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent);
          symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy);
          return copy;
        }
      }
    }
  }
  function resolveJSDocMemberName(name, ignoreErrors, container) {
    if (isEntityName(name)) {
      const meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */;
      let symbol = resolveEntityName(
        name,
        meaning,
        ignoreErrors,
        /*dontResolveAlias*/
        true,
        getHostSignatureFromJSDoc(name)
      );
      if (!symbol && isIdentifier(name) && container) {
        symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning));
      }
      if (symbol) {
        return symbol;
      }
    }
    const left = isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container);
    const right = isIdentifier(name) ? name.escapedText : name.right.escapedText;
    if (left) {
      const proto = left.flags & 111551 /* Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype");
      const t = proto ? getTypeOfSymbol(proto) : getDeclaredTypeOfSymbol(left);
      return getPropertyOfType(t, right);
    }
  }
  function getSymbolAtLocation(node, ignoreErrors) {
    if (isSourceFile(node)) {
      return isExternalModule(node) ? getMergedSymbol(node.symbol) : void 0;
    }
    const { parent } = node;
    const grandParent = parent.parent;
    if (node.flags & 67108864 /* InWithStatement */) {
      return void 0;
    }
    if (isDeclarationNameOrImportPropertyName(node)) {
      const parentSymbol = getSymbolOfDeclaration(parent);
      return isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node ? getImmediateAliasedSymbol(parentSymbol) : parentSymbol;
    } else if (isLiteralComputedPropertyDeclarationName(node)) {
      return getSymbolOfDeclaration(parent.parent);
    }
    if (node.kind === 80 /* Identifier */) {
      if (isInRightSideOfImportOrExportAssignment(node)) {
        return getSymbolOfNameOrPropertyAccessExpression(node);
      } else if (parent.kind === 208 /* BindingElement */ && grandParent.kind === 206 /* ObjectBindingPattern */ && node === parent.propertyName) {
        const typeOfPattern = getTypeOfNode(grandParent);
        const propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
        if (propertyDeclaration) {
          return propertyDeclaration;
        }
      } else if (isMetaProperty(parent) && parent.name === node) {
        if (parent.keywordToken === 105 /* NewKeyword */ && idText(node) === "target") {
          return checkNewTargetMetaProperty(parent).symbol;
        }
        if (parent.keywordToken === 102 /* ImportKeyword */ && idText(node) === "meta") {
          return getGlobalImportMetaExpressionType().members.get("meta");
        }
        return void 0;
      }
    }
    switch (node.kind) {
      case 80 /* Identifier */:
      case 81 /* PrivateIdentifier */:
      case 211 /* PropertyAccessExpression */:
      case 166 /* QualifiedName */:
        if (!isThisInTypeQuery(node)) {
          return getSymbolOfNameOrPropertyAccessExpression(node);
        }
      // falls through
      case 110 /* ThisKeyword */:
        const container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        if (isFunctionLike(container)) {
          const sig = getSignatureFromDeclaration(container);
          if (sig.thisParameter) {
            return sig.thisParameter;
          }
        }
        if (isInExpressionContext(node)) {
          return checkExpression(node).symbol;
        }
      // falls through
      case 197 /* ThisType */:
        return getTypeFromThisTypeNode(node).symbol;
      case 108 /* SuperKeyword */:
        return checkExpression(node).symbol;
      case 137 /* ConstructorKeyword */:
        const constructorDeclaration = node.parent;
        if (constructorDeclaration && constructorDeclaration.kind === 176 /* Constructor */) {
          return constructorDeclaration.parent.symbol;
        }
        return void 0;
      case 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
        if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 272 /* ImportDeclaration */ || node.parent.kind === 278 /* ExportDeclaration */) && node.parent.moduleSpecifier === node || isInJSFile(node) && isJSDocImportTag(node.parent) && node.parent.moduleSpecifier === node || (isInJSFile(node) && isRequireCall(
          node.parent,
          /*requireStringLiteralLikeArgument*/
          false
        ) || isImportCall(node.parent)) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) {
          return resolveExternalModuleName(node, node, ignoreErrors);
        }
        if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
          return getSymbolOfDeclaration(parent);
        }
      // falls through
      case 9 /* NumericLiteral */:
        const objectType = isElementAccessExpression(parent) ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : void 0 : isLiteralTypeNode(parent) && isIndexedAccessTypeNode(grandParent) ? getTypeFromTypeNode(grandParent.objectType) : void 0;
        return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores(node.text));
      case 90 /* DefaultKeyword */:
      case 100 /* FunctionKeyword */:
      case 39 /* EqualsGreaterThanToken */:
      case 86 /* ClassKeyword */:
        return getSymbolOfNode(node.parent);
      case 205 /* ImportType */:
        return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : void 0;
      case 95 /* ExportKeyword */:
        return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : void 0;
      case 102 /* ImportKeyword */:
      case 105 /* NewKeyword */:
        return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0;
      case 104 /* InstanceOfKeyword */:
        if (isBinaryExpression(node.parent)) {
          const type = getTypeOfExpression(node.parent.right);
          const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(type);
          return (hasInstanceMethodType == null ? void 0 : hasInstanceMethodType.symbol) ?? type.symbol;
        }
        return void 0;
      case 236 /* MetaProperty */:
        return checkExpression(node).symbol;
      case 295 /* JsxNamespacedName */:
        if (isJSXTagName(node) && isJsxIntrinsicTagName(node)) {
          const symbol = getIntrinsicTagSymbol(node.parent);
          return symbol === unknownSymbol ? void 0 : symbol;
        }
      // falls through
      default:
        return void 0;
    }
  }
  function getIndexInfosAtLocation(node) {
    if (isIdentifier(node) && isPropertyAccessExpression(node.parent) && node.parent.name === node) {
      const keyType = getLiteralTypeFromPropertyName(node);
      const objectType = getTypeOfExpression(node.parent.expression);
      const objectTypes = objectType.flags & 1048576 /* Union */ ? objectType.types : [objectType];
      return flatMap(objectTypes, (t) => filter(getIndexInfosOfType(t), (info) => isApplicableIndexType(keyType, info.keyType)));
    }
    return void 0;
  }
  function getShorthandAssignmentValueSymbol(location) {
    if (location && location.kind === 304 /* ShorthandPropertyAssignment */) {
      return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
    }
    return void 0;
  }
  function getExportSpecifierLocalTargetSymbol(node) {
    if (isExportSpecifier(node)) {
      const name = node.propertyName || node.name;
      return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === 11 /* StringLiteral */ ? void 0 : (
        // Skip for invalid syntax like this: export { "x" }
        resolveEntityName(name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)
      );
    } else {
      return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
    }
  }
  function getTypeOfNode(node) {
    if (isSourceFile(node) && !isExternalModule(node)) {
      return errorType;
    }
    if (node.flags & 67108864 /* InWithStatement */) {
      return errorType;
    }
    const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
    const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(classDecl.class));
    if (isPartOfTypeNode(node)) {
      const typeFromTypeNode = getTypeFromTypeNode(node);
      return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
    }
    if (isExpressionNode(node)) {
      return getRegularTypeOfExpression(node);
    }
    if (classType && !classDecl.isImplements) {
      const baseType = firstOrUndefined(getBaseTypes(classType));
      return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
    }
    if (isTypeDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      return getDeclaredTypeOfSymbol(symbol);
    }
    if (isTypeDeclarationName(node)) {
      const symbol = getSymbolAtLocation(node);
      return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
    }
    if (isBindingElement(node)) {
      return getTypeForVariableLikeDeclaration(
        node,
        /*includeOptionality*/
        true,
        0 /* Normal */
      ) || errorType;
    }
    if (isDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      return symbol ? getTypeOfSymbol(symbol) : errorType;
    }
    if (isDeclarationNameOrImportPropertyName(node)) {
      const symbol = getSymbolAtLocation(node);
      if (symbol) {
        return getTypeOfSymbol(symbol);
      }
      return errorType;
    }
    if (isBindingPattern(node)) {
      return getTypeForVariableLikeDeclaration(
        node.parent,
        /*includeOptionality*/
        true,
        0 /* Normal */
      ) || errorType;
    }
    if (isInRightSideOfImportOrExportAssignment(node)) {
      const symbol = getSymbolAtLocation(node);
      if (symbol) {
        const declaredType = getDeclaredTypeOfSymbol(symbol);
        return !isErrorType(declaredType) ? declaredType : getTypeOfSymbol(symbol);
      }
    }
    if (isMetaProperty(node.parent) && node.parent.keywordToken === node.kind) {
      return checkMetaPropertyKeyword(node.parent);
    }
    if (isImportAttributes(node)) {
      return getGlobalImportAttributesType(
        /*reportErrors*/
        false
      );
    }
    return errorType;
  }
  function getTypeOfAssignmentPattern(expr) {
    Debug.assert(expr.kind === 210 /* ObjectLiteralExpression */ || expr.kind === 209 /* ArrayLiteralExpression */);
    if (expr.parent.kind === 250 /* ForOfStatement */) {
      const iteratedType = checkRightHandSideOfForOf(expr.parent);
      return checkDestructuringAssignment(expr, iteratedType || errorType);
    }
    if (expr.parent.kind === 226 /* BinaryExpression */) {
      const iteratedType = getTypeOfExpression(expr.parent.right);
      return checkDestructuringAssignment(expr, iteratedType || errorType);
    }
    if (expr.parent.kind === 303 /* PropertyAssignment */) {
      const node2 = cast(expr.parent.parent, isObjectLiteralExpression);
      const typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node2) || errorType;
      const propertyIndex = indexOfNode(node2.properties, expr.parent);
      return checkObjectLiteralDestructuringPropertyAssignment(node2, typeOfParentObjectLiteral, propertyIndex);
    }
    const node = cast(expr.parent, isArrayLiteralExpression);
    const typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
    const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
    return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
  }
  function getPropertySymbolOfDestructuringAssignment(location) {
    const typeOfObjectLiteral = getTypeOfAssignmentPattern(cast(location.parent.parent, isAssignmentPattern));
    return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
  }
  function getRegularTypeOfExpression(expr) {
    if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
      expr = expr.parent;
    }
    return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
  }
  function getParentTypeOfClassElement(node) {
    const classSymbol = getSymbolOfNode(node.parent);
    return isStatic(node) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol);
  }
  function getClassElementPropertyKeyType(element) {
    const name = element.name;
    switch (name.kind) {
      case 80 /* Identifier */:
        return getStringLiteralType(idText(name));
      case 9 /* NumericLiteral */:
      case 11 /* StringLiteral */:
        return getStringLiteralType(name.text);
      case 167 /* ComputedPropertyName */:
        const nameType = checkComputedPropertyName(name);
        return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
      default:
        return Debug.fail("Unsupported property name.");
    }
  }
  function getAugmentedPropertiesOfType(type) {
    type = getApparentType(type);
    const propsByName = createSymbolTable(getPropertiesOfType(type));
    const functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : void 0;
    if (functionType) {
      forEach(getPropertiesOfType(functionType), (p) => {
        if (!propsByName.has(p.escapedName)) {
          propsByName.set(p.escapedName, p);
        }
      });
    }
    return getNamedMembers(propsByName);
  }
  function typeHasCallOrConstructSignatures(type) {
    return getSignaturesOfType(type, 0 /* Call */).length !== 0 || getSignaturesOfType(type, 1 /* Construct */).length !== 0;
  }
  function getRootSymbols(symbol) {
    const roots = getImmediateRootSymbols(symbol);
    return roots ? flatMap(roots, getRootSymbols) : [symbol];
  }
  function getImmediateRootSymbols(symbol) {
    if (getCheckFlags(symbol) & 6 /* Synthetic */) {
      return mapDefined(getSymbolLinks(symbol).containingType.types, (type) => getPropertyOfType(type, symbol.escapedName));
    } else if (symbol.flags & 33554432 /* Transient */) {
      const { links: { leftSpread, rightSpread, syntheticOrigin } } = symbol;
      return leftSpread ? [leftSpread, rightSpread] : syntheticOrigin ? [syntheticOrigin] : singleElementArray(tryGetTarget(symbol));
    }
    return void 0;
  }
  function tryGetTarget(symbol) {
    let target;
    let next = symbol;
    while (next = getSymbolLinks(next).target) {
      target = next;
    }
    return target;
  }
  function isArgumentsLocalBinding(nodeIn) {
    if (isGeneratedIdentifier(nodeIn)) return false;
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (!node) return false;
    const parent = node.parent;
    if (!parent) return false;
    const isPropertyName2 = (isPropertyAccessExpression(parent) || isPropertyAssignment(parent)) && parent.name === node;
    return !isPropertyName2 && getReferencedValueSymbol(node) === argumentsSymbol;
  }
  function isNameOfModuleOrEnumDeclaration(node) {
    return isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
  }
  function getReferencedExportContainer(nodeIn, prefixLocals) {
    var _a;
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (node) {
      let symbol = getReferencedValueSymbol(
        node,
        /*startInDeclarationContainer*/
        isNameOfModuleOrEnumDeclaration(node)
      );
      if (symbol) {
        if (symbol.flags & 1048576 /* ExportValue */) {
          const exportSymbol = getMergedSymbol(symbol.exportSymbol);
          if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
            return void 0;
          }
          symbol = exportSymbol;
        }
        const parentSymbol = getParentOfSymbol(symbol);
        if (parentSymbol) {
          if (parentSymbol.flags & 512 /* ValueModule */ && ((_a = parentSymbol.valueDeclaration) == null ? void 0 : _a.kind) === 307 /* SourceFile */) {
            const symbolFile = parentSymbol.valueDeclaration;
            const referenceFile = getSourceFileOfNode(node);
            const symbolIsUmdExport = symbolFile !== referenceFile;
            return symbolIsUmdExport ? void 0 : symbolFile;
          }
          return findAncestor(node.parent, (n) => isModuleOrEnumDeclaration(n) && getSymbolOfDeclaration(n) === parentSymbol);
        }
      }
    }
  }
  function getReferencedImportDeclaration(nodeIn) {
    const specifier = getIdentifierGeneratedImportReference(nodeIn);
    if (specifier) {
      return specifier;
    }
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (node) {
      const symbol = getReferencedValueOrAliasSymbol(node);
      if (isNonLocalAlias(
        symbol,
        /*excludes*/
        111551 /* Value */
      ) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) {
        return getDeclarationOfAliasSymbol(symbol);
      }
    }
    return void 0;
  }
  function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
    return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 299 /* CatchClause */;
  }
  function isSymbolOfDeclarationWithCollidingName(symbol) {
    if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) {
      const links = getSymbolLinks(symbol);
      if (links.isDeclarationWithCollidingName === void 0) {
        const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
        if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
          if (resolveName(
            container.parent,
            symbol.escapedName,
            111551 /* Value */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          )) {
            links.isDeclarationWithCollidingName = true;
          } else if (hasNodeCheckFlag(symbol.valueDeclaration, 16384 /* CapturedBlockScopedBinding */)) {
            const isDeclaredInLoop = hasNodeCheckFlag(symbol.valueDeclaration, 32768 /* BlockScopedBindingInLoop */);
            const inLoopInitializer = isIterationStatement(
              container,
              /*lookInLabeledStatements*/
              false
            );
            const inLoopBodyBlock = container.kind === 241 /* Block */ && isIterationStatement(
              container.parent,
              /*lookInLabeledStatements*/
              false
            );
            links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || !inLoopInitializer && !inLoopBodyBlock);
          } else {
            links.isDeclarationWithCollidingName = false;
          }
        }
      }
      return links.isDeclarationWithCollidingName;
    }
    return false;
  }
  function getReferencedDeclarationWithCollidingName(nodeIn) {
    if (!isGeneratedIdentifier(nodeIn)) {
      const node = getParseTreeNode(nodeIn, isIdentifier);
      if (node) {
        const symbol = getReferencedValueSymbol(node);
        if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
          return symbol.valueDeclaration;
        }
      }
    }
    return void 0;
  }
  function isDeclarationWithCollidingName(nodeIn) {
    const node = getParseTreeNode(nodeIn, isDeclaration);
    if (node) {
      const symbol = getSymbolOfDeclaration(node);
      if (symbol) {
        return isSymbolOfDeclarationWithCollidingName(symbol);
      }
    }
    return false;
  }
  function isValueAliasDeclaration(node) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
        return isAliasResolvedToValue(getSymbolOfDeclaration(node));
      case 273 /* ImportClause */:
      case 274 /* NamespaceImport */:
      case 276 /* ImportSpecifier */:
      case 281 /* ExportSpecifier */:
        const symbol = getSymbolOfDeclaration(node);
        return !!symbol && isAliasResolvedToValue(
          symbol,
          /*excludeTypeOnlyValues*/
          true
        );
      case 278 /* ExportDeclaration */:
        const exportClause = node.exportClause;
        return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration));
      case 277 /* ExportAssignment */:
        return node.expression && node.expression.kind === 80 /* Identifier */ ? isAliasResolvedToValue(
          getSymbolOfDeclaration(node),
          /*excludeTypeOnlyValues*/
          true
        ) : true;
    }
    return false;
  }
  function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
    const node = getParseTreeNode(nodeIn, isImportEqualsDeclaration);
    if (node === void 0 || node.parent.kind !== 307 /* SourceFile */ || !isInternalModuleImportEqualsDeclaration(node)) {
      return false;
    }
    const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node));
    return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference);
  }
  function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) {
    if (!symbol) {
      return false;
    }
    const container = getSourceFileOfNode(symbol.valueDeclaration);
    const fileSymbol = container && getSymbolOfDeclaration(container);
    void resolveExternalModuleSymbol(fileSymbol);
    const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol));
    if (target === unknownSymbol) {
      return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol);
    }
    return !!(getSymbolFlags(
      symbol,
      excludeTypeOnlyValues,
      /*excludeLocalMeanings*/
      true
    ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
  }
  function isConstEnumOrConstEnumOnlyModule(s) {
    return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
  }
  function isReferencedAliasDeclaration(node, checkChildren) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    if (isAliasSymbolDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      const links = symbol && getSymbolLinks(symbol);
      if (links == null ? void 0 : links.referenced) {
        return true;
      }
      const target = getSymbolLinks(symbol).aliasTarget;
      if (target && getEffectiveModifierFlags(node) & 32 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
        return true;
      }
    }
    if (checkChildren) {
      return !!forEachChild(node, (node2) => isReferencedAliasDeclaration(node2, checkChildren));
    }
    return false;
  }
  function isImplementationOfOverload(node) {
    if (nodeIsPresent(node.body)) {
      if (isGetAccessor(node) || isSetAccessor(node)) return false;
      const symbol = getSymbolOfDeclaration(node);
      const signaturesOfSymbol = getSignaturesOfSymbol(symbol);
      return signaturesOfSymbol.length > 1 || // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
      // e.g.: function foo(a: string): string;
      //       function foo(a: any) { // This is implementation of the overloads
      //           return a;
      //       }
      signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node;
    }
    return false;
  }
  function declaredParameterTypeContainsUndefined(parameter) {
    const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter);
    if (!typeNode) return false;
    const type = getTypeFromTypeNode(typeNode);
    return isErrorType(type) || containsUndefinedType(type);
  }
  function requiresAddingImplicitUndefined(parameter, enclosingDeclaration) {
    return (isRequiredInitializedParameter(parameter, enclosingDeclaration) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter);
  }
  function isRequiredInitializedParameter(parameter, enclosingDeclaration) {
    if (!strictNullChecks || isOptionalParameter(parameter) || isJSDocParameterTag(parameter) || !parameter.initializer) {
      return false;
    }
    if (hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */)) {
      return !!enclosingDeclaration && isFunctionLikeDeclaration(enclosingDeclaration);
    }
    return true;
  }
  function isOptionalUninitializedParameterProperty(parameter) {
    return strictNullChecks && isOptionalParameter(parameter) && (isJSDocParameterTag(parameter) || !parameter.initializer) && hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */);
  }
  function isExpandoFunctionDeclaration(node) {
    const declaration = getParseTreeNode(node, (n) => isFunctionDeclaration(n) || isVariableDeclaration(n));
    if (!declaration) {
      return false;
    }
    let symbol;
    if (isVariableDeclaration(declaration)) {
      if (declaration.type || !isInJSFile(declaration) && !isVarConstLike2(declaration)) {
        return false;
      }
      const initializer = getDeclaredExpandoInitializer(declaration);
      if (!initializer || !canHaveSymbol(initializer)) {
        return false;
      }
      symbol = getSymbolOfDeclaration(initializer);
    } else {
      symbol = getSymbolOfDeclaration(declaration);
    }
    if (!symbol || !(symbol.flags & 16 /* Function */ | 3 /* Variable */)) {
      return false;
    }
    return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & 111551 /* Value */ && isExpandoPropertyDeclaration(p.valueDeclaration));
  }
  function getPropertiesOfContainerFunction(node) {
    const declaration = getParseTreeNode(node, isFunctionDeclaration);
    if (!declaration) {
      return emptyArray;
    }
    const symbol = getSymbolOfDeclaration(declaration);
    return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || emptyArray;
  }
  function getNodeCheckFlags(node) {
    var _a;
    const nodeId = node.id || 0;
    if (nodeId < 0 || nodeId >= nodeLinks.length) return 0;
    return ((_a = nodeLinks[nodeId]) == null ? void 0 : _a.flags) || 0;
  }
  function hasNodeCheckFlag(node, flag) {
    calculateNodeCheckFlagWorker(node, flag);
    return !!(getNodeCheckFlags(node) & flag);
  }
  function calculateNodeCheckFlagWorker(node, flag) {
    if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnostics(getSourceFileOfNode(node), compilerOptions)) {
      return;
    }
    const links = getNodeLinks(node);
    if (links.calculatedFlags & flag) {
      return;
    }
    switch (flag) {
      case 16 /* SuperInstance */:
      case 32 /* SuperStatic */:
        return checkSingleSuperExpression(node);
      case 128 /* MethodWithSuperPropertyAccessInAsync */:
      case 256 /* MethodWithSuperPropertyAssignmentInAsync */:
      case 2097152 /* ContainsSuperPropertyInStaticInitializer */:
        return checkChildSuperExpressions(node);
      case 512 /* CaptureArguments */:
      case 8192 /* ContainsCapturedBlockScopeBinding */:
      case 65536 /* NeedsLoopOutParameter */:
      case 262144 /* ContainsConstructorReference */:
        return checkChildIdentifiers(node);
      case 536870912 /* ConstructorReference */:
        return checkSingleIdentifier(node);
      case 4096 /* LoopWithCapturedBlockScopedBinding */:
      case 32768 /* BlockScopedBindingInLoop */:
      case 16384 /* CapturedBlockScopedBinding */:
        return checkContainingBlockScopeBindingUses(node);
      default:
        return Debug.assertNever(flag, `Unhandled node check flag calculation: ${Debug.formatNodeCheckFlags(flag)}`);
    }
    function forEachNodeRecursively(root, cb) {
      const rootResult = cb(root, root.parent);
      if (rootResult === "skip") return void 0;
      if (rootResult) return rootResult;
      return forEachChildRecursively(root, cb);
    }
    function checkSuperExpressions(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= 128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */ | 2097152 /* ContainsSuperPropertyInStaticInitializer */;
      checkSingleSuperExpression(node2);
      return void 0;
    }
    function checkChildSuperExpressions(node2) {
      forEachNodeRecursively(node2, checkSuperExpressions);
    }
    function checkSingleSuperExpression(node2) {
      const nodeLinks2 = getNodeLinks(node2);
      nodeLinks2.calculatedFlags |= 16 /* SuperInstance */ | 32 /* SuperStatic */;
      if (node2.kind === 108 /* SuperKeyword */) {
        checkSuperExpression(node2);
      }
    }
    function checkIdentifiers(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= 512 /* CaptureArguments */ | 8192 /* ContainsCapturedBlockScopeBinding */ | 65536 /* NeedsLoopOutParameter */ | 262144 /* ContainsConstructorReference */;
      checkSingleIdentifier(node2);
      return void 0;
    }
    function checkChildIdentifiers(node2) {
      forEachNodeRecursively(node2, checkIdentifiers);
    }
    function isExpressionNodeOrShorthandPropertyAssignmentName(node2) {
      return isExpressionNode(node2) || isShorthandPropertyAssignment(node2.parent) && (node2.parent.objectAssignmentInitializer ?? node2.parent.name) === node2;
    }
    function checkSingleIdentifier(node2) {
      const nodeLinks2 = getNodeLinks(node2);
      nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */;
      if (isIdentifier(node2)) {
        nodeLinks2.calculatedFlags |= 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */;
        if (isExpressionNodeOrShorthandPropertyAssignmentName(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) {
          const s = getResolvedSymbol(node2);
          if (s && s !== unknownSymbol) {
            checkIdentifierCalculateNodeCheckFlags(node2, s);
          }
        }
      }
    }
    function checkBlockScopeBindings(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= 4096 /* LoopWithCapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */;
      checkSingleBlockScopeBinding(node2);
      return void 0;
    }
    function checkContainingBlockScopeBindingUses(node2) {
      const scope = getEnclosingBlockScopeContainer(isDeclarationName(node2) ? node2.parent : node2);
      forEachNodeRecursively(scope, checkBlockScopeBindings);
    }
    function checkSingleBlockScopeBinding(node2) {
      checkSingleIdentifier(node2);
      if (isComputedPropertyName(node2)) {
        checkComputedPropertyName(node2);
      }
      if (isPrivateIdentifier(node2) && isClassElement(node2.parent)) {
        setNodeLinksForPrivateIdentifierScope(node2.parent);
      }
    }
  }
  function getEnumMemberValue(node) {
    computeEnumMemberValues(node.parent);
    return getNodeLinks(node).enumMemberValue ?? evaluatorResult(
      /*value*/
      void 0
    );
  }
  function canHaveConstantValue(node) {
    switch (node.kind) {
      case 306 /* EnumMember */:
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return true;
    }
    return false;
  }
  function getConstantValue2(node) {
    if (node.kind === 306 /* EnumMember */) {
      return getEnumMemberValue(node).value;
    }
    if (!getNodeLinks(node).resolvedSymbol) {
      void checkExpressionCached(node);
    }
    const symbol = getNodeLinks(node).resolvedSymbol || (isEntityNameExpression(node) ? resolveEntityName(
      node,
      111551 /* Value */,
      /*ignoreErrors*/
      true
    ) : void 0);
    if (symbol && symbol.flags & 8 /* EnumMember */) {
      const member = symbol.valueDeclaration;
      if (isEnumConst(member.parent)) {
        return getEnumMemberValue(member).value;
      }
    }
    return void 0;
  }
  function isFunctionType(type) {
    return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
  }
  function getTypeReferenceSerializationKind(typeNameIn, location) {
    var _a;
    const typeName = getParseTreeNode(typeNameIn, isEntityName);
    if (!typeName) return 0 /* Unknown */;
    if (location) {
      location = getParseTreeNode(location);
      if (!location) return 0 /* Unknown */;
    }
    let isTypeOnly = false;
    if (isQualifiedName(typeName)) {
      const rootValueSymbol = resolveEntityName(
        getFirstIdentifier(typeName),
        111551 /* Value */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        location
      );
      isTypeOnly = !!((_a = rootValueSymbol == null ? void 0 : rootValueSymbol.declarations) == null ? void 0 : _a.every(isTypeOnlyImportOrExportDeclaration));
    }
    const valueSymbol = resolveEntityName(
      typeName,
      111551 /* Value */,
      /*ignoreErrors*/
      true,
      /*dontResolveAlias*/
      true,
      location
    );
    const resolvedValueSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
    isTypeOnly || (isTypeOnly = !!(valueSymbol && getTypeOnlyAliasDeclaration(valueSymbol, 111551 /* Value */)));
    const typeSymbol = resolveEntityName(
      typeName,
      788968 /* Type */,
      /*ignoreErrors*/
      true,
      /*dontResolveAlias*/
      true,
      location
    );
    const resolvedTypeSymbol = typeSymbol && typeSymbol.flags & 2097152 /* Alias */ ? resolveAlias(typeSymbol) : typeSymbol;
    if (!valueSymbol) {
      isTypeOnly || (isTypeOnly = !!(typeSymbol && getTypeOnlyAliasDeclaration(typeSymbol, 788968 /* Type */)));
    }
    if (resolvedValueSymbol && resolvedValueSymbol === resolvedTypeSymbol) {
      const globalPromiseSymbol = getGlobalPromiseConstructorSymbol(
        /*reportErrors*/
        false
      );
      if (globalPromiseSymbol && resolvedValueSymbol === globalPromiseSymbol) {
        return 9 /* Promise */;
      }
      const constructorType = getTypeOfSymbol(resolvedValueSymbol);
      if (constructorType && isConstructorType(constructorType)) {
        return isTypeOnly ? 10 /* TypeWithCallSignature */ : 1 /* TypeWithConstructSignatureAndValue */;
      }
    }
    if (!resolvedTypeSymbol) {
      return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */;
    }
    const type = getDeclaredTypeOfSymbol(resolvedTypeSymbol);
    if (isErrorType(type)) {
      return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */;
    } else if (type.flags & 3 /* AnyOrUnknown */) {
      return 11 /* ObjectType */;
    } else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
      return 2 /* VoidNullableOrNeverType */;
    } else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
      return 6 /* BooleanType */;
    } else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
      return 3 /* NumberLikeType */;
    } else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
      return 4 /* BigIntLikeType */;
    } else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) {
      return 5 /* StringLikeType */;
    } else if (isTupleType(type)) {
      return 7 /* ArrayLikeType */;
    } else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
      return 8 /* ESSymbolType */;
    } else if (isFunctionType(type)) {
      return 10 /* TypeWithCallSignature */;
    } else if (isArrayType(type)) {
      return 7 /* ArrayLikeType */;
    } else {
      return 11 /* ObjectType */;
    }
  }
  function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const declaration = getParseTreeNode(declarationIn, hasInferredType);
    if (!declaration) {
      return factory.createToken(133 /* AnyKeyword */);
    }
    const symbol = getSymbolOfDeclaration(declaration);
    return nodeBuilder.serializeTypeForDeclaration(declaration, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker);
  }
  function getAllAccessorDeclarationsForDeclaration(accessor) {
    accessor = getParseTreeNode(accessor, isGetOrSetAccessorDeclaration);
    const otherKind = accessor.kind === 178 /* SetAccessor */ ? 177 /* GetAccessor */ : 178 /* SetAccessor */;
    const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(accessor), otherKind);
    const firstAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? otherAccessor : accessor;
    const secondAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? accessor : otherAccessor;
    const setAccessor = accessor.kind === 178 /* SetAccessor */ ? accessor : otherAccessor;
    const getAccessor = accessor.kind === 177 /* GetAccessor */ ? accessor : otherAccessor;
    return {
      firstAccessor,
      secondAccessor,
      setAccessor,
      getAccessor
    };
  }
  function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike);
    if (!signatureDeclaration) {
      return factory.createToken(133 /* AnyKeyword */);
    }
    return nodeBuilder.serializeReturnTypeForSignature(signatureDeclaration, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker);
  }
  function createTypeOfExpression(exprIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const expr = getParseTreeNode(exprIn, isExpression);
    if (!expr) {
      return factory.createToken(133 /* AnyKeyword */);
    }
    return nodeBuilder.serializeTypeForExpression(expr, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker);
  }
  function hasGlobalName(name) {
    return globals.has(escapeLeadingUnderscores(name));
  }
  function getReferencedValueSymbol(reference, startInDeclarationContainer) {
    const resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
    if (resolvedSymbol) {
      return resolvedSymbol;
    }
    let location = reference;
    if (startInDeclarationContainer) {
      const parent = reference.parent;
      if (isDeclaration(parent) && reference === parent.name) {
        location = getDeclarationContainer(parent);
      }
    }
    return resolveName(
      location,
      reference.escapedText,
      111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
  }
  function getReferencedValueOrAliasSymbol(reference) {
    const resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
    if (resolvedSymbol && resolvedSymbol !== unknownSymbol) {
      return resolvedSymbol;
    }
    return resolveName(
      reference,
      reference.escapedText,
      111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true,
      /*excludeGlobals*/
      void 0
    );
  }
  function getReferencedValueDeclaration(referenceIn) {
    if (!isGeneratedIdentifier(referenceIn)) {
      const reference = getParseTreeNode(referenceIn, isIdentifier);
      if (reference) {
        const symbol = getReferencedValueSymbol(reference);
        if (symbol) {
          return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
        }
      }
    }
    return void 0;
  }
  function getReferencedValueDeclarations(referenceIn) {
    if (!isGeneratedIdentifier(referenceIn)) {
      const reference = getParseTreeNode(referenceIn, isIdentifier);
      if (reference) {
        const symbol = getReferencedValueSymbol(reference);
        if (symbol) {
          return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => {
            switch (declaration.kind) {
              case 260 /* VariableDeclaration */:
              case 169 /* Parameter */:
              case 208 /* BindingElement */:
              case 172 /* PropertyDeclaration */:
              case 303 /* PropertyAssignment */:
              case 304 /* ShorthandPropertyAssignment */:
              case 306 /* EnumMember */:
              case 210 /* ObjectLiteralExpression */:
              case 262 /* FunctionDeclaration */:
              case 218 /* FunctionExpression */:
              case 219 /* ArrowFunction */:
              case 263 /* ClassDeclaration */:
              case 231 /* ClassExpression */:
              case 266 /* EnumDeclaration */:
              case 174 /* MethodDeclaration */:
              case 177 /* GetAccessor */:
              case 178 /* SetAccessor */:
              case 267 /* ModuleDeclaration */:
                return true;
            }
            return false;
          });
        }
      }
    }
    return void 0;
  }
  function isLiteralConstDeclaration(node) {
    if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike2(node)) {
      return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node)));
    }
    return false;
  }
  function literalTypeToNode(type, enclosing, tracker) {
    const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression(
      type.symbol,
      111551 /* Value */,
      enclosing,
      /*flags*/
      void 0,
      /*internalFlags*/
      void 0,
      tracker
    ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse();
    if (enumResult) return enumResult;
    const literalValue = type.value;
    return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "string" ? factory.createStringLiteral(literalValue) : literalValue < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-literalValue)) : factory.createNumericLiteral(literalValue);
  }
  function createLiteralConstValue(node, tracker) {
    const type = getTypeOfSymbol(getSymbolOfDeclaration(node));
    return literalTypeToNode(type, node, tracker);
  }
  function getJsxFactoryEntity(location) {
    return location ? (getJsxNamespace(location), getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity) : _jsxFactoryEntity;
  }
  function getJsxFragmentFactoryEntity(location) {
    if (location) {
      const file = getSourceFileOfNode(location);
      if (file) {
        if (file.localJsxFragmentFactory) {
          return file.localJsxFragmentFactory;
        }
        const jsxFragPragmas = file.pragmas.get("jsxfrag");
        const jsxFragPragma = isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
        if (jsxFragPragma) {
          file.localJsxFragmentFactory = parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
          return file.localJsxFragmentFactory;
        }
      }
    }
    if (compilerOptions.jsxFragmentFactory) {
      return parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
    }
  }
  function getNonlocalEffectiveTypeAnnotationNode(node) {
    const direct = getEffectiveTypeAnnotationNode(node);
    if (direct) {
      return direct;
    }
    if (node.kind === 169 /* Parameter */ && node.parent.kind === 178 /* SetAccessor */) {
      const other = getAllAccessorDeclarationsForDeclaration(node.parent).getAccessor;
      if (other) {
        return getEffectiveReturnTypeNode(other);
      }
    }
    return void 0;
  }
  function createResolver() {
    return {
      getReferencedExportContainer,
      getReferencedImportDeclaration,
      getReferencedDeclarationWithCollidingName,
      isDeclarationWithCollidingName,
      isValueAliasDeclaration: (nodeIn) => {
        const node = getParseTreeNode(nodeIn);
        return node && canCollectSymbolAliasAccessabilityData ? isValueAliasDeclaration(node) : true;
      },
      hasGlobalName,
      isReferencedAliasDeclaration: (nodeIn, checkChildren) => {
        const node = getParseTreeNode(nodeIn);
        return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true;
      },
      hasNodeCheckFlag: (nodeIn, flag) => {
        const node = getParseTreeNode(nodeIn);
        if (!node) return false;
        return hasNodeCheckFlag(node, flag);
      },
      isTopLevelValueImportEqualsWithEntityName,
      isDeclarationVisible,
      isImplementationOfOverload,
      requiresAddingImplicitUndefined,
      isExpandoFunctionDeclaration,
      getPropertiesOfContainerFunction,
      createTypeOfDeclaration,
      createReturnTypeOfSignatureDeclaration,
      createTypeOfExpression,
      createLiteralConstValue,
      isSymbolAccessible,
      isEntityNameVisible,
      getConstantValue: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, canHaveConstantValue);
        return node ? getConstantValue2(node) : void 0;
      },
      getEnumMemberValue: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, isEnumMember);
        return node ? getEnumMemberValue(node) : void 0;
      },
      collectLinkedAliases,
      markLinkedReferences: (nodeIn) => {
        const node = getParseTreeNode(nodeIn);
        return node && markLinkedReferences(node, 0 /* Unspecified */);
      },
      getReferencedValueDeclaration,
      getReferencedValueDeclarations,
      getTypeReferenceSerializationKind,
      isOptionalParameter,
      isArgumentsLocalBinding,
      getExternalModuleFileFromDeclaration: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, hasPossibleExternalModuleReference);
        return node && getExternalModuleFileFromDeclaration(node);
      },
      isLiteralConstDeclaration,
      isLateBound: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, isDeclaration);
        const symbol = node && getSymbolOfDeclaration(node);
        return !!(symbol && getCheckFlags(symbol) & 4096 /* Late */);
      },
      getJsxFactoryEntity,
      getJsxFragmentFactoryEntity,
      isBindingCapturedByNode: (node, decl) => {
        const parseNode = getParseTreeNode(node);
        const parseDecl = getParseTreeNode(decl);
        return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
      },
      getDeclarationStatementsForSourceFile: (node, flags, internalFlags, tracker) => {
        const n = getParseTreeNode(node);
        Debug.assert(n && n.kind === 307 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
        const sym = getSymbolOfDeclaration(node);
        if (!sym) {
          return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, internalFlags, tracker);
        }
        resolveExternalModuleSymbol(sym);
        return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, internalFlags, tracker);
      },
      isImportRequiredByAugmentation,
      isDefinitelyReferenceToGlobalSymbolObject,
      createLateBoundIndexSignatures: (cls, enclosing, flags, internalFlags, tracker) => {
        const sym = cls.symbol;
        const staticInfos = getIndexInfosOfType(getTypeOfSymbol(sym));
        const instanceIndexSymbol = getIndexSymbol(sym);
        const instanceInfos = instanceIndexSymbol && getIndexInfosOfIndexSymbol(instanceIndexSymbol, arrayFrom(getMembersOfSymbol(sym).values()));
        let result;
        for (const infoList of [staticInfos, instanceInfos]) {
          if (!length(infoList)) continue;
          result || (result = []);
          for (const info of infoList) {
            if (info.declaration) continue;
            if (info === anyBaseTypeIndexInfo) continue;
            const node = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, enclosing, flags, internalFlags, tracker);
            if (node && infoList === staticInfos) {
              (node.modifiers || (node.modifiers = factory.createNodeArray())).unshift(factory.createModifier(126 /* StaticKeyword */));
            }
            if (node) {
              result.push(node);
            }
          }
        }
        return result;
      }
    };
    function isImportRequiredByAugmentation(node) {
      const file = getSourceFileOfNode(node);
      if (!file.symbol) return false;
      const importTarget = getExternalModuleFileFromDeclaration(node);
      if (!importTarget) return false;
      if (importTarget === file) return false;
      const exports2 = getExportsOfModule(file.symbol);
      for (const s of arrayFrom(exports2.values())) {
        if (s.mergeId) {
          const merged = getMergedSymbol(s);
          if (merged.declarations) {
            for (const d of merged.declarations) {
              const declFile = getSourceFileOfNode(d);
              if (declFile === importTarget) {
                return true;
              }
            }
          }
        }
      }
      return false;
    }
  }
  function getExternalModuleFileFromDeclaration(declaration) {
    const specifier = declaration.kind === 267 /* ModuleDeclaration */ ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration);
    const moduleSymbol = resolveExternalModuleNameWorker(
      specifier,
      specifier,
      /*moduleNotFoundError*/
      void 0
    );
    if (!moduleSymbol) {
      return void 0;
    }
    return getDeclarationOfKind(moduleSymbol, 307 /* SourceFile */);
  }
  function initializeTypeChecker() {
    for (const file of host.getSourceFiles()) {
      bindSourceFile(file, compilerOptions);
    }
    amalgamatedDuplicates = /* @__PURE__ */ new Map();
    let augmentations;
    for (const file of host.getSourceFiles()) {
      if (file.redirectInfo) {
        continue;
      }
      if (!isExternalOrCommonJsModule(file)) {
        const fileGlobalThisSymbol = file.locals.get("globalThis");
        if (fileGlobalThisSymbol == null ? void 0 : fileGlobalThisSymbol.declarations) {
          for (const declaration of fileGlobalThisSymbol.declarations) {
            diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
          }
        }
        mergeSymbolTable(globals, file.locals);
      }
      if (file.jsGlobalAugmentations) {
        mergeSymbolTable(globals, file.jsGlobalAugmentations);
      }
      if (file.patternAmbientModules && file.patternAmbientModules.length) {
        patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules);
      }
      if (file.moduleAugmentations.length) {
        (augmentations || (augmentations = [])).push(file.moduleAugmentations);
      }
      if (file.symbol && file.symbol.globalExports) {
        const source = file.symbol.globalExports;
        source.forEach((sourceSymbol, id) => {
          if (!globals.has(id)) {
            globals.set(id, sourceSymbol);
          }
        });
      }
    }
    if (augmentations) {
      for (const list of augmentations) {
        for (const augmentation of list) {
          if (!isGlobalScopeAugmentation(augmentation.parent)) continue;
          mergeModuleAugmentation(augmentation);
        }
      }
    }
    addUndefinedToGlobalsOrErrorOnRedeclaration();
    getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
    getSymbolLinks(argumentsSymbol).type = getGlobalType(
      "IArguments",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    getSymbolLinks(unknownSymbol).type = errorType;
    getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
    globalArrayType = getGlobalType(
      "Array",
      /*arity*/
      1,
      /*reportErrors*/
      true
    );
    globalObjectType = getGlobalType(
      "Object",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalFunctionType = getGlobalType(
      "Function",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalCallableFunctionType = strictBindCallApply && getGlobalType(
      "CallableFunction",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || globalFunctionType;
    globalNewableFunctionType = strictBindCallApply && getGlobalType(
      "NewableFunction",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || globalFunctionType;
    globalStringType = getGlobalType(
      "String",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalNumberType = getGlobalType(
      "Number",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalBooleanType = getGlobalType(
      "Boolean",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalRegExpType = getGlobalType(
      "RegExp",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    anyArrayType = createArrayType(anyType);
    autoArrayType = createArrayType(autoType);
    if (autoArrayType === emptyObjectType) {
      autoArrayType = createAnonymousType(
        /*symbol*/
        void 0,
        emptySymbols,
        emptyArray,
        emptyArray,
        emptyArray
      );
    }
    globalReadonlyArrayType = getGlobalTypeOrUndefined(
      "ReadonlyArray",
      /*arity*/
      1
    ) || globalArrayType;
    anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
    globalThisType = getGlobalTypeOrUndefined(
      "ThisType",
      /*arity*/
      1
    );
    if (augmentations) {
      for (const list of augmentations) {
        for (const augmentation of list) {
          if (isGlobalScopeAugmentation(augmentation.parent)) continue;
          mergeModuleAugmentation(augmentation);
        }
      }
    }
    amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => {
      if (conflictingSymbols.size < 8) {
        conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName2) => {
          const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
          for (const node of firstFileLocations) {
            addDuplicateDeclarationError(node, message, symbolName2, secondFileLocations);
          }
          for (const node of secondFileLocations) {
            addDuplicateDeclarationError(node, message, symbolName2, firstFileLocations);
          }
        });
      } else {
        const list = arrayFrom(conflictingSymbols.keys()).join(", ");
        diagnostics.add(addRelatedInfo(
          createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list),
          createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file)
        ));
        diagnostics.add(addRelatedInfo(
          createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list),
          createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file)
        ));
      }
    });
    amalgamatedDuplicates = void 0;
  }
  function checkExternalEmitHelpers(location, helpers) {
    if (compilerOptions.importHelpers) {
      const sourceFile = getSourceFileOfNode(location);
      if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 33554432 /* Ambient */)) {
        const helpersModule = resolveHelpersModule(sourceFile, location);
        if (helpersModule !== unknownSymbol) {
          const links = getSymbolLinks(helpersModule);
          links.requestedExternalEmitHelpers ?? (links.requestedExternalEmitHelpers = 0);
          if ((links.requestedExternalEmitHelpers & helpers) !== helpers) {
            const uncheckedHelpers = helpers & ~links.requestedExternalEmitHelpers;
            for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) {
              if (uncheckedHelpers & helper) {
                for (const name of getHelperNames(helper)) {
                  const symbol = resolveSymbol(getSymbol(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */));
                  if (!symbol) {
                    error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name);
                  } else if (helper & 524288 /* ClassPrivateFieldGet */) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4);
                    }
                  } else if (helper & 1048576 /* ClassPrivateFieldSet */) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5);
                    }
                  } else if (helper & 1024 /* SpreadArray */) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3);
                    }
                  }
                }
              }
            }
          }
          links.requestedExternalEmitHelpers |= helpers;
        }
      }
    }
  }
  function getHelperNames(helper) {
    switch (helper) {
      case 1 /* Extends */:
        return ["__extends"];
      case 2 /* Assign */:
        return ["__assign"];
      case 4 /* Rest */:
        return ["__rest"];
      case 8 /* Decorate */:
        return legacyDecorators ? ["__decorate"] : ["__esDecorate", "__runInitializers"];
      case 16 /* Metadata */:
        return ["__metadata"];
      case 32 /* Param */:
        return ["__param"];
      case 64 /* Awaiter */:
        return ["__awaiter"];
      case 128 /* Generator */:
        return ["__generator"];
      case 256 /* Values */:
        return ["__values"];
      case 512 /* Read */:
        return ["__read"];
      case 1024 /* SpreadArray */:
        return ["__spreadArray"];
      case 2048 /* Await */:
        return ["__await"];
      case 4096 /* AsyncGenerator */:
        return ["__asyncGenerator"];
      case 8192 /* AsyncDelegator */:
        return ["__asyncDelegator"];
      case 16384 /* AsyncValues */:
        return ["__asyncValues"];
      case 32768 /* ExportStar */:
        return ["__exportStar"];
      case 65536 /* ImportStar */:
        return ["__importStar"];
      case 131072 /* ImportDefault */:
        return ["__importDefault"];
      case 262144 /* MakeTemplateObject */:
        return ["__makeTemplateObject"];
      case 524288 /* ClassPrivateFieldGet */:
        return ["__classPrivateFieldGet"];
      case 1048576 /* ClassPrivateFieldSet */:
        return ["__classPrivateFieldSet"];
      case 2097152 /* ClassPrivateFieldIn */:
        return ["__classPrivateFieldIn"];
      case 4194304 /* SetFunctionName */:
        return ["__setFunctionName"];
      case 8388608 /* PropKey */:
        return ["__propKey"];
      case 16777216 /* AddDisposableResourceAndDisposeResources */:
        return ["__addDisposableResource", "__disposeResources"];
      case 33554432 /* RewriteRelativeImportExtension */:
        return ["__rewriteRelativeImportExtension"];
      default:
        return Debug.fail("Unrecognized helper");
    }
  }
  function resolveHelpersModule(file, errorNode) {
    const links = getNodeLinks(file);
    if (!links.externalHelpersModule) {
      links.externalHelpersModule = resolveExternalModule(getImportHelpersImportSpecifier(file), externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
    }
    return links.externalHelpersModule;
  }
  function checkGrammarModifiers(node) {
    var _a;
    const quickResult = reportObviousDecoratorErrors(node) || reportObviousModifierErrors(node);
    if (quickResult !== void 0) {
      return quickResult;
    }
    if (isParameter(node) && parameterIsThisKeyword(node)) {
      return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters);
    }
    const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & 7 /* BlockScoped */ : 0 /* None */;
    let lastStatic, lastDeclare, lastAsync, lastOverride, firstDecorator;
    let flags = 0 /* None */;
    let sawExportBeforeDecorators = false;
    let hasLeadingDecorators = false;
    for (const modifier of node.modifiers) {
      if (isDecorator(modifier)) {
        if (!nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) {
          if (node.kind === 174 /* MethodDeclaration */ && !nodeIsPresent(node.body)) {
            return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
          } else {
            return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here);
          }
        } else if (legacyDecorators && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */)) {
          const accessors = getAllAccessorDeclarationsForDeclaration(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 & ~(2080 /* ExportDefault */ | 32768 /* Decorator */)) {
          return grammarErrorOnNode(modifier, Diagnostics.Decorators_are_not_valid_here);
        }
        if (hasLeadingDecorators && flags & 98303 /* 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 |= 32768 /* Decorator */;
        if (!(flags & 98303 /* Modifier */)) {
          hasLeadingDecorators = true;
        } else if (flags & 32 /* Export */) {
          sawExportBeforeDecorators = true;
        }
        firstDecorator ?? (firstDecorator = modifier);
      } else {
        if (modifier.kind !== 148 /* ReadonlyKeyword */) {
          if (node.kind === 171 /* PropertySignature */ || node.kind === 173 /* MethodSignature */) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind));
          }
          if (node.kind === 181 /* 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 === 168 /* 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 !== 266 /* EnumDeclaration */ && node.kind !== 168 /* TypeParameter */) {
              return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(87 /* ConstKeyword */));
            }
            const parent = isJSDocTemplateTag(node.parent) && getEffectiveJSDocHost(node.parent) || node.parent;
            if (node.kind === 168 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent) || isClassLike(parent) || isFunctionTypeNode(parent) || isConstructorTypeNode(parent) || isCallSignatureDeclaration(parent) || isConstructSignatureDeclaration(parent) || isMethodSignature(parent))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind));
            }
            break;
          }
          case 164 /* OverrideKeyword */:
            if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override");
            } else if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async");
            }
            flags |= 16 /* Override */;
            lastOverride = modifier;
            break;
          case 125 /* PublicKeyword */:
          case 124 /* ProtectedKeyword */:
          case 123 /* PrivateKeyword */:
            const text = visibilityToString(modifierToFlag(modifier.kind));
            if (flags & 7 /* AccessibilityModifier */) {
              return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen);
            } else if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override");
            } else if (flags & 256 /* Static */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
            } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
            } else if (flags & 64 /* 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 & 256 /* Static */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor");
            } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
            } else if (node.kind === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
            } else if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
            } else if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override");
            }
            flags |= 256 /* Static */;
            lastStatic = modifier;
            break;
          case 129 /* AccessorKeyword */:
            if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly");
            } else if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare");
            } else if (node.kind !== 172 /* PropertyDeclaration */) {
              return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration);
            }
            flags |= 512 /* Accessor */;
            break;
          case 148 /* ReadonlyKeyword */:
            if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly");
            } else if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */ && node.kind !== 181 /* IndexSignature */ && node.kind !== 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor");
            }
            flags |= 8 /* Readonly */;
            break;
          case 95 /* ExportKeyword */:
            if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later
            node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 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 & 32 /* Export */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export");
            } else if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
            } else if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
            } else if (flags & 1024 /* 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 === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
            } else if (blockScopeKind === 4 /* Using */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export");
            } else if (blockScopeKind === 6 /* AwaitUsing */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export");
            }
            flags |= 32 /* Export */;
            break;
          case 90 /* DefaultKeyword */:
            const container = node.parent.kind === 307 /* SourceFile */ ? node.parent : node.parent.parent;
            if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) {
              return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
            } else if (blockScopeKind === 4 /* Using */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default");
            } else if (blockScopeKind === 6 /* AwaitUsing */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default");
            } else if (!(flags & 32 /* 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 |= 2048 /* Default */;
            break;
          case 138 /* DeclareKeyword */:
            if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (flags & 16 /* 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 === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
            } else if (blockScopeKind === 4 /* Using */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare");
            } else if (blockScopeKind === 6 /* AwaitUsing */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare");
            } else if (node.parent.flags & 33554432 /* Ambient */ && node.parent.kind === 268 /* 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 & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor");
            }
            flags |= 128 /* Ambient */;
            lastDeclare = modifier;
            break;
          case 128 /* AbstractKeyword */:
            if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract");
            }
            if (node.kind !== 263 /* ClassDeclaration */ && node.kind !== 185 /* ConstructorType */) {
              if (node.kind !== 174 /* MethodDeclaration */ && node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 177 /* GetAccessor */ && node.kind !== 178 /* SetAccessor */) {
                return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
              }
              if (!(node.parent.kind === 263 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 64 /* Abstract */))) {
                const message = node.kind === 172 /* 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 & 256 /* Static */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
              }
              if (flags & 2 /* Private */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
              }
              if (flags & 1024 /* Async */ && lastAsync) {
                return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
              }
              if (flags & 16 /* Override */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override");
              }
              if (flags & 512 /* 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 |= 64 /* Abstract */;
            break;
          case 134 /* AsyncKeyword */:
            if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async");
            } else if (flags & 128 /* Ambient */ || node.parent.flags & 33554432 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (node.kind === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
            }
            if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
            }
            flags |= 1024 /* Async */;
            lastAsync = modifier;
            break;
          case 103 /* InKeyword */:
          case 147 /* OutKeyword */: {
            const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 8192 /* In */ : 16384 /* Out */;
            const inOutText = modifier.kind === 103 /* InKeyword */ ? "in" : "out";
            const parent = isJSDocTemplateTag(node.parent) && (getEffectiveJSDocHost(node.parent) || find((_a = getJSDocRoot(node.parent)) == null ? void 0 : _a.tags, isJSDocTypedefTag)) || node.parent;
            if (node.kind !== 168 /* TypeParameter */ || parent && !(isInterfaceDeclaration(parent) || isClassLike(parent) || isTypeAliasDeclaration(parent) || isJSDocTypedefTag(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 & 8192 /* In */ && flags & 16384 /* Out */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out");
            }
            flags |= inOutFlag;
            break;
          }
        }
      }
    }
    if (node.kind === 176 /* Constructor */) {
      if (flags & 256 /* Static */) {
        return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
      }
      if (flags & 16 /* Override */) {
        return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override");
      }
      if (flags & 1024 /* Async */) {
        return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
      }
      return false;
    } else if ((node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */) && flags & 128 /* Ambient */) {
      return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
    } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
    } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && node.dotDotDotToken) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
    }
    if (flags & 1024 /* 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 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 176 /* Constructor */:
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 181 /* IndexSignature */:
      case 267 /* ModuleDeclaration */:
      case 272 /* ImportDeclaration */:
      case 271 /* ImportEqualsDeclaration */:
      case 278 /* ExportDeclaration */:
      case 277 /* ExportAssignment */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 169 /* Parameter */:
      case 168 /* TypeParameter */:
        return void 0;
      case 175 /* ClassStaticBlockDeclaration */:
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
      case 270 /* NamespaceExportDeclaration */:
      case 282 /* MissingDeclaration */:
        return find(node.modifiers, isModifier);
      default:
        if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) {
          return void 0;
        }
        switch (node.kind) {
          case 262 /* FunctionDeclaration */:
            return findFirstModifierExcept(node, 134 /* AsyncKeyword */);
          case 263 /* ClassDeclaration */:
          case 185 /* ConstructorType */:
            return findFirstModifierExcept(node, 128 /* AbstractKeyword */);
          case 231 /* ClassExpression */:
          case 264 /* InterfaceDeclaration */:
          case 265 /* TypeAliasDeclaration */:
            return find(node.modifiers, isModifier);
          case 243 /* VariableStatement */:
            return node.declarationList.flags & 4 /* Using */ ? findFirstModifierExcept(node, 135 /* AwaitKeyword */) : find(node.modifiers, isModifier);
          case 266 /* 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 174 /* MethodDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* 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 start = typeParameters.pos - "<".length;
      const end = skipTrivia(file.text, typeParameters.end) + ">".length;
      return grammarErrorAtPos(file, start, end - start, 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 & 33554432 /* 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 (hasEffectiveQuestionToken(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 start = typeArguments.pos - "<".length;
      const end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
      return grammarErrorAtPos(sourceFile, start, end - start, 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 & 64 /* 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 !== 167 /* ComputedPropertyName */) {
      return false;
    }
    const computedPropertyName = node;
    if (computedPropertyName.expression.kind === 226 /* 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 === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ || node.kind === 174 /* MethodDeclaration */
      );
      if (node.flags & 33554432 /* 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 === 305 /* 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 === 167 /* ComputedPropertyName */) {
        checkGrammarComputedPropertyName(name);
      }
      if (prop.kind === 304 /* 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 !== 174 /* 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 304 /* ShorthandPropertyAssignment */:
        case 303 /* 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);
          }
          if (name.kind === 10 /* BigIntLiteral */) {
            addErrorOrSuggestion(
              /*isError*/
              true,
              createDiagnosticForNode(name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name)
            );
          }
          currentKind = 4 /* PropertyAssignment */;
          break;
        case 174 /* MethodDeclaration */:
          currentKind = 8 /* Method */;
          break;
        case 177 /* GetAccessor */:
          currentKind = 1 /* GetAccessor */;
          break;
        case 178 /* 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 === 293 /* 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 === 294 /* 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 === 250 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
      if (!(forInOrOfStatement.flags & 65536 /* 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;
                }
              // fallthrough
              case 7 /* ES2022 */:
              case 99 /* ESNext */:
              case 200 /* Preserve */:
              case 4 /* System */:
                if (languageVersion >= 4 /* ES2017 */) {
                  break;
                }
              // fallthrough
              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_nodenext_or_preserve_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 !== 176 /* 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;
          }
        }
      }
    }
    if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 65536 /* 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 === 261 /* 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 === 249 /* 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 === 249 /* 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 === 249 /* 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 & 33554432 /* Ambient */) && accessor.parent.kind !== 187 /* TypeLiteral */ && accessor.parent.kind !== 264 /* InterfaceDeclaration */) {
      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, 64 /* Abstract */)) {
        return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, Diagnostics._0_expected, "{");
      }
    }
    if (accessor.body) {
      if (hasSyntacticModifier(accessor, 64 /* Abstract */)) {
        return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
      }
      if (accessor.parent.kind === 187 /* TypeLiteral */ || accessor.parent.kind === 264 /* 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 === 177 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter
      );
    }
    if (accessor.kind === 178 /* 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 === 177 /* GetAccessor */ ? 0 : 1);
  }
  function getAccessorThisParameter(accessor) {
    if (accessor.parameters.length === (accessor.kind === 177 /* 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 parent = walkUpParenthesizedTypes(node.parent);
      if (isInJSFile(parent) && isJSDocTypeExpression(parent)) {
        const host2 = getJSDocHost(parent);
        if (host2) {
          parent = getSingleVariableOfVariableStatement(host2) || host2;
        }
      }
      switch (parent.kind) {
        case 260 /* VariableDeclaration */:
          const decl = parent;
          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(parent.name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
          }
          break;
        case 172 /* PropertyDeclaration */:
          if (!isStatic(parent) || !hasEffectiveReadonlyModifier(parent)) {
            return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
          }
          break;
        case 171 /* PropertySignature */:
          if (!hasSyntacticModifier(parent, 8 /* Readonly */)) {
            return grammarErrorOnNode(parent.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 !== 188 /* ArrayType */ && node.type.kind !== 189 /* 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 === 174 /* MethodDeclaration */) {
      if (node.parent.kind === 210 /* 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 & 33554432 /* 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 === 174 /* 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 === 264 /* 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 === 187 /* 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 256 /* LabeledStatement */:
          if (node.label && current.label.escapedText === node.label.escapedText) {
            const isMisplacedContinueLabel = node.kind === 251 /* 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 255 /* SwitchStatement */:
          if (node.kind === 252 /* 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 === 252 /* 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 === 252 /* 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 === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 9 /* NumericLiteral */;
  }
  function isBigIntLiteralExpression(expr) {
    return expr.kind === 10 /* BigIntLiteral */ || expr.kind === 224 /* 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) && isVarConstLike2(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) {
    const nodeFlags = getCombinedNodeFlagsCached(node);
    const blockScopeKind = nodeFlags & 7 /* BlockScoped */;
    if (isBindingPattern(node.name)) {
      switch (blockScopeKind) {
        case 6 /* AwaitUsing */:
          return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "await using");
        case 4 /* Using */:
          return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "using");
      }
    }
    if (node.parent.parent.kind !== 249 /* ForInStatement */ && node.parent.parent.kind !== 250 /* ForOfStatement */) {
      if (nodeFlags & 33554432 /* 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);
        }
        switch (blockScopeKind) {
          case 6 /* AwaitUsing */:
            return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "await using");
          case 4 /* Using */:
            return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "using");
          case 2 /* Const */:
            return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "const");
        }
      }
    }
    if (node.exclamationToken && (node.parent.parent.kind !== 243 /* VariableStatement */ || !node.type || node.initializer || nodeFlags & 33554432 /* 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 (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 32 /* Export */)) {
      checkESModuleMarker(node.name);
    }
    return !!blockScopeKind && 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);
    }
    const blockScopeFlags = declarationList.flags & 7 /* BlockScoped */;
    if ((blockScopeFlags === 4 /* Using */ || blockScopeFlags === 6 /* AwaitUsing */) && isForInStatement(declarationList.parent)) {
      return grammarErrorOnNode(
        declarationList,
        blockScopeFlags === 4 /* Using */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration
      );
    }
    if (blockScopeFlags === 6 /* AwaitUsing */) {
      return checkAwaitGrammar(declarationList);
    }
    return false;
  }
  function allowBlockDeclarations(parent) {
    switch (parent.kind) {
      case 245 /* IfStatement */:
      case 246 /* DoStatement */:
      case 247 /* WhileStatement */:
      case 254 /* WithStatement */:
      case 248 /* ForStatement */:
      case 249 /* ForInStatement */:
      case 250 /* ForOfStatement */:
        return false;
      case 256 /* LabeledStatement */:
        return allowBlockDeclarations(parent.parent);
    }
    return true;
  }
  function checkGrammarForDisallowedBlockScopedVariableStatement(node) {
    if (!allowBlockDeclarations(node.parent)) {
      const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & 7 /* BlockScoped */;
      if (blockScopeKind) {
        const keyword = blockScopeKind === 1 /* Let */ ? "let" : blockScopeKind === 2 /* Const */ ? "const" : blockScopeKind === 4 /* Using */ ? "using" : blockScopeKind === 6 /* AwaitUsing */ ? "await using" : Debug.fail("Unknown BlockScope flag");
        return grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, keyword);
      }
    }
  }
  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, start, length2, message, ...args) {
    const sourceFile = getSourceFileOfNode(nodeForSourceFile);
    if (!hasParseDiagnostics(sourceFile)) {
      diagnostics.add(createFileDiagnostic(sourceFile, start, 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 === 264 /* 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 & 33554432 /* Ambient */) {
      checkAmbientInitializer(node);
    }
    if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || node.flags & 33554432 /* 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 === 264 /* InterfaceDeclaration */ || node.kind === 265 /* TypeAliasDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 278 /* ExportDeclaration */ || node.kind === 277 /* ExportAssignment */ || node.kind === 270 /* NamespaceExportDeclaration */ || hasSyntacticModifier(node, 128 /* Ambient */ | 32 /* Export */ | 2048 /* 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 === 243 /* VariableStatement */) {
        if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
          return true;
        }
      }
    }
    return false;
  }
  function checkGrammarSourceFile(node) {
    return !!(node.flags & 33554432 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
  }
  function checkGrammarStatementInAmbientContext(node) {
    if (node.flags & 33554432 /* 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 === 241 /* Block */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* 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).includes(".");
    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) === 275 /* NamedImports */) {
      return checkGrammarNamedImportsOrExports(node.namedBindings);
    }
    return false;
  }
  function checkGrammarNamedImportsOrExports(namedBindings) {
    return !!forEach(namedBindings.elements, (specifier) => {
      if (specifier.isTypeOnly) {
        return grammarErrorOnFirstToken(
          specifier,
          specifier.kind === 276 /* 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 */ && moduleKind !== 200 /* Preserve */) {
      checkGrammarForDisallowedTrailingComma(nodeArguments);
      if (nodeArguments.length > 1) {
        const importAttributesArgument = nodeArguments[1];
        return grammarErrorOnNode(importAttributesArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_nodenext_or_preserve);
      }
    }
    if (nodeArguments.length === 0 || nodeArguments.length > 2) {
      return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_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) ? tryGetNameFromType(getTypeOfExpression(node.expression)) : void 0;
  }
  function getCombinedModifierFlagsCached(node) {
    if (lastGetCombinedModifierFlagsNode === node) {
      return lastGetCombinedModifierFlagsResult;
    }
    lastGetCombinedModifierFlagsNode = node;
    lastGetCombinedModifierFlagsResult = getCombinedModifierFlags(node);
    return lastGetCombinedModifierFlagsResult;
  }
  function getCombinedNodeFlagsCached(node) {
    if (lastGetCombinedNodeFlagsNode === node) {
      return lastGetCombinedNodeFlagsResult;
    }
    lastGetCombinedNodeFlagsNode = node;
    lastGetCombinedNodeFlagsResult = getCombinedNodeFlags(node);
    return lastGetCombinedNodeFlagsResult;
  }
  function isVarConstLike2(node) {
    const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */;
    return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */;
  }
  function getJSXRuntimeImportSpecifier(file, specifierText) {
    const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0;
    const specifier = file == null ? void 0 : file.imports[jsxImportIndex];
    if (specifier) {
      Debug.assert(nodeIsSynthesized(specifier) && specifier.text === specifierText, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`);
    }
    return specifier;
  }
  function getImportHelpersImportSpecifier(file) {
    Debug.assert(compilerOptions.importHelpers, "Expected importHelpers to be enabled");
    const specifier = file.imports[0];
    Debug.assert(specifier && nodeIsSynthesized(specifier) && specifier.text === "tslib", `Expected sourceFile.imports[0] to be the synthesized tslib import`);
    return specifier;
  }
}
function isNotAccessor(declaration) {
  return !isAccessor(declaration);
}
function isNotOverload(declaration) {
  return declaration.kind !== 262 /* FunctionDeclaration */ && declaration.kind !== 174 /* MethodDeclaration */ || !!declaration.body;
}
function isDeclarationNameOrImportPropertyName(name) {
  switch (name.parent.kind) {
    case 276 /* ImportSpecifier */:
    case 281 /* ExportSpecifier */:
      return isIdentifier(name) || name.kind === 11 /* StringLiteral */;
    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 = {}));
var ReactNames;
((ReactNames2) => {
  ReactNames2.Fragment = "Fragment";
})(ReactNames || (ReactNames = {}));
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: () => 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,
    getDefaultResolutionModeForFile: (file) => host.getDefaultResolutionModeForFile(file),
    getModeForResolutionAtIndex: (file, index) => host.getModeForResolutionAtIndex(file, index),
    getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation)
  };
}
var SymbolTrackerImpl = class _SymbolTrackerImpl {
  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, _b;
    if (((_a = this.inner) == null ? void 0 : _a.trackSymbol) && !this.disableTrackSymbol) {
      if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) {
        this.onDiagnosticReported();
        return true;
      }
      if (!(symbol.flags & 262144 /* TypeParameter */)) ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]);
    }
    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();
    }
  }
  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);
    }
  }
  onDiagnosticReported() {
    this.context.reportedDiagnostic = true;
  }
  reportInferenceFallback(node) {
    var _a;
    if (((_a = this.inner) == null ? void 0 : _a.reportInferenceFallback) && !this.context.suppressReportInferenceFallback) {
      this.onDiagnosticReported();
      this.inner.reportInferenceFallback(node);
    }
  }
  pushErrorFallbackNode(node) {
    var _a, _b;
    return (_b = (_a = this.inner) == null ? void 0 : _a.pushErrorFallbackNode) == null ? void 0 : _b.call(_a, node);
  }
  popErrorFallbackNode() {
    var _a, _b;
    return (_b = (_a = this.inner) == null ? void 0 : _a.popErrorFallbackNode) == null ? void 0 : _b.call(_a);
  }
};

// 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, start, count) {
  if (nodes === void 0) {
    return nodes;
  }
  const length2 = nodes.length;
  if (start === void 0 || start < 0) {
    start = 0;
  }
  if (count === void 0 || count > length2 - start) {
    count = length2 - start;
  }
  let hasTrailingComma;
  let pos = -1;
  let end = -1;
  if (start > 0 || count < length2) {
    hasTrailingComma = nodes.hasTrailingComma && start + count === length2;
  } else {
    pos = nodes.pos;
    end = nodes.end;
    hasTrailingComma = nodes.hasTrailingComma;
  }
  const updated = visitArrayWorker(nodes, visitor, test, start, count);
  if (updated !== nodes) {
    const updatedArray = factory.createNodeArray(updated, hasTrailingComma);
    setTextRangePosEnd(updatedArray, pos, end);
    return updatedArray;
  }
  return nodes;
}
function visitArray(nodes, visitor, test, start, count) {
  if (nodes === void 0) {
    return nodes;
  }
  const length2 = nodes.length;
  if (start === void 0 || start < 0) {
    start = 0;
  }
  if (count === void 0 || count > length2 - start) {
    count = length2 - start;
  }
  return visitArrayWorker(nodes, visitor, test, start, count);
}
function visitArrayWorker(nodes, visitor, test, start, count) {
  let updated;
  const length2 = nodes.length;
  if (start > 0 || count < length2) {
    updated = [];
  }
  for (let i = 0; i < count; i++) {
    const node = nodes[i + start];
    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, start, ensureUseStrict, nodesVisitor = visitNodes2) {
  context.startLexicalEnvironment();
  statements = nodesVisitor(statements, visitor, isStatement, start);
  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 = nullTransformationContext, 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 = {
  [166 /* 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))
    );
  },
  [167 /* ComputedPropertyName */]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateComputedPropertyName(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // Signature elements
  [168 /* 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)
    );
  },
  [169 /* 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)
    );
  },
  [170 /* Decorator */]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateDecorator(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // Type elements
  [171 /* 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)
    );
  },
  [172 /* 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)
    );
  },
  [173 /* 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)
    );
  },
  [174 /* 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)
    );
  },
  [176 /* 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)
    );
  },
  [177 /* 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)
    );
  },
  [178 /* 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)
    );
  },
  [175 /* ClassStaticBlockDeclaration */]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    context.startLexicalEnvironment();
    context.suspendLexicalEnvironment();
    return context.factory.updateClassStaticBlockDeclaration(
      node,
      visitFunctionBody(node.body, visitor, context, nodeVisitor)
    );
  },
  [179 /* 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)
    );
  },
  [180 /* 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)
    );
  },
  [181 /* 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
  [182 /* 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)
    );
  },
  [183 /* 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)
    );
  },
  [184 /* 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))
    );
  },
  [185 /* 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))
    );
  },
  [186 /* 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)
    );
  },
  [187 /* TypeLiteral */]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeLiteralNode(
      node,
      nodesVisitor(node.members, visitor, isTypeElement)
    );
  },
  [188 /* ArrayType */]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateArrayTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode))
    );
  },
  [189 /* TupleType */]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateTupleTypeNode(
      node,
      nodesVisitor(node.elements, visitor, isTypeNode)
    );
  },
  [190 /* OptionalType */]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateOptionalTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [191 /* RestType */]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateRestTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [192 /* UnionType */]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateUnionTypeNode(
      node,
      nodesVisitor(node.types, visitor, isTypeNode)
    );
  },
  [193 /* IntersectionType */]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateIntersectionTypeNode(
      node,
      nodesVisitor(node.types, visitor, isTypeNode)
    );
  },
  [194 /* 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))
    );
  },
  [195 /* InferType */]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateInferTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration))
    );
  },
  [205 /* ImportType */]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)),
      nodeVisitor(node.attributes, visitor, isImportAttributes),
      nodeVisitor(node.qualifier, visitor, isEntityName),
      nodesVisitor(node.typeArguments, visitor, isTypeNode),
      node.isTypeOf
    );
  },
  [302 /* ImportTypeAssertionContainer */]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportTypeAssertionContainer(
      node,
      Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)),
      node.multiLine
    );
  },
  [202 /* 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))
    );
  },
  [196 /* ParenthesizedType */]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateParenthesizedType(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [198 /* TypeOperator */]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeOperatorNode(
      node,
      Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))
    );
  },
  [199 /* 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))
    );
  },
  [200 /* 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)
    );
  },
  [201 /* LiteralType */]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateLiteralTypeNode(
      node,
      Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral))
    );
  },
  [203 /* 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)
    );
  },
  [204 /* 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
  [206 /* ObjectBindingPattern */]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateObjectBindingPattern(
      node,
      nodesVisitor(node.elements, visitor, isBindingElement)
    );
  },
  [207 /* ArrayBindingPattern */]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateArrayBindingPattern(
      node,
      nodesVisitor(node.elements, visitor, isArrayBindingElement)
    );
  },
  [208 /* 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
  [209 /* ArrayLiteralExpression */]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateArrayLiteralExpression(
      node,
      nodesVisitor(node.elements, visitor, isExpression)
    );
  },
  [210 /* ObjectLiteralExpression */]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateObjectLiteralExpression(
      node,
      nodesVisitor(node.properties, visitor, isObjectLiteralElementLike)
    );
  },
  [211 /* 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))
    );
  },
  [212 /* 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))
    );
  },
  [213 /* 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)
    );
  },
  [214 /* 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)
    );
  },
  [215 /* 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))
    );
  },
  [216 /* 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))
    );
  },
  [217 /* ParenthesizedExpression */]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateParenthesizedExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [218 /* 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)
    );
  },
  [219 /* 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)
    );
  },
  [220 /* DeleteExpression */]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateDeleteExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [221 /* TypeOfExpression */]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateTypeOfExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [222 /* VoidExpression */]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateVoidExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [223 /* AwaitExpression */]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateAwaitExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [224 /* PrefixUnaryExpression */]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePrefixUnaryExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))
    );
  },
  [225 /* PostfixUnaryExpression */]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePostfixUnaryExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))
    );
  },
  [226 /* 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))
    );
  },
  [227 /* 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))
    );
  },
  [228 /* 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)
    );
  },
  [229 /* 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)
    );
  },
  [230 /* SpreadElement */]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSpreadElement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [231 /* 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)
    );
  },
  [233 /* 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)
    );
  },
  [234 /* 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))
    );
  },
  [238 /* 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))
    );
  },
  [235 /* 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))
    );
  },
  [236 /* MetaProperty */]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateMetaProperty(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  // Misc
  [239 /* 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
  [241 /* Block */]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateBlock(
      node,
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [243 /* 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))
    );
  },
  [244 /* ExpressionStatement */]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExpressionStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [245 /* 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)
    );
  },
  [246 /* 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))
    );
  },
  [247 /* 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)
    );
  },
  [248 /* 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)
    );
  },
  [249 /* 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)
    );
  },
  [250 /* 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)
    );
  },
  [251 /* ContinueStatement */]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateContinueStatement(
      node,
      nodeVisitor(node.label, visitor, isIdentifier)
    );
  },
  [252 /* BreakStatement */]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateBreakStatement(
      node,
      nodeVisitor(node.label, visitor, isIdentifier)
    );
  },
  [253 /* ReturnStatement */]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateReturnStatement(
      node,
      nodeVisitor(node.expression, visitor, isExpression)
    );
  },
  [254 /* 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))
    );
  },
  [255 /* 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))
    );
  },
  [256 /* 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))
    );
  },
  [257 /* ThrowStatement */]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateThrowStatement(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [258 /* 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)
    );
  },
  [260 /* 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)
    );
  },
  [261 /* VariableDeclarationList */]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateVariableDeclarationList(
      node,
      nodesVisitor(node.declarations, visitor, isVariableDeclaration)
    );
  },
  [262 /* 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)
    );
  },
  [263 /* 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)
    );
  },
  [264 /* 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)
    );
  },
  [265 /* 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))
    );
  },
  [266 /* 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)
    );
  },
  [267 /* 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)
    );
  },
  [268 /* ModuleBlock */]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateModuleBlock(
      node,
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [269 /* CaseBlock */]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateCaseBlock(
      node,
      nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause)
    );
  },
  [270 /* NamespaceExportDeclaration */]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamespaceExportDeclaration(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [271 /* 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))
    );
  },
  [272 /* 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.attributes, visitor, isImportAttributes)
    );
  },
  [300 /* ImportAttributes */]: function visitEachChildOfImportAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportAttributes(
      node,
      nodesVisitor(node.elements, visitor, isImportAttribute),
      node.multiLine
    );
  },
  [301 /* ImportAttribute */]: function visitEachChildOfImportAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportAttribute(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isImportAttributeName)),
      Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression))
    );
  },
  [273 /* 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)
    );
  },
  [274 /* NamespaceImport */]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamespaceImport(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [280 /* NamespaceExport */]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamespaceExport(
      node,
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [275 /* NamedImports */]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamedImports(
      node,
      nodesVisitor(node.elements, visitor, isImportSpecifier)
    );
  },
  [276 /* ImportSpecifier */]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateImportSpecifier(
      node,
      node.isTypeOnly,
      nodeVisitor(node.propertyName, visitor, isModuleExportName),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))
    );
  },
  [277 /* 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))
    );
  },
  [278 /* 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.attributes, visitor, isImportAttributes)
    );
  },
  [279 /* NamedExports */]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateNamedExports(
      node,
      nodesVisitor(node.elements, visitor, isExportSpecifier)
    );
  },
  [281 /* ExportSpecifier */]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExportSpecifier(
      node,
      node.isTypeOnly,
      nodeVisitor(node.propertyName, visitor, isModuleExportName),
      Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleExportName))
    );
  },
  // Module references
  [283 /* ExternalModuleReference */]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateExternalModuleReference(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // JSX
  [284 /* 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))
    );
  },
  [285 /* 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))
    );
  },
  [286 /* 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))
    );
  },
  [287 /* JsxClosingElement */]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxClosingElement(
      node,
      Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression))
    );
  },
  [295 /* 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))
    );
  },
  [288 /* 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))
    );
  },
  [291 /* 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)
    );
  },
  [292 /* JsxAttributes */]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxAttributes(
      node,
      nodesVisitor(node.properties, visitor, isJsxAttributeLike)
    );
  },
  [293 /* JsxSpreadAttribute */]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxSpreadAttribute(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [294 /* JsxExpression */]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateJsxExpression(
      node,
      nodeVisitor(node.expression, visitor, isExpression)
    );
  },
  // Clauses
  [296 /* 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)
    );
  },
  [297 /* DefaultClause */]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateDefaultClause(
      node,
      nodesVisitor(node.statements, visitor, isStatement)
    );
  },
  [298 /* HeritageClause */]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateHeritageClause(
      node,
      nodesVisitor(node.types, visitor, isExpressionWithTypeArguments)
    );
  },
  [299 /* 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
  [303 /* 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))
    );
  },
  [304 /* 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)
    );
  },
  [305 /* SpreadAssignment */]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updateSpreadAssignment(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  // Enum
  [306 /* 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
  [307 /* SourceFile */]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) {
    return context.factory.updateSourceFile(
      node,
      visitLexicalEnvironment(node.statements, visitor, context)
    );
  },
  // Transformation nodes
  [355 /* PartiallyEmittedExpression */]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
    return context.factory.updatePartiallyEmittedExpression(
      node,
      Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))
    );
  },
  [356 /* 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, start, 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 (start && (raw.generatedLine < start.line || start.line === raw.generatedLine && raw.generatedCharacter < start.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 - (start ? start.line : 0);
      const newGeneratedLine = rawGeneratedLine + generatedLine;
      const rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.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 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 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;
}

// 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) && !isNamedExports(node)) return false;
  return some(node.elements, isNamedDefaultReference);
}
function isNamedDefaultReference(e) {
  return moduleExportNameIsDefault(e.propertyName || e.name);
}
function chainBundle(context, transformSourceFile) {
  return transformSourceFileOrBundle;
  function transformSourceFileOrBundle(node) {
    return node.kind === 307 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
  }
  function transformBundle(node) {
    return context.factory.createBundle(map(node.sourceFiles, transformSourceFile));
  }
}
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) {
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const externalImports = [];
  const exportSpecifiers = new IdentifierNameMultiMap();
  const exportedBindings = [];
  const uniqueExports = /* @__PURE__ */ new Map();
  const exportedFunctions = /* @__PURE__ */ new Set();
  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 272 /* ImportDeclaration */:
        externalImports.push(node);
        if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
          hasImportStar = true;
        }
        if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
          hasImportDefault = true;
        }
        break;
      case 271 /* ImportEqualsDeclaration */:
        if (node.moduleReference.kind === 283 /* ExternalModuleReference */) {
          externalImports.push(node);
        }
        break;
      case 278 /* ExportDeclaration */:
        if (node.moduleSpecifier) {
          if (!node.exportClause) {
            externalImports.push(node);
            hasExportStarsToExportValues = true;
          } else {
            externalImports.push(node);
            if (isNamedExports(node.exportClause)) {
              addExportedNamesForExportDeclaration(node);
              hasImportDefault || (hasImportDefault = containsDefaultReference(node.exportClause));
            } else {
              const name = node.exportClause.name;
              const nameText = moduleExportNameTextUnescaped(name);
              if (!uniqueExports.get(nameText)) {
                multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
                uniqueExports.set(nameText, true);
                exportedNames = append(exportedNames, name);
              }
              hasImportStar = true;
            }
          }
        } else {
          addExportedNamesForExportDeclaration(node);
        }
        break;
      case 277 /* ExportAssignment */:
        if (node.isExportEquals && !exportEquals) {
          exportEquals = node;
        }
        break;
      case 243 /* VariableStatement */:
        if (hasSyntacticModifier(node, 32 /* Export */)) {
          for (const decl of node.declarationList.declarations) {
            exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings);
          }
        }
        break;
      case 262 /* FunctionDeclaration */:
        if (hasSyntacticModifier(node, 32 /* Export */)) {
          addExportedFunctionDeclaration(
            node,
            /*name*/
            void 0,
            hasSyntacticModifier(node, 2048 /* Default */)
          );
        }
        break;
      case 263 /* ClassDeclaration */:
        if (hasSyntacticModifier(node, 32 /* Export */)) {
          if (hasSyntacticModifier(node, 2048 /* 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, exportedFunctions, externalHelpersImportDeclaration };
  function addExportedNamesForExportDeclaration(node) {
    for (const specifier of cast(node.exportClause, isNamedExports).elements) {
      const specifierNameText = moduleExportNameTextUnescaped(specifier.name);
      if (!uniqueExports.get(specifierNameText)) {
        const name = specifier.propertyName || specifier.name;
        if (name.kind !== 11 /* StringLiteral */) {
          if (!node.moduleSpecifier) {
            exportSpecifiers.add(name, specifier);
          }
          const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name);
          if (decl) {
            if (decl.kind === 262 /* FunctionDeclaration */) {
              addExportedFunctionDeclaration(decl, specifier.name, moduleExportNameIsDefault(specifier.name));
              continue;
            }
            multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
          }
        }
        uniqueExports.set(specifierNameText, true);
        exportedNames = append(exportedNames, specifier.name);
      }
    }
  }
  function addExportedFunctionDeclaration(node, name, isDefault) {
    exportedFunctions.add(getOriginalNode(node, isFunctionDeclaration));
    if (isDefault) {
      if (!hasExportDefault) {
        multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name ?? context.factory.getDeclarationName(node));
        hasExportDefault = true;
      }
    } else {
      name ?? (name = node.name);
      const nameText = moduleExportNameTextUnescaped(name);
      if (!uniqueExports.get(nameText)) {
        multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
        uniqueExports.set(nameText, true);
      }
    }
  }
}
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;
}
var IdentifierNameMap = class _IdentifierNameMap {
  constructor() {
    this._map = /* @__PURE__ */ new Map();
  }
  get size() {
    return this._map.size;
  }
  has(key) {
    return this._map.has(_IdentifierNameMap.toKey(key));
  }
  get(key) {
    return this._map.get(_IdentifierNameMap.toKey(key));
  }
  set(key, value) {
    this._map.set(_IdentifierNameMap.toKey(key), value);
    return this;
  }
  delete(key) {
    var _a;
    return ((_a = this._map) == null ? void 0 : _a.delete(_IdentifierNameMap.toKey(key))) ?? false;
  }
  clear() {
    this._map.clear();
  }
  values() {
    return this._map.values();
  }
  static toKey(name) {
    if (isGeneratedPrivateIdentifier(name) || isGeneratedIdentifier(name)) {
      const autoGenerate = name.emitNode.autoGenerate;
      if ((autoGenerate.flags & 7 /* KindMask */) === 4 /* Node */) {
        const node = getNodeForGeneratedName(name);
        const baseName = isMemberName(node) && node !== name ? _IdentifierNameMap.toKey(node) : `(generated@${getNodeId(node)})`;
        return formatGeneratedName(
          /*privateName*/
          false,
          autoGenerate.prefix,
          baseName,
          autoGenerate.suffix,
          _IdentifierNameMap.toKey
        );
      } else {
        const baseName = `(auto@${autoGenerate.id})`;
        return formatGeneratedName(
          /*privateName*/
          false,
          autoGenerate.prefix,
          baseName,
          autoGenerate.suffix,
          _IdentifierNameMap.toKey
        );
      }
    }
    if (isPrivateIdentifier(name)) {
      return idText(name).slice(1);
    }
    return idText(name);
  }
};
var IdentifierNameMultiMap = class extends IdentifierNameMap {
  add(key, value) {
    let values = this.get(key);
    if (values) {
      values.push(value);
    } else {
      this.set(key, values = [value]);
    }
    return values;
  }
  remove(key, value) {
    const values = this.get(key);
    if (values) {
      unorderedRemoveItem(values, value);
      if (!values.length) {
        this.delete(key);
      }
    }
  }
};
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 findSuperStatementIndexPathWorker(statements, start, indices) {
  for (let i = start; i < statements.length; i += 1) {
    const statement = statements[i];
    if (getSuperCallFromStatement(statement)) {
      indices.unshift(i);
      return true;
    } else if (isTryStatement(statement) && findSuperStatementIndexPathWorker(statement.tryBlock.statements, 0, indices)) {
      indices.unshift(i);
      return true;
    }
  }
  return false;
}
function findSuperStatementIndexPath(statements, start) {
  const indices = [];
  findSuperStatementIndexPathWorker(statements, start, indices);
  return indices;
}
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 === 172 /* 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, useLegacyDecorators) {
  const decorators = getDecorators(node);
  const parameters = useLegacyDecorators ? getDecoratorsOfParameters(getFirstConstructorWithBody(node)) : void 0;
  if (!some(decorators) && !some(parameters)) {
    return void 0;
  }
  return {
    decorators,
    parameters
  };
}
function getAllDecoratorsOfClassElement(member, parent, useLegacyDecorators) {
  switch (member.kind) {
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
      if (!useLegacyDecorators) {
        return getAllDecoratorsOfMethod(
          member,
          /*useLegacyDecorators*/
          false
        );
      }
      return getAllDecoratorsOfAccessors(
        member,
        parent,
        /*useLegacyDecorators*/
        true
      );
    case 174 /* MethodDeclaration */:
      return getAllDecoratorsOfMethod(member, useLegacyDecorators);
    case 172 /* PropertyDeclaration */:
      return getAllDecoratorsOfProperty(member);
    default:
      return void 0;
  }
}
function getAllDecoratorsOfAccessors(accessor, parent, useLegacyDecorators) {
  if (!accessor.body) {
    return void 0;
  }
  const { firstAccessor, secondAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(parent.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 = useLegacyDecorators ? getDecoratorsOfParameters(setAccessor) : void 0;
  if (!some(decorators) && !some(parameters)) {
    return void 0;
  }
  return {
    decorators,
    parameters,
    getDecorators: getAccessor && getDecorators(getAccessor),
    setDecorators: setAccessor && getDecorators(setAccessor)
  };
}
function getAllDecoratorsOfMethod(method, useLegacyDecorators) {
  if (!method.body) {
    return void 0;
  }
  const decorators = getDecorators(method);
  const parameters = useLegacyDecorators ? getDecoratorsOfParameters(method) : void 0;
  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));
}
function isSimpleParameter(node) {
  return !node.initializer && isIdentifier(node.name);
}
function isSimpleParameterList(nodes) {
  return every(nodes, isSimpleParameter);
}
function rewriteModuleSpecifier(node, compilerOptions) {
  if (!node || !isStringLiteral(node) || !shouldRewriteModuleSpecifier(node.text, compilerOptions)) {
    return node;
  }
  const updatedText = changeExtension(node.text, getOutputExtension(node.text, compilerOptions));
  return updatedText !== node.text ? setOriginalNode(setTextRange(factory.createStringLiteral(updatedText, node.singleQuote), node), node) : node;
}

// src/compiler/transformers/destructuring.ts
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, parent, pattern, value, location) {
  const elements = getElementsOfBindingOrAssignmentPattern(pattern);
  const numElements = elements.length;
  if (numElements !== 1) {
    const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || 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, parent, 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(parent) || 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) || isBigIntLiteral(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/classThis.ts
function createClassThisAssignmentBlock(factory2, classThis, thisExpression = factory2.createThis()) {
  const expression = factory2.createAssignment(classThis, thisExpression);
  const statement = factory2.createExpressionStatement(expression);
  const body = factory2.createBlock(
    [statement],
    /*multiLine*/
    false
  );
  const block = factory2.createClassStaticBlockDeclaration(body);
  getOrCreateEmitNode(block).classThis = classThis;
  return block;
}
function isClassThisAssignmentBlock(node) {
  var _a;
  if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) {
    return false;
  }
  const statement = node.body.statements[0];
  return isExpressionStatement(statement) && isAssignmentExpression(
    statement.expression,
    /*excludeCompoundAssignment*/
    true
  ) && isIdentifier(statement.expression.left) && ((_a = node.emitNode) == null ? void 0 : _a.classThis) === statement.expression.left && statement.expression.right.kind === 110 /* ThisKeyword */;
}
function classHasClassThisAssignment(node) {
  var _a;
  return !!((_a = node.emitNode) == null ? void 0 : _a.classThis) && some(node.members, isClassThisAssignmentBlock);
}
function injectClassThisAssignmentIfMissing(factory2, node, classThis, thisExpression) {
  if (classHasClassThisAssignment(node)) {
    return node;
  }
  const staticBlock = createClassThisAssignmentBlock(factory2, classThis, thisExpression);
  if (node.name) {
    setSourceMapRange(staticBlock.body.statements[0], node.name);
  }
  const members = factory2.createNodeArray([staticBlock, ...node.members]);
  setTextRange(members, node.members);
  const updatedNode = isClassDeclaration(node) ? factory2.updateClassDeclaration(
    node,
    node.modifiers,
    node.name,
    node.typeParameters,
    node.heritageClauses,
    members
  ) : factory2.updateClassExpression(
    node,
    node.modifiers,
    node.name,
    node.typeParameters,
    node.heritageClauses,
    members
  );
  getOrCreateEmitNode(updatedNode).classThis = classThis;
  return updatedNode;
}

// src/compiler/transformers/namedEvaluation.ts
function getAssignedNameOfIdentifier(factory2, name, expression) {
  const original = getOriginalNode(skipOuterExpressions(expression));
  if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && !original.name && hasSyntacticModifier(original, 2048 /* Default */)) {
    return factory2.createStringLiteral("default");
  }
  return factory2.createStringLiteralFromNode(name);
}
function getAssignedNameOfPropertyName(context, name, assignedNameText) {
  const { factory: factory2 } = context;
  if (assignedNameText !== void 0) {
    const assignedName2 = factory2.createStringLiteral(assignedNameText);
    return { assignedName: assignedName2, name };
  }
  if (isPropertyNameLiteral(name) || isPrivateIdentifier(name)) {
    const assignedName2 = factory2.createStringLiteralFromNode(name);
    return { assignedName: assignedName2, name };
  }
  if (isPropertyNameLiteral(name.expression) && !isIdentifier(name.expression)) {
    const assignedName2 = factory2.createStringLiteralFromNode(name.expression);
    return { assignedName: assignedName2, name };
  }
  const assignedName = factory2.getGeneratedNameForNode(name);
  context.hoistVariableDeclaration(assignedName);
  const key = context.getEmitHelperFactory().createPropKeyHelper(name.expression);
  const assignment = factory2.createAssignment(assignedName, key);
  const updatedName = factory2.updateComputedPropertyName(name, assignment);
  return { assignedName, name: updatedName };
}
function createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression = context.factory.createThis()) {
  const { factory: factory2 } = context;
  const expression = context.getEmitHelperFactory().createSetFunctionNameHelper(thisExpression, assignedName);
  const statement = factory2.createExpressionStatement(expression);
  const body = factory2.createBlock(
    [statement],
    /*multiLine*/
    false
  );
  const block = factory2.createClassStaticBlockDeclaration(body);
  getOrCreateEmitNode(block).assignedName = assignedName;
  return block;
}
function isClassNamedEvaluationHelperBlock(node) {
  var _a;
  if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) {
    return false;
  }
  const statement = node.body.statements[0];
  return isExpressionStatement(statement) && isCallToHelper(statement.expression, "___setFunctionName") && statement.expression.arguments.length >= 2 && statement.expression.arguments[1] === ((_a = node.emitNode) == null ? void 0 : _a.assignedName);
}
function classHasExplicitlyAssignedName(node) {
  var _a;
  return !!((_a = node.emitNode) == null ? void 0 : _a.assignedName) && some(node.members, isClassNamedEvaluationHelperBlock);
}
function classHasDeclaredOrExplicitlyAssignedName(node) {
  return !!node.name || classHasExplicitlyAssignedName(node);
}
function injectClassNamedEvaluationHelperBlockIfMissing(context, node, assignedName, thisExpression) {
  if (classHasExplicitlyAssignedName(node)) {
    return node;
  }
  const { factory: factory2 } = context;
  const namedEvaluationBlock = createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression);
  if (node.name) {
    setSourceMapRange(namedEvaluationBlock.body.statements[0], node.name);
  }
  const insertionIndex = findIndex(node.members, isClassThisAssignmentBlock) + 1;
  const leading = node.members.slice(0, insertionIndex);
  const trailing = node.members.slice(insertionIndex);
  const members = factory2.createNodeArray([...leading, namedEvaluationBlock, ...trailing]);
  setTextRange(members, node.members);
  node = isClassDeclaration(node) ? factory2.updateClassDeclaration(
    node,
    node.modifiers,
    node.name,
    node.typeParameters,
    node.heritageClauses,
    members
  ) : factory2.updateClassExpression(
    node,
    node.modifiers,
    node.name,
    node.typeParameters,
    node.heritageClauses,
    members
  );
  getOrCreateEmitNode(node).assignedName = assignedName;
  return node;
}
function finishTransformNamedEvaluation(context, expression, assignedName, ignoreEmptyStringLiteral) {
  if (ignoreEmptyStringLiteral && isStringLiteral(assignedName) && isEmptyStringLiteral(assignedName)) {
    return expression;
  }
  const { factory: factory2 } = context;
  const innerExpression = skipOuterExpressions(expression);
  const updatedExpression = isClassExpression(innerExpression) ? cast(injectClassNamedEvaluationHelperBlockIfMissing(context, innerExpression, assignedName), isClassExpression) : context.getEmitHelperFactory().createSetFunctionNameHelper(innerExpression, assignedName);
  return factory2.restoreOuterExpressions(expression, updatedExpression);
}
function transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText);
  const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral);
  return factory2.updatePropertyAssignment(
    node,
    name,
    initializer
  );
}
function transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.objectAssignmentInitializer);
  const objectAssignmentInitializer = finishTransformNamedEvaluation(context, node.objectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral);
  return factory2.updateShorthandPropertyAssignment(
    node,
    node.name,
    objectAssignmentInitializer
  );
}
function transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer);
  const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral);
  return factory2.updateVariableDeclaration(
    node,
    node.name,
    node.exclamationToken,
    node.type,
    initializer
  );
}
function transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer);
  const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral);
  return factory2.updateParameterDeclaration(
    node,
    node.modifiers,
    node.dotDotDotToken,
    node.name,
    node.questionToken,
    node.type,
    initializer
  );
}
function transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer);
  const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral);
  return factory2.updateBindingElement(
    node,
    node.dotDotDotToken,
    node.propertyName,
    node.name,
    initializer
  );
}
function transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText);
  const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral);
  return factory2.updatePropertyDeclaration(
    node,
    node.modifiers,
    name,
    node.questionToken ?? node.exclamationToken,
    node.type,
    initializer
  );
}
function transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.left, node.right);
  const right = finishTransformNamedEvaluation(context, node.right, assignedName, ignoreEmptyStringLiteral);
  return factory2.updateBinaryExpression(
    node,
    node.left,
    node.operatorToken,
    right
  );
}
function transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) {
  const { factory: factory2 } = context;
  const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : factory2.createStringLiteral(node.isExportEquals ? "" : "default");
  const expression = finishTransformNamedEvaluation(context, node.expression, assignedName, ignoreEmptyStringLiteral);
  return factory2.updateExportAssignment(
    node,
    node.modifiers,
    expression
  );
}
function transformNamedEvaluation(context, node, ignoreEmptyStringLiteral, assignedName) {
  switch (node.kind) {
    case 303 /* PropertyAssignment */:
      return transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedName);
    case 304 /* ShorthandPropertyAssignment */:
      return transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedName);
    case 260 /* VariableDeclaration */:
      return transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedName);
    case 169 /* Parameter */:
      return transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedName);
    case 208 /* BindingElement */:
      return transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedName);
    case 172 /* PropertyDeclaration */:
      return transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedName);
    case 226 /* BinaryExpression */:
      return transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedName);
    case 277 /* ExportAssignment */:
      return transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedName);
  }
}

// src/compiler/transformers/taggedTemplate.ts
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(211 /* PropertyAccessExpression */);
  context.enableSubstitution(212 /* ElementAccessExpression */);
  let currentSourceFile;
  let currentNamespace;
  let currentNamespaceContainerName;
  let currentLexicalScope;
  let currentScopeFirstDeclarationsOfName;
  let enabledSubstitutions = 0 /* None */;
  let applicableSubstitutions;
  return transformSourceFileOrBundle;
  function transformSourceFileOrBundle(node) {
    if (node.kind === 308 /* Bundle */) {
      return transformBundle(node);
    }
    return transformSourceFile(node);
  }
  function transformBundle(node) {
    return factory2.createBundle(
      node.sourceFiles.map(transformSourceFile)
    );
  }
  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;
    onBeforeVisitNode(node);
    const visited = f(node);
    if (currentLexicalScope !== savedCurrentScope) {
      currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
    }
    currentLexicalScope = savedCurrentScope;
    return visited;
  }
  function onBeforeVisitNode(node) {
    switch (node.kind) {
      case 307 /* SourceFile */:
      case 269 /* CaseBlock */:
      case 268 /* ModuleBlock */:
      case 241 /* Block */:
        currentLexicalScope = node;
        currentScopeFirstDeclarationsOfName = void 0;
        break;
      case 263 /* ClassDeclaration */:
      case 262 /* FunctionDeclaration */:
        if (hasSyntacticModifier(node, 128 /* Ambient */)) {
          break;
        }
        if (node.name) {
          recordEmittedDeclarationInScope(node);
        } else {
          Debug.assert(node.kind === 263 /* ClassDeclaration */ || hasSyntacticModifier(node, 2048 /* 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 272 /* ImportDeclaration */:
      case 271 /* ImportEqualsDeclaration */:
      case 277 /* ExportAssignment */:
      case 278 /* ExportDeclaration */:
        return visitElidableStatement(node);
      default:
        return visitorWorker(node);
    }
  }
  function isElisionBlocked(node) {
    const parsed = getParseTreeNode(node);
    if (parsed === node || isExportAssignment(node)) {
      return false;
    }
    if (!parsed || parsed.kind !== node.kind) {
      return true;
    }
    switch (node.kind) {
      case 272 /* ImportDeclaration */:
        Debug.assertNode(parsed, isImportDeclaration);
        if (node.importClause !== parsed.importClause) {
          return true;
        }
        if (node.attributes !== parsed.attributes) {
          return true;
        }
        break;
      case 271 /* ImportEqualsDeclaration */:
        Debug.assertNode(parsed, isImportEqualsDeclaration);
        if (node.name !== parsed.name) {
          return true;
        }
        if (node.isTypeOnly !== parsed.isTypeOnly) {
          return true;
        }
        if (node.moduleReference !== parsed.moduleReference && (isEntityName(node.moduleReference) || isEntityName(parsed.moduleReference))) {
          return true;
        }
        break;
      case 278 /* ExportDeclaration */:
        Debug.assertNode(parsed, isExportDeclaration);
        if (node.exportClause !== parsed.exportClause) {
          return true;
        }
        if (node.attributes !== parsed.attributes) {
          return true;
        }
        break;
    }
    return false;
  }
  function visitElidableStatement(node) {
    if (isElisionBlocked(node)) {
      if (node.transformFlags & 1 /* ContainsTypeScript */) {
        return visitEachChild(node, visitor, context);
      }
      return node;
    }
    switch (node.kind) {
      case 272 /* ImportDeclaration */:
        return visitImportDeclaration(node);
      case 271 /* ImportEqualsDeclaration */:
        return visitImportEqualsDeclaration(node);
      case 277 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 278 /* ExportDeclaration */:
        return visitExportDeclaration(node);
      default:
        Debug.fail("Unhandled ellided statement");
    }
  }
  function namespaceElementVisitor(node) {
    return saveStateAndInvoke(node, namespaceElementVisitorWorker);
  }
  function namespaceElementVisitorWorker(node) {
    if (node.kind === 278 /* ExportDeclaration */ || node.kind === 272 /* ImportDeclaration */ || node.kind === 273 /* ImportClause */ || node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */) {
      return void 0;
    } else if (node.transformFlags & 1 /* ContainsTypeScript */ || hasSyntacticModifier(node, 32 /* Export */)) {
      return visitTypeScript(node);
    }
    return node;
  }
  function getClassElementVisitor(parent) {
    return (node) => saveStateAndInvoke(node, (n) => classElementVisitorWorker(n, parent));
  }
  function classElementVisitorWorker(node, parent) {
    switch (node.kind) {
      case 176 /* Constructor */:
        return visitConstructor(node);
      case 172 /* PropertyDeclaration */:
        return visitPropertyDeclaration(node, parent);
      case 177 /* GetAccessor */:
        return visitGetAccessor(node, parent);
      case 178 /* SetAccessor */:
        return visitSetAccessor(node, parent);
      case 174 /* MethodDeclaration */:
        return visitMethodDeclaration(node, parent);
      case 175 /* ClassStaticBlockDeclaration */:
        return visitEachChild(node, visitor, context);
      case 240 /* SemicolonClassElement */:
        return node;
      case 181 /* IndexSignature */:
        return;
      default:
        return Debug.failBadSyntaxKind(node);
    }
  }
  function getObjectLiteralElementVisitor(parent) {
    return (node) => saveStateAndInvoke(node, (n) => objectLiteralElementVisitorWorker(n, parent));
  }
  function objectLiteralElementVisitorWorker(node, parent) {
    switch (node.kind) {
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
      case 305 /* SpreadAssignment */:
        return visitor(node);
      case 177 /* GetAccessor */:
        return visitGetAccessor(node, parent);
      case 178 /* SetAccessor */:
        return visitSetAccessor(node, parent);
      case 174 /* MethodDeclaration */:
        return visitMethodDeclaration(node, parent);
      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) & 28895 /* TypeScriptModifier */) {
      return void 0;
    } else if (currentNamespace && node.kind === 95 /* ExportKeyword */) {
      return void 0;
    }
    return node;
  }
  function visitTypeScript(node) {
    if (isStatement(node) && hasSyntacticModifier(node, 128 /* 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 164 /* OverrideKeyword */:
      case 87 /* ConstKeyword */:
      case 138 /* DeclareKeyword */:
      case 148 /* ReadonlyKeyword */:
      case 103 /* InKeyword */:
      case 147 /* OutKeyword */:
      // TypeScript accessibility and readonly modifiers are elided
      // falls through
      case 188 /* ArrayType */:
      case 189 /* TupleType */:
      case 190 /* OptionalType */:
      case 191 /* RestType */:
      case 187 /* TypeLiteral */:
      case 182 /* TypePredicate */:
      case 168 /* 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 185 /* ConstructorType */:
      case 184 /* FunctionType */:
      case 186 /* TypeQuery */:
      case 183 /* TypeReference */:
      case 192 /* UnionType */:
      case 193 /* IntersectionType */:
      case 194 /* ConditionalType */:
      case 196 /* ParenthesizedType */:
      case 197 /* ThisType */:
      case 198 /* TypeOperator */:
      case 199 /* IndexedAccessType */:
      case 200 /* MappedType */:
      case 201 /* LiteralType */:
      // TypeScript type nodes are elided.
      // falls through
      case 181 /* IndexSignature */:
        return void 0;
      case 265 /* TypeAliasDeclaration */:
        return factory2.createNotEmittedStatement(node);
      case 270 /* NamespaceExportDeclaration */:
        return void 0;
      case 264 /* InterfaceDeclaration */:
        return factory2.createNotEmittedStatement(node);
      case 263 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 231 /* ClassExpression */:
        return visitClassExpression(node);
      case 298 /* HeritageClause */:
        return visitHeritageClause(node);
      case 233 /* ExpressionWithTypeArguments */:
        return visitExpressionWithTypeArguments(node);
      case 210 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 176 /* Constructor */:
      case 172 /* PropertyDeclaration */:
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 175 /* ClassStaticBlockDeclaration */:
        return Debug.fail("Class and object literal elements must be visited with their respective visitors");
      case 262 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 218 /* FunctionExpression */:
        return visitFunctionExpression(node);
      case 219 /* ArrowFunction */:
        return visitArrowFunction(node);
      case 169 /* Parameter */:
        return visitParameter(node);
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node);
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        return visitAssertionExpression(node);
      case 238 /* SatisfiesExpression */:
        return visitSatisfiesExpression(node);
      case 213 /* CallExpression */:
        return visitCallExpression(node);
      case 214 /* NewExpression */:
        return visitNewExpression(node);
      case 215 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 235 /* NonNullExpression */:
        return visitNonNullExpression(node);
      case 266 /* EnumDeclaration */:
        return visitEnumDeclaration(node);
      case 243 /* VariableStatement */:
        return visitVariableStatement(node);
      case 260 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 267 /* ModuleDeclaration */:
        return visitModuleDeclaration(node);
      case 271 /* ImportEqualsDeclaration */:
        return visitImportEqualsDeclaration(node);
      case 285 /* JsxSelfClosingElement */:
        return visitJsxSelfClosingElement(node);
      case 286 /* 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 varDecl = factory2.createVariableDeclaration(
        factory2.getLocalName(
          node,
          /*allowComments*/
          false,
          /*allowSourceMaps*/
          false
        ),
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        iife
      );
      setOriginalNode(varDecl, node);
      const varStatement = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList([varDecl], 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 */) {
        return [
          statement,
          factory2.createExternalModuleExport(factory2.getDeclarationName(
            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, container));
        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, container)
        ));
        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 === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 172 /* PropertyDeclaration */;
  }
  function shouldAddReturnTypeMetadata(node) {
    return node.kind === 174 /* MethodDeclaration */;
  }
  function shouldAddParamTypesMetadata(node) {
    switch (node.kind) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        return getFirstConstructorWithBody(node) !== void 0;
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* 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 (legacyDecorators && isComputedPropertyName(name) && hasDecorators(member)) {
      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, parent) {
    const isAmbient = node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 64 /* Abstract */);
    if (isAmbient && !(legacyDecorators && hasDecorators(node))) {
      return void 0;
    }
    let modifiers = isClassLike(parent) ? !isAmbient ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent);
    if (isAmbient) {
      return factory2.updatePropertyDeclaration(
        node,
        concatenate(modifiers, factory2.createModifiersFromModifierFlags(128 /* 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 transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) {
    const superStatementIndex = superPath[superPathDepth];
    const superStatement = statementsIn[superStatementIndex];
    addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset));
    if (isTryStatement(superStatement)) {
      const tryBlockStatements = [];
      transformConstructorBodyWorker(
        tryBlockStatements,
        superStatement.tryBlock.statements,
        /*statementOffset*/
        0,
        superPath,
        superPathDepth + 1,
        initializerStatements
      );
      const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements);
      setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements);
      statementsOut.push(factory2.updateTryStatement(
        superStatement,
        factory2.updateBlock(superStatement.tryBlock, tryBlockStatements),
        visitNode(superStatement.catchClause, visitor, isCatchClause),
        visitNode(superStatement.finallyBlock, visitor, isBlock)
      ));
    } else {
      addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1));
      addRange(statementsOut, initializerStatements);
    }
    addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1));
  }
  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 superPath = findSuperStatementIndexPath(body.statements, prologueStatementCount);
    const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment);
    if (superPath.length) {
      transformConstructorBodyWorker(
        statements,
        body.statements,
        prologueStatementCount,
        superPath,
        /*superPathDepth*/
        0,
        parameterPropertyAssignments
      );
    } else {
      addRange(statements, parameterPropertyAssignments);
      addRange(statements, visitNodes2(body.statements, visitor, isStatement, prologueStatementCount));
    }
    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, parent) {
    if (!(node.transformFlags & 1 /* ContainsTypeScript */)) {
      return node;
    }
    if (!shouldEmitFunctionLikeDeclaration(node)) {
      return void 0;
    }
    let modifiers = isClassLike(parent) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent);
    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, 64 /* Abstract */));
  }
  function visitGetAccessor(node, parent) {
    if (!(node.transformFlags & 1 /* ContainsTypeScript */)) {
      return node;
    }
    if (!shouldEmitAccessorDeclaration(node)) {
      return void 0;
    }
    let modifiers = isClassLike(parent) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent);
    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, parent) {
    if (!(node.transformFlags & 1 /* ContainsTypeScript */)) {
      return node;
    }
    if (!shouldEmitAccessorDeclaration(node)) {
      return void 0;
    }
    let modifiers = isClassLike(parent) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike);
    modifiers = injectClassElementTypeMetadata(modifiers, node, parent);
    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 */ | 16 /* ExpressionsWithTypeArguments */));
    if (isAssertionExpression(innerExpression) || isSatisfiesExpression(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 evaluated = resolver.getEnumMemberValue(member);
    const valueExpression = transformEnumMemberDeclarationValue(member, evaluated == null ? void 0 : evaluated.value);
    const innerAssignment = factory2.createAssignment(
      factory2.createElementAccessExpression(
        currentNamespaceContainerName,
        name
      ),
      valueExpression
    );
    const outerAssignment = typeof (evaluated == null ? void 0 : evaluated.value) === "string" || (evaluated == null ? void 0 : evaluated.isSyntacticallyString) ? innerAssignment : factory2.createAssignment(
      factory2.createElementAccessExpression(
        currentNamespaceContainerName,
        innerAssignment
      ),
      name
    );
    return setTextRange(
      factory2.createExpressionStatement(
        setTextRange(
          outerAssignment,
          member
        )
      ),
      member
    );
  }
  function transformEnumMemberDeclarationValue(member, constantValue) {
    if (constantValue !== void 0) {
      return typeof constantValue === "string" ? factory2.createStringLiteral(constantValue) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(-constantValue)) : factory2.createNumericLiteral(constantValue);
    } 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 === 307 /* 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 === 266 /* 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 === 268 /* 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 !== 268 /* ModuleBlock */) {
      setEmitFlags(block, getEmitFlags(block) | 3072 /* NoComments */);
    }
    return block;
  }
  function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
    if (moduleDeclaration.body.kind === 267 /* 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 ? factory2.updateImportDeclaration(
      node,
      /*modifiers*/
      void 0,
      importClause,
      node.moduleSpecifier,
      node.attributes
    ) : 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 === 274 /* NamespaceImport */) {
      return shouldEmitAliasDeclaration(node) ? node : void 0;
    } else {
      const allowEmpty = compilerOptions.verbatimModuleSyntax;
      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 factory2.updateExportDeclaration(
        node,
        node.modifiers,
        node.isTypeOnly,
        node.exportClause,
        node.moduleSpecifier,
        node.attributes
      );
    }
    const allowEmpty = !!compilerOptions.verbatimModuleSyntax;
    const exportClause = visitNode(
      node.exportClause,
      (bindings) => visitNamedExportBindings(bindings, allowEmpty),
      isNamedExportBindings
    );
    return exportClause ? factory2.updateExportDeclaration(
      node,
      /*modifiers*/
      void 0,
      node.isTypeOnly,
      exportClause,
      node.moduleSpecifier,
      node.attributes
    ) : 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)) {
      if (!shouldEmitAliasDeclaration(node)) {
        return void 0;
      }
      return visitEachChild(node, visitor, context);
    }
    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, 32 /* Export */);
  }
  function isExternalModuleExport(node) {
    return currentNamespace === void 0 && hasSyntacticModifier(node, 32 /* Export */);
  }
  function isNamedExternalModuleExport(node) {
    return isExternalModuleExport(node) && !hasSyntacticModifier(node, 2048 /* Default */);
  }
  function isDefaultExternalModuleExport(node) {
    return isExternalModuleExport(node) && hasSyntacticModifier(node, 2048 /* 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(304 /* ShorthandPropertyAssignment */);
      context.enableEmitNotification(267 /* ModuleDeclaration */);
    }
  }
  function isTransformedModuleDeclaration(node) {
    return getOriginalNode(node).kind === 267 /* ModuleDeclaration */;
  }
  function isTransformedEnumDeclaration(node) {
    return getOriginalNode(node).kind === 266 /* 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 211 /* PropertyAccessExpression */:
        return substitutePropertyAccessExpression(node);
      case 212 /* 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 !== 307 /* SourceFile */) {
        const substitute = applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 267 /* ModuleDeclaration */ || applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 266 /* 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) : constantValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(-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) || 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 = 0 /* None */;
  let classAliases;
  let pendingExpressions;
  let pendingStatements;
  let lexicalEnvironment;
  const lexicalEnvironmentMap = /* @__PURE__ */ new Map();
  const noSubstitution = /* @__PURE__ */ new Set();
  let currentClassContainer;
  let currentClassElement;
  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 263 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 231 /* ClassExpression */:
        return visitClassExpression(node);
      case 175 /* ClassStaticBlockDeclaration */:
      case 172 /* PropertyDeclaration */:
        return Debug.fail("Use `classElementVisitor` instead.");
      case 303 /* PropertyAssignment */:
        return visitPropertyAssignment(node);
      case 243 /* VariableStatement */:
        return visitVariableStatement(node);
      case 260 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 169 /* Parameter */:
        return visitParameterDeclaration(node);
      case 208 /* BindingElement */:
        return visitBindingElement(node);
      case 277 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 81 /* PrivateIdentifier */:
        return visitPrivateIdentifier(node);
      case 211 /* PropertyAccessExpression */:
        return visitPropertyAccessExpression(node);
      case 212 /* ElementAccessExpression */:
        return visitElementAccessExpression(node);
      case 224 /* PrefixUnaryExpression */:
      case 225 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          false
        );
      case 226 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          false
        );
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          false
        );
      case 213 /* CallExpression */:
        return visitCallExpression(node);
      case 244 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 215 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 248 /* ForStatement */:
        return visitForStatement(node);
      case 110 /* ThisKeyword */:
        return visitThisExpression(node);
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
        return setCurrentClassElementAnd(
          /*classElement*/
          void 0,
          fallbackVisitor,
          node
        );
      case 176 /* Constructor */:
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */: {
        return setCurrentClassElementAnd(
          node,
          fallbackVisitor,
          node
        );
      }
      default:
        return fallbackVisitor(node);
    }
  }
  function fallbackVisitor(node) {
    return visitEachChild(node, visitor, context);
  }
  function discardedValueVisitor(node) {
    switch (node.kind) {
      case 224 /* PrefixUnaryExpression */:
      case 225 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          true
        );
      case 226 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          true
        );
      case 356 /* CommaListExpression */:
        return visitCommaListExpression(
          node,
          /*discarded*/
          true
        );
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          true
        );
      default:
        return visitor(node);
    }
  }
  function heritageClauseVisitor(node) {
    switch (node.kind) {
      case 298 /* HeritageClause */:
        return visitEachChild(node, heritageClauseVisitor, context);
      case 233 /* ExpressionWithTypeArguments */:
        return visitExpressionWithTypeArgumentsInHeritageClause(node);
      default:
        return visitor(node);
    }
  }
  function assignmentTargetVisitor(node) {
    switch (node.kind) {
      case 210 /* ObjectLiteralExpression */:
      case 209 /* ArrayLiteralExpression */:
        return visitAssignmentPattern(node);
      default:
        return visitor(node);
    }
  }
  function classElementVisitor(node) {
    switch (node.kind) {
      case 176 /* Constructor */:
        return setCurrentClassElementAnd(
          node,
          visitConstructorDeclaration,
          node
        );
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 174 /* MethodDeclaration */:
        return setCurrentClassElementAnd(
          node,
          visitMethodOrAccessorDeclaration,
          node
        );
      case 172 /* PropertyDeclaration */:
        return setCurrentClassElementAnd(
          node,
          visitPropertyDeclaration,
          node
        );
      case 175 /* ClassStaticBlockDeclaration */:
        return setCurrentClassElementAnd(
          node,
          visitClassStaticBlockDeclaration,
          node
        );
      case 167 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      case 240 /* SemicolonClassElement */:
        return node;
      default:
        return isModifierLike(node) ? modifierVisitor(node) : visitor(node);
    }
  }
  function propertyNameVisitor(node) {
    switch (node.kind) {
      case 167 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      default:
        return visitor(node);
    }
  }
  function accessorFieldResultVisitor(node) {
    switch (node.kind) {
      case 172 /* PropertyDeclaration */:
        return transformFieldInitializer(node);
      case 177 /* GetAccessor */:
      case 178 /* 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)) {
      node = transformNamedEvaluation(context, node);
    }
    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 visitVariableDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitParameterDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitBindingElement(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitExportAssignment(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(
        context,
        node,
        /*ignoreEmptyStringLiteral*/
        true,
        node.isExportEquals ? "" : "default"
      );
    }
    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 setCurrentClassElementAnd(classElement, visitor2, arg) {
    if (classElement !== currentClassElement) {
      const savedCurrentClassElement = currentClassElement;
      currentClassElement = classElement;
      const result = visitor2(arg);
      currentClassElement = savedCurrentClassElement;
      return result;
    }
    return visitor2(arg);
  }
  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 tryGetClassThis() {
    const lex = getClassLexicalEnvironment();
    return lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name);
  }
  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 receiver = isStatic(node) ? tryGetClassThis() ?? factory2.createThis() : factory2.createThis();
    const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver);
    setOriginalNode(getter, node);
    setCommentRange(getter, commentRange);
    setSourceMapRange(getter, sourceMapRange);
    const setterModifiers = factory2.createModifiersFromModifierFlags(modifiersToFlags(modifiers));
    const setter = createAccessorPropertySetRedirector(factory2, node, setterModifiers, setterName, receiver);
    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)) {
      node = transformNamedEvaluation(context, node);
    }
    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
      );
      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 shouldForceDynamicThis() {
    return !!currentClassElement && hasStaticModifier(currentClassElement) && isAccessor(currentClassElement) && isAutoAccessorPropertyDeclaration(getOriginalNode(currentClassElement));
  }
  function ensureDynamicThisIfNeeded(node) {
    if (shouldForceDynamicThis()) {
      const innerExpression = skipOuterExpressions(node);
      if (innerExpression.kind === 110 /* ThisKeyword */) {
        noSubstitution.add(innerExpression);
      }
    }
  }
  function createPrivateIdentifierAccess(info, receiver) {
    receiver = visitNode(receiver, visitor, isExpression);
    ensureDynamicThisIfNeeded(receiver);
    return createPrivateIdentifierAccessHelper(info, receiver);
  }
  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 && currentClassElement && isSuperProperty(node) && isIdentifier(node.name) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (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 && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (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);
          ensureDynamicThisIfNeeded(receiver);
          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 && currentClassElement && isSuperProperty(operand) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (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 clone = nodeIsSynthesized(receiver) ? receiver : factory2.cloneNode(receiver);
    if (receiver.kind === 110 /* ThisKeyword */ && noSubstitution.has(receiver)) {
      noSubstitution.add(clone);
    }
    if (isSimpleInlineableExpression(receiver)) {
      return { readExpression: clone, initializeExpression: void 0 };
    }
    const readExpression = factory2.createTempVariable(hoistVariableDeclaration);
    const initializeExpression = factory2.createAssignment(readExpression, clone);
    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 && currentClassElement && isSuperProperty(node.expression) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_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 && currentClassElement && isSuperProperty(node.tag) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_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) {
      if (isClassThisAssignmentBlock(node)) {
        const result = visitNode(node.body.statements[0].expression, visitor, isExpression);
        if (isAssignmentExpression(
          result,
          /*excludeCompoundAssignment*/
          true
        ) && result.left === result.right) {
          return void 0;
        }
        return result;
      }
      if (isClassNamedEvaluationHelperBlock(node)) {
        return visitNode(node.body.statements[0].expression, visitor, isExpression);
      }
      startLexicalEnvironment();
      let statements = setCurrentClassElementAnd(
        node,
        (statements2) => visitNodes2(statements2, visitor, isStatement),
        node.body.statements
      );
      statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment());
      const iife = factory2.createImmediatelyInvokedArrowFunction(statements);
      setOriginalNode(skipParentheses(iife.expression), node);
      addEmitFlags(skipParentheses(iife.expression), 4 /* AdviseOnEmitNode */);
      setOriginalNode(iife, node);
      setTextRange(iife, node);
      return iife;
    }
  }
  function isAnonymousClassNeedingAssignedName(node) {
    if (isClassExpression(node) && !node.name) {
      const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node);
      if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) {
        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)) {
        node = transformNamedEvaluation(context, node);
        Debug.assertNode(node, isAssignmentExpression);
      }
      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 && currentClassElement && isSuperProperty(node.left) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (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) {
    const visitorFunc = discarded ? discardedValueVisitor : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updateParenthesizedExpression(node, expression);
  }
  function createPrivateIdentifierAssignment(info, receiver, right, operator) {
    receiver = visitNode(receiver, visitor, isExpression);
    right = visitNode(right, visitor, isExpression);
    ensureDynamicThisIfNeeded(receiver);
    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) {
    var _a;
    let facts = 0 /* None */;
    const original = getOriginalNode(node);
    if (isClassLike(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) {
      facts |= 1 /* ClassWasDecorated */;
    }
    if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) {
      facts |= 2 /* NeedsClassConstructorReference */;
    }
    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 */;
        } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) {
          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;
          if (resolver.hasNodeCheckFlag(member, 262144 /* ContainsConstructorReference */)) {
            facts |= 2 /* NeedsClassConstructorReference */;
          }
        } 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, visitor2) {
    var _a;
    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;
      } else if ((_a = node.emitNode) == null ? void 0 : _a.assignedName) {
        if (isStringLiteral(node.emitNode.assignedName)) {
          if (node.emitNode.assignedName.textSourceNode && isIdentifier(node.emitNode.assignedName.textSourceNode)) {
            getPrivateIdentifierEnvironment().data.className = node.emitNode.assignedName.textSourceNode;
          } else if (isIdentifierText(node.emitNode.assignedName.text, languageVersion)) {
            const prefixName = factory2.createIdentifier(node.emitNode.assignedName.text);
            getPrivateIdentifierEnvironment().data.className = prefixName;
          }
        }
      }
    }
    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);
    endClassLexicalEnvironment();
    Debug.assert(lexicalEnvironment === savedLexicalEnvironment);
    currentClassContainer = savedCurrentClassContainer;
    pendingExpressions = savedPendingExpressions;
    return result;
  }
  function visitClassDeclaration(node) {
    return visitInNewClassLexicalEnvironment(node, 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 isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */);
    const isExport = hasSyntacticModifier(node, 32 /* Export */);
    const isDefault = hasSyntacticModifier(node, 2048 /* 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 alias = getClassLexicalEnvironment().classConstructor;
    if (isClassWithConstructorReference && alias) {
      enableSubstitutionForClassAliases();
      classAliases[getOriginalNodeId(node)] = alias;
    }
    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) {
    return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment);
  }
  function visitClassExpressionInNewClassLexicalEnvironment(node, facts) {
    var _a, _b, _c;
    const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */);
    const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node);
    const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */);
    const requiresBlockScopedVar = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */);
    let temp;
    function createClassTempVar() {
      var _a2;
      if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) {
        return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis;
      }
      const temp2 = factory2.createTempVariable(
        requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration,
        /*reservedInNestedScopes*/
        true
      );
      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);
    const 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)) {
      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 (some(staticPropertiesOrClassStaticBlocks)) {
          addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, ((_b = node.emitNode) == null ? void 0 : _b.classThis) ?? factory2.getInternalName(node));
        }
        if (temp) {
          expressions.push(factory2.createAssignment(temp, classExpression));
        } else if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_c = node.emitNode) == null ? void 0 : _c.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);
        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 visitThisExpression(node) {
    if (shouldTransformThisInStaticInitializers && currentClassElement && isClassStaticBlockDeclaration(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) {
      const { classThis, classConstructor } = lexicalEnvironment.data;
      return classThis ?? classConstructor ?? node;
    }
    return node;
  }
  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;
      const classThisAssignmentBlock = find(members, isClassThisAssignmentBlock);
      const classNamedEvaluationHelperBlock = find(members, isClassNamedEvaluationHelperBlock);
      membersArray = append(membersArray, classThisAssignmentBlock);
      membersArray = append(membersArray, classNamedEvaluationHelperBlock);
      membersArray = append(membersArray, syntheticConstructor);
      membersArray = append(membersArray, syntheticStaticBlock);
      const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? filter(members, (member) => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : members;
      membersArray = addRange(membersArray, remainingMembers);
      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 transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements, constructor) {
    const superStatementIndex = superPath[superPathDepth];
    const superStatement = statementsIn[superStatementIndex];
    addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset));
    statementOffset = superStatementIndex + 1;
    if (isTryStatement(superStatement)) {
      const tryBlockStatements = [];
      transformConstructorBodyWorker(
        tryBlockStatements,
        superStatement.tryBlock.statements,
        /*statementOffset*/
        0,
        superPath,
        superPathDepth + 1,
        initializerStatements,
        constructor
      );
      const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements);
      setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements);
      statementsOut.push(factory2.updateTryStatement(
        superStatement,
        factory2.updateBlock(superStatement.tryBlock, tryBlockStatements),
        visitNode(superStatement.catchClause, visitor, isCatchClause),
        visitNode(superStatement.finallyBlock, visitor, isBlock)
      ));
    } else {
      addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1));
      while (statementOffset < statementsIn.length) {
        const statement = statementsIn[statementOffset];
        if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) {
          statementOffset++;
        } else {
          break;
        }
      }
      addRange(statementsOut, initializerStatements);
    }
    addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset));
  }
  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 statementOffset = 0;
    let statements = [];
    const initializerStatements = [];
    const receiver = factory2.createThis();
    addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver);
    if (constructor) {
      const parameterProperties = filter(instanceProperties, (prop) => isParameterPropertyDeclaration(getOriginalNode(prop), constructor));
      const nonParameterProperties = filter(properties, (prop) => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor));
      addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver);
      addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver);
    } else {
      addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver);
    }
    if (constructor == null ? void 0 : constructor.body) {
      statementOffset = factory2.copyPrologue(
        constructor.body.statements,
        statements,
        /*ensureUseStrict*/
        false,
        visitor
      );
      const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset);
      if (superStatementIndices.length) {
        transformConstructorBodyWorker(
          statements,
          constructor.body.statements,
          statementOffset,
          superStatementIndices,
          /*superPathDepth*/
          0,
          initializerStatements,
          constructor
        );
      } else {
        while (statementOffset < constructor.body.statements.length) {
          const statement = constructor.body.statements[statementOffset];
          if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) {
            statementOffset++;
          } else {
            break;
          }
        }
        addRange(statements, initializerStatements);
        addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, statementOffset));
      }
    } else {
      if (needsSyntheticConstructor) {
        statements.push(
          factory2.createExpressionStatement(
            factory2.createCallExpression(
              factory2.createSuper(),
              /*typeArguments*/
              void 0,
              [factory2.createSpreadElement(factory2.createIdentifier("arguments"))]
            )
          )
        );
      }
      addRange(statements, initializerStatements);
    }
    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*/
          ((_a = constructor == null ? void 0 : constructor.body) == null ? void 0 : _a.statements) ?? node.members
        ),
        multiLine
      ),
      /*location*/
      constructor == null ? void 0 : constructor.body
    );
  }
  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) ? setCurrentClassElementAnd(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) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : setCurrentClassElementAnd(
        property,
        () => transformProperty(property, receiver),
        /*arg*/
        void 0
      );
      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 savedCurrentClassElement = currentClassElement;
    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);
    }
    currentClassElement = savedCurrentClassElement;
    return transformed;
  }
  function transformPropertyWorker(property, receiver) {
    const emitAssignment = !useDefineForClassFields;
    if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) {
      property = transformNamedEvaluation(context, property);
    }
    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)) {
      currentClassElement = property;
    }
    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, visitor, isExpression),
              privateIdentifierInfo.brandCheckIdentifier
            );
          } else {
            return createPrivateStaticFieldInitializer(
              factory2,
              privateIdentifierInfo.variableName,
              visitNode(property.initializer, visitor, 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, 64 /* Abstract */)) {
      return void 0;
    }
    let initializer = visitNode(property.initializer, visitor, 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(262 /* FunctionDeclaration */);
      context.enableEmitNotification(218 /* FunctionExpression */);
      context.enableEmitNotification(176 /* Constructor */);
      context.enableEmitNotification(177 /* GetAccessor */);
      context.enableEmitNotification(178 /* SetAccessor */);
      context.enableEmitNotification(174 /* MethodDeclaration */);
      context.enableEmitNotification(172 /* PropertyDeclaration */);
      context.enableEmitNotification(167 /* 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) {
    if (isComputedPropertyName(name)) {
      const cacheAssignment = findComputedPropertyNameCacheAssignment(name);
      const 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.hasNodeCheckFlag(name, 32768 /* BlockScopedBindingInLoop */)) {
          addBlockScopedVariable(generatedName);
        } else {
          hoistVariableDeclaration(generatedName);
        }
        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.hasNodeCheckFlag(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 && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (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)) {
      node = transformNamedEvaluation(context, node);
    }
    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)) {
      node = transformNamedEvaluation(context, node);
    }
    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 218 /* FunctionExpression */:
        if (isArrowFunction(original) || getEmitFlags(node) & 524288 /* AsyncFunctionBody */) {
          break;
        }
      // falls through
      case 262 /* FunctionDeclaration */:
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 174 /* MethodDeclaration */:
      case 172 /* 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 167 /* 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) && !noSubstitution.has(node)) {
      const { facts, classConstructor, classThis } = lexicalEnvironment.data;
      const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor;
      if (substituteThis) {
        return setTextRange(
          setOriginalNode(
            factory2.cloneNode(substituteThis),
            node
          ),
          node
        );
      }
      if (facts & 1 /* ClassWasDecorated */ && legacyDecorators) {
        return factory2.createParenthesizedExpression(factory2.createVoidZero());
      }
    }
    return node;
  }
  function substituteExpressionIdentifier(node) {
    return trySubstituteClassAlias(node) || node;
  }
  function trySubstituteClassAlias(node) {
    if (enabledSubstitutions & 1 /* ClassAliases */) {
      if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) {
        const declaration = resolver.getReferencedValueDeclaration(node);
        if (declaration) {
          const classAlias = classAliases[declaration.id];
          if (classAlias) {
            const clone = factory2.cloneNode(classAlias);
            setSourceMapRange(clone, node);
            setCommentRange(clone, node);
            return clone;
          }
        }
      }
    }
    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 */;
}
function isStaticPropertyDeclaration2(node) {
  return isPropertyDeclaration(node) && hasStaticModifier(node);
}
function isStaticPropertyDeclarationOrClassStaticBlock(node) {
  return isClassStaticBlockDeclaration(node) || isStaticPropertyDeclaration2(node);
}

// 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, container) => setSerializerContextAnd(serializerContext, serializeTypeOfNode, node, container),
    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, container) {
    const accessors = getAllAccessorDeclarations(container.members, node);
    return accessors.setAccessor && getSetAccessorTypeAnnotationNode(accessors.setAccessor) || accessors.getAccessor && getEffectiveReturnTypeNode(accessors.getAccessor);
  }
  function serializeTypeOfNode(node, container) {
    switch (node.kind) {
      case 172 /* PropertyDeclaration */:
      case 169 /* Parameter */:
        return serializeTypeNode(node.type);
      case 178 /* SetAccessor */:
      case 177 /* GetAccessor */:
        return serializeTypeNode(getAccessorTypeNode(node, container));
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
      case 174 /* 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, container));
        }
      }
    }
    return factory2.createArrayLiteralExpression(expressions);
  }
  function getParametersOfDecoratedDeclaration(node, container) {
    if (container && node.kind === 177 /* 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 184 /* FunctionType */:
      case 185 /* ConstructorType */:
        return factory2.createIdentifier("Function");
      case 188 /* ArrayType */:
      case 189 /* TupleType */:
        return factory2.createIdentifier("Array");
      case 182 /* TypePredicate */:
        return node.assertsModifier ? factory2.createVoidZero() : factory2.createIdentifier("Boolean");
      case 136 /* BooleanKeyword */:
        return factory2.createIdentifier("Boolean");
      case 203 /* TemplateLiteralType */:
      case 154 /* StringKeyword */:
        return factory2.createIdentifier("String");
      case 151 /* ObjectKeyword */:
        return factory2.createIdentifier("Object");
      case 201 /* LiteralType */:
        return serializeLiteralOfLiteralTypeNode(node.literal);
      case 150 /* NumberKeyword */:
        return factory2.createIdentifier("Number");
      case 163 /* BigIntKeyword */:
        return getGlobalConstructor("BigInt", 7 /* ES2020 */);
      case 155 /* SymbolKeyword */:
        return getGlobalConstructor("Symbol", 2 /* ES2015 */);
      case 183 /* TypeReference */:
        return serializeTypeReferenceNode(node);
      case 193 /* IntersectionType */:
        return serializeUnionOrIntersectionConstituents(
          node.types,
          /*isIntersection*/
          true
        );
      case 192 /* UnionType */:
        return serializeUnionOrIntersectionConstituents(
          node.types,
          /*isIntersection*/
          false
        );
      case 194 /* ConditionalType */:
        return serializeUnionOrIntersectionConstituents(
          [node.trueType, node.falseType],
          /*isIntersection*/
          false
        );
      case 198 /* TypeOperator */:
        if (node.operator === 148 /* ReadonlyKeyword */) {
          return serializeTypeNode(node.type);
        }
        break;
      case 186 /* TypeQuery */:
      case 199 /* IndexedAccessType */:
      case 200 /* MappedType */:
      case 187 /* TypeLiteral */:
      case 133 /* AnyKeyword */:
      case 159 /* UnknownKeyword */:
      case 197 /* ThisType */:
      case 205 /* ImportType */:
        break;
      // handle JSDoc types from an invalid parse
      case 312 /* JSDocAllType */:
      case 313 /* JSDocUnknownType */:
      case 317 /* JSDocFunctionType */:
      case 318 /* JSDocVariadicType */:
      case 319 /* JSDocNamepathType */:
        break;
      case 314 /* JSDocNullableType */:
      case 315 /* JSDocNonNullableType */:
      case 316 /* 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 224 /* 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 166 /* 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 170 /* Decorator */:
        return void 0;
      case 263 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 231 /* ClassExpression */:
        return visitClassExpression(node);
      case 176 /* Constructor */:
        return visitConstructorDeclaration(node);
      case 174 /* MethodDeclaration */:
        return visitMethodDeclaration(node);
      case 178 /* SetAccessor */:
        return visitSetAccessorDeclaration(node);
      case 177 /* GetAccessor */:
        return visitGetAccessorDeclaration(node);
      case 172 /* PropertyDeclaration */:
        return visitPropertyDeclaration(node);
      case 169 /* 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, 32 /* Export */);
    const isDefault = hasSyntacticModifier(node, 2048 /* 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, 256 /* 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 varInitializer = classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression;
    const varDecl = factory2.createVariableDeclaration(
      declName,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      varInitializer
    );
    setOriginalNode(varDecl, node);
    const varDeclList = factory2.createVariableDeclarationList([varDecl], 1 /* Let */);
    const varStatement = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      varDeclList
    );
    setOriginalNode(varStatement, node);
    setTextRange(varStatement, location);
    setCommentRange(varStatement, node);
    const statements = [varStatement];
    addRange(statements, decorationStatements);
    addConstructorDecorationStatement(statements, node);
    if (isExport) {
      if (isDefault) {
        const exportStatement = factory2.createExportDefault(declName);
        statements.push(exportStatement);
      } else {
        const exportStatement = factory2.createExternalModuleExport(factory2.getDeclarationName(node));
        statements.push(exportStatement);
      }
    }
    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 & 33554432 /* Ambient */ || hasSyntacticModifier(node, 128 /* 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, parent) {
    return nodeOrChildIsDecorated(
      /*useLegacyDecorators*/
      true,
      member,
      parent
    ) && 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, 128 /* Ambient */)
    );
    const descriptor = isPropertyDeclaration(member) && !hasAccessorModifier(member) ? factory2.createVoidZero() : factory2.createNull();
    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,
      /*useLegacyDecorators*/
      true
    );
    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.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */)) {
      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.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) {
        const declaration = resolver.getReferencedValueDeclaration(node);
        if (declaration) {
          const classAlias = classAliases[declaration.id];
          if (classAlias) {
            const clone = factory2.cloneNode(classAlias);
            setSourceMapRange(clone, node);
            setCommentRange(clone, node);
            return clone;
          }
        }
      }
    }
    return void 0;
  }
}

// src/compiler/transformers/esDecorators.ts
function transformESDecorators(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    startLexicalEnvironment,
    endLexicalEnvironment,
    hoistVariableDeclaration
  } = context;
  const languageVersion = getEmitScriptTarget(context.getCompilerOptions());
  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 170 /* Decorator */:
        return Debug.fail("Use `modifierVisitor` instead.");
      case 263 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 231 /* ClassExpression */:
        return visitClassExpression(node);
      case 176 /* Constructor */:
      case 172 /* PropertyDeclaration */:
      case 175 /* ClassStaticBlockDeclaration */:
        return Debug.fail("Not supported outside of a class. Use 'classElementVisitor' instead.");
      case 169 /* Parameter */:
        return visitParameterDeclaration(node);
      // Support NamedEvaluation to ensure the correct class name for class expressions.
      case 226 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          false
        );
      case 303 /* PropertyAssignment */:
        return visitPropertyAssignment(node);
      case 260 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 208 /* BindingElement */:
        return visitBindingElement(node);
      case 277 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 110 /* ThisKeyword */:
        return visitThisExpression(node);
      case 248 /* ForStatement */:
        return visitForStatement(node);
      case 244 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 356 /* CommaListExpression */:
        return visitCommaListExpression(
          node,
          /*discarded*/
          false
        );
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          false
        );
      case 355 /* PartiallyEmittedExpression */:
        return visitPartiallyEmittedExpression(
          node,
          /*discarded*/
          false
        );
      case 213 /* CallExpression */:
        return visitCallExpression(node);
      case 215 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 224 /* PrefixUnaryExpression */:
      case 225 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          false
        );
      case 211 /* PropertyAccessExpression */:
        return visitPropertyAccessExpression(node);
      case 212 /* ElementAccessExpression */:
        return visitElementAccessExpression(node);
      case 167 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      case 174 /* MethodDeclaration */:
      // object literal methods and accessors
      case 178 /* SetAccessor */:
      case 177 /* GetAccessor */:
      case 218 /* FunctionExpression */:
      case 262 /* FunctionDeclaration */: {
        enterOther();
        const result = visitEachChild(node, fallbackVisitor, context);
        exitOther();
        return result;
      }
      default:
        return visitEachChild(node, fallbackVisitor, context);
    }
  }
  function fallbackVisitor(node) {
    switch (node.kind) {
      case 170 /* Decorator */:
        return void 0;
      default:
        return visitor(node);
    }
  }
  function modifierVisitor(node) {
    switch (node.kind) {
      case 170 /* Decorator */:
        return void 0;
      default:
        return node;
    }
  }
  function classElementVisitor(node) {
    switch (node.kind) {
      case 176 /* Constructor */:
        return visitConstructorDeclaration(node);
      case 174 /* MethodDeclaration */:
        return visitMethodDeclaration(node);
      case 177 /* GetAccessor */:
        return visitGetAccessorDeclaration(node);
      case 178 /* SetAccessor */:
        return visitSetAccessorDeclaration(node);
      case 172 /* PropertyDeclaration */:
        return visitPropertyDeclaration(node);
      case 175 /* ClassStaticBlockDeclaration */:
        return visitClassStaticBlockDeclaration(node);
      default:
        return visitor(node);
    }
  }
  function discardedValueVisitor(node) {
    switch (node.kind) {
      case 224 /* PrefixUnaryExpression */:
      case 225 /* PostfixUnaryExpression */:
        return visitPreOrPostfixUnaryExpression(
          node,
          /*discarded*/
          true
        );
      case 226 /* BinaryExpression */:
        return visitBinaryExpression(
          node,
          /*discarded*/
          true
        );
      case 356 /* CommaListExpression */:
        return visitCommaListExpression(
          node,
          /*discarded*/
          true
        );
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(
          node,
          /*discarded*/
          true
        );
      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) {
    const metadataReference = factory2.createUniqueName("_metadata", 16 /* Optimistic */ | 32 /* FileLevel */);
    let instanceMethodExtraInitializersName;
    let staticMethodExtraInitializersName;
    let hasStaticInitializers = false;
    let hasNonAmbientInstanceFields = false;
    let hasStaticPrivateClassElements = false;
    let classThis2;
    let pendingStaticInitializers;
    let pendingInstanceInitializers;
    if (nodeIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    )) {
      const needsUniqueClassThis = some(node.members, (member) => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member));
      classThis2 = factory2.createUniqueName(
        "_classThis",
        needsUniqueClassThis ? 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */ : 16 /* Optimistic */ | 32 /* FileLevel */
      );
    }
    for (const member of node.members) {
      if (isMethodOrAccessor(member) && nodeOrChildIsDecorated(
        /*useLegacyDecorators*/
        false,
        member,
        node
      )) {
        if (hasStaticModifier(member)) {
          if (!staticMethodExtraInitializersName) {
            staticMethodExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */);
            const initializer = emitHelpers().createRunInitializersHelper(classThis2 ?? factory2.createThis(), staticMethodExtraInitializersName);
            setSourceMapRange(initializer, node.name ?? moveRangePastDecorators(node));
            pendingStaticInitializers ?? (pendingStaticInitializers = []);
            pendingStaticInitializers.push(initializer);
          }
        } else {
          if (!instanceMethodExtraInitializersName) {
            instanceMethodExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */);
            const initializer = emitHelpers().createRunInitializersHelper(factory2.createThis(), instanceMethodExtraInitializersName);
            setSourceMapRange(initializer, node.name ?? moveRangePastDecorators(node));
            pendingInstanceInitializers ?? (pendingInstanceInitializers = []);
            pendingInstanceInitializers.push(initializer);
          }
          instanceMethodExtraInitializersName ?? (instanceMethodExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */));
        }
      }
      if (isClassStaticBlockDeclaration(member)) {
        if (!isClassNamedEvaluationHelperBlock(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 (staticMethodExtraInitializersName && instanceMethodExtraInitializersName && hasStaticInitializers && hasNonAmbientInstanceFields && hasStaticPrivateClassElements) {
        break;
      }
    }
    return {
      class: node,
      classThis: classThis2,
      metadataReference,
      instanceMethodExtraInitializersName,
      staticMethodExtraInitializersName,
      hasStaticInitializers,
      hasNonAmbientInstanceFields,
      hasStaticPrivateClassElements,
      pendingStaticInitializers,
      pendingInstanceInitializers
    };
  }
  function transformClassLike(node) {
    startLexicalEnvironment();
    if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    )) {
      node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory2.createStringLiteral(""));
    }
    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,
      /*useLegacyDecorators*/
      false
    ));
    if (classDecorators) {
      classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 16 /* Optimistic */ | 32 /* FileLevel */);
      classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */ | 32 /* FileLevel */);
      classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */);
      Debug.assertIsDefined(classInfo2.classThis);
      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;
      }
    }
    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 */ | 32 /* FileLevel */);
      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]);
    }
    const renamedClassThis = classInfo2.classThis ?? factory2.createThis();
    enterClass(classInfo2);
    leadingBlockStatements = append(leadingBlockStatements, createMetadata(classInfo2.metadataReference, classInfo2.classSuper));
    let members = node.members;
    members = visitNodes2(members, (node2) => isConstructorDeclaration(node2) ? node2 : classElementVisitor(node2), isClassElement);
    members = visitNodes2(members, (node2) => isConstructorDeclaration(node2) ? classElementVisitor(node2) : node2, 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 (some(classInfo2.pendingInstanceInitializers) && !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.staticMethodExtraInitializersName) {
      classDefinitionStatements.push(
        createLet(classInfo2.staticMethodExtraInitializersName, factory2.createArrayLiteralExpression())
      );
    }
    if (classInfo2.instanceMethodExtraInitializersName) {
      classDefinitionStatements.push(
        createLet(classInfo2.instanceMethodExtraInitializersName, 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.memberExtraInitializersName) {
            classDefinitionStatements.push(createLet(memberInfo.memberExtraInitializersName, 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.memberExtraInitializersName) {
            classDefinitionStatements.push(createLet(memberInfo.memberExtraInitializersName, 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", renamedClassThis);
      const classDescriptor = factory2.createObjectLiteralExpression([valueProperty]);
      const classDescriptorAssignment = factory2.createAssignment(classInfo2.classDescriptorName, classDescriptor);
      const classNameReference = factory2.createPropertyAccessExpression(renamedClassThis, "name");
      const esDecorateHelper2 = emitHelpers().createESDecorateHelper(
        factory2.createNull(),
        classDescriptorAssignment,
        classInfo2.classDecoratorsName,
        { kind: "class", name: classNameReference, metadata: classInfo2.metadataReference },
        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));
    }
    leadingBlockStatements.push(createSymbolMetadata(renamedClassThis, classInfo2.metadataReference));
    if (some(classInfo2.pendingStaticInitializers)) {
      for (const initializer of classInfo2.pendingStaticInitializers) {
        const initializerStatement = factory2.createExpressionStatement(initializer);
        setSourceMapRange(initializerStatement, getSourceMapRange(initializer));
        trailingBlockStatements = append(trailingBlockStatements, initializerStatement);
      }
      classInfo2.pendingStaticInitializers = void 0;
    }
    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;
    }
    const leadingStaticBlock = leadingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock(
      leadingBlockStatements,
      /*multiLine*/
      true
    ));
    if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) {
      setInternalEmitFlags(leadingStaticBlock, 32 /* TransformPrivateStaticElements */);
    }
    const trailingStaticBlock = trailingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock(
      trailingBlockStatements,
      /*multiLine*/
      true
    ));
    if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) {
      const newMembers = [];
      const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock);
      if (leadingStaticBlock) {
        addRange(newMembers, members, 0, existingNamedEvaluationHelperBlockIndex + 1);
        newMembers.push(leadingStaticBlock);
        addRange(newMembers, members, existingNamedEvaluationHelperBlockIndex + 1);
      } else {
        addRange(newMembers, members);
      }
      if (syntheticConstructor) {
        newMembers.push(syntheticConstructor);
      }
      if (trailingStaticBlock) {
        newMembers.push(trailingStaticBlock);
      }
      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
      );
      if (classInfo2.classThis) {
        classExpression = injectClassThisAssignmentIfMissing(factory2, classExpression, classInfo2.classThis);
      }
      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);
    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)) {
      const statements = [];
      const originalClass = getOriginalNode(node, isClassLike) ?? node;
      const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default");
      const isExport = hasSyntacticModifier(node, 32 /* Export */);
      const isDefault = hasSyntacticModifier(node, 2048 /* Default */);
      if (!node.name) {
        node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className);
      }
      if (isExport && isDefault) {
        const iife = transformClassLike(node);
        if (node.name) {
          const varDecl = factory2.createVariableDeclaration(
            factory2.getLocalName(node),
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            iife
          );
          setOriginalNode(varDecl, node);
          const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */);
          const varStatement = factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            varDecls
          );
          statements.push(varStatement);
          const exportStatement = factory2.createExportDefault(factory2.getDeclarationName(node));
          setOriginalNode(exportStatement, node);
          setCommentRange(exportStatement, getCommentRange(node));
          setSourceMapRange(exportStatement, moveRangePastDecorators(node));
          statements.push(exportStatement);
        } else {
          const exportStatement = factory2.createExportDefault(iife);
          setOriginalNode(exportStatement, node);
          setCommentRange(exportStatement, getCommentRange(node));
          setSourceMapRange(exportStatement, moveRangePastDecorators(node));
          statements.push(exportStatement);
        }
      } else {
        Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name.");
        const iife = transformClassLike(node);
        const modifierVisitorNoExport = isExport ? (node2) => isExportModifier(node2) ? void 0 : modifierVisitor(node2) : modifierVisitor;
        const modifiers = visitNodes2(node.modifiers, modifierVisitorNoExport, isModifier);
        const declName = 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 varStatement = factory2.createVariableStatement(modifiers, varDecls);
        setOriginalNode(varStatement, node);
        setCommentRange(varStatement, getCommentRange(node));
        statements.push(varStatement);
        if (isExport) {
          const exportStatement = factory2.createExternalModuleExport(declName);
          setOriginalNode(exportStatement, node);
          statements.push(exportStatement);
        }
      }
      return singleOrMany(statements);
    } 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) {
    if (isDecoratedClassLike(node)) {
      const iife = transformClassLike(node);
      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 (some(classInfo2.pendingInstanceInitializers)) {
      const statements = [];
      statements.push(
        factory2.createExpressionStatement(
          factory2.inlineExpressions(classInfo2.pendingInstanceInitializers)
        )
      );
      classInfo2.pendingInstanceInitializers = void 0;
      return statements;
    }
  }
  function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) {
    const superStatementIndex = superPath[superPathDepth];
    const superStatement = statementsIn[superStatementIndex];
    addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset));
    if (isTryStatement(superStatement)) {
      const tryBlockStatements = [];
      transformConstructorBodyWorker(
        tryBlockStatements,
        superStatement.tryBlock.statements,
        /*statementOffset*/
        0,
        superPath,
        superPathDepth + 1,
        initializerStatements
      );
      const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements);
      setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements);
      statementsOut.push(factory2.updateTryStatement(
        superStatement,
        factory2.updateBlock(superStatement.tryBlock, tryBlockStatements),
        visitNode(superStatement.catchClause, visitor, isCatchClause),
        visitNode(superStatement.finallyBlock, visitor, isBlock)
      ));
    } else {
      addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1));
      addRange(statementsOut, initializerStatements);
    }
    addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1));
  }
  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 superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart);
        if (superStatementIndices.length > 0) {
          transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements);
        } 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, classInfo2, createDescriptor) {
    let referencedName;
    let name;
    let initializersName;
    let extraInitializersName;
    let thisArg;
    let descriptorName;
    if (!classInfo2) {
      const modifiers2 = visitNodes2(member.modifiers, modifierVisitor, isModifier);
      enterName();
      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)
        },
        metadata: classInfo2.metadataReference
      };
      if (isMethodOrAccessor(member)) {
        const methodExtraInitializersName = isStatic(member) ? classInfo2.staticMethodExtraInitializersName : classInfo2.instanceMethodExtraInitializersName;
        Debug.assertIsDefined(methodExtraInitializersName);
        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(), methodExtraInitializersName);
        const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression);
        setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member));
        statements.push(esDecorateStatement);
      } else if (isPropertyDeclaration(member)) {
        initializersName = memberInfo.memberInitializersName ?? (memberInfo.memberInitializersName = createHelperVariable(member, "initializers"));
        extraInitializersName = memberInfo.memberExtraInitializersName ?? (memberInfo.memberExtraInitializersName = createHelperVariable(member, "extraInitializers"));
        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,
          extraInitializersName
        );
        const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression);
        setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member));
        statements.push(esDecorateStatement);
      }
    }
    if (name === void 0) {
      enterName();
      name = visitPropertyName(member.name);
      exitName();
    }
    if (!some(modifiers) && (isMethodDeclaration(member) || isPropertyDeclaration(member))) {
      setEmitFlags(name, 1024 /* NoLeadingComments */);
    }
    return { modifiers, referencedName, name, initializersName, extraInitializersName, descriptorName, thisArg };
  }
  function visitMethodDeclaration(node) {
    enterClassElement(node);
    const { modifiers, name, descriptorName } = partialTransformClassElement(node, 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, 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, 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);
    let result;
    if (isClassNamedEvaluationHelperBlock(node)) {
      result = visitEachChild(node, visitor, context);
    } else if (isClassThisAssignmentBlock(node)) {
      const savedClassThis = classThis;
      classThis = void 0;
      result = visitEachChild(node, visitor, context);
      classThis = savedClassThis;
    } else {
      node = visitEachChild(node, visitor, context);
      result = node;
      if (classInfo) {
        classInfo.hasStaticInitializers = true;
        if (some(classInfo.pendingStaticInitializers)) {
          const statements = [];
          for (const initializer of classInfo.pendingStaticInitializers) {
            const initializerStatement = factory2.createExpressionStatement(initializer);
            setSourceMapRange(initializerStatement, getSourceMapRange(initializer));
            statements.push(initializerStatement);
          }
          const body = factory2.createBlock(
            statements,
            /*multiLine*/
            true
          );
          const staticBlock = factory2.createClassStaticBlockDeclaration(body);
          result = [staticBlock, result];
          classInfo.pendingStaticInitializers = void 0;
        }
      }
    }
    exitClassElement();
    return result;
  }
  function visitPropertyDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer));
    }
    enterClassElement(node);
    Debug.assert(!isAmbientPropertyDeclaration(node), "Not yet implemented.");
    const { modifiers, name, initializersName, extraInitializersName, descriptorName, thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0);
    startLexicalEnvironment();
    let initializer = visitNode(node.initializer, visitor, isExpression);
    if (initializersName) {
      initializer = emitHelpers().createRunInitializersHelper(
        thisArg ?? factory2.createThis(),
        initializersName,
        initializer ?? factory2.createVoidZero()
      );
    }
    if (isStatic(node) && classInfo && initializer) {
      classInfo.hasStaticInitializers = true;
    }
    const declarations = endLexicalEnvironment();
    if (some(declarations)) {
      initializer = factory2.createImmediatelyInvokedArrowFunction([
        ...declarations,
        factory2.createReturnStatement(initializer)
      ]);
    }
    if (classInfo) {
      if (isStatic(node)) {
        initializer = injectPendingInitializers(
          classInfo,
          /*isStatic*/
          true,
          initializer
        );
        if (extraInitializersName) {
          classInfo.pendingStaticInitializers ?? (classInfo.pendingStaticInitializers = []);
          classInfo.pendingStaticInitializers.push(
            emitHelpers().createRunInitializersHelper(
              classInfo.classThis ?? factory2.createThis(),
              extraInitializersName
            )
          );
        }
      } else {
        initializer = injectPendingInitializers(
          classInfo,
          /*isStatic*/
          false,
          initializer
        );
        if (extraInitializersName) {
          classInfo.pendingInstanceInitializers ?? (classInfo.pendingInstanceInitializers = []);
          classInfo.pendingInstanceInitializers.push(
            emitHelpers().createRunInitializersHelper(
              factory2.createThis(),
              extraInitializersName
            )
          );
        }
      }
    }
    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) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer));
    }
    const 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 canIgnoreEmptyStringLiteralInAssignedName(node) {
    const innerExpression = skipOuterExpressions(node);
    return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      innerExpression
    );
  }
  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)) {
        node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right));
        return visitEachChild(node, visitor, context);
      }
      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)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer));
    }
    return visitEachChild(node, visitor, context);
  }
  function visitVariableDeclaration(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer));
    }
    return visitEachChild(node, visitor, context);
  }
  function visitBindingElement(node) {
    if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.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
    )) {
      if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) {
        node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right));
      }
      const assignmentTarget = visitDestructuringAssignmentTarget(node.left);
      const 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)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.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)) {
      node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.expression));
    }
    return visitEachChild(node, visitor, context);
  }
  function visitParenthesizedExpression(node, discarded) {
    const visitorFunc = discarded ? discardedValueVisitor : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updateParenthesizedExpression(node, expression);
  }
  function visitPartiallyEmittedExpression(node, discarded) {
    const visitorFunc = discarded ? discardedValueVisitor : visitor;
    const expression = visitNode(node.expression, visitorFunc, isExpression);
    return factory2.updatePartiallyEmittedExpression(node, expression);
  }
  function injectPendingExpressionsCommon(pendingExpressions2, expression) {
    if (some(pendingExpressions2)) {
      if (expression) {
        if (isParenthesizedExpression(expression)) {
          pendingExpressions2.push(expression.expression);
          expression = factory2.updateParenthesizedExpression(expression, factory2.inlineExpressions(pendingExpressions2));
        } else {
          pendingExpressions2.push(expression);
          expression = factory2.inlineExpressions(pendingExpressions2);
        }
      } else {
        expression = factory2.inlineExpressions(pendingExpressions2);
      }
    }
    return expression;
  }
  function injectPendingExpressions(expression) {
    const result = injectPendingExpressionsCommon(pendingExpressions, expression);
    Debug.assertIsDefined(result);
    if (result !== expression) {
      pendingExpressions = void 0;
    }
    return result;
  }
  function injectPendingInitializers(classInfo2, isStatic2, expression) {
    const result = injectPendingExpressionsCommon(isStatic2 ? classInfo2.pendingStaticInitializers : classInfo2.pendingInstanceInitializers, expression);
    if (result !== expression) {
      if (isStatic2) {
        classInfo2.pendingStaticInitializers = void 0;
      } else {
        classInfo2.pendingInstanceInitializers = void 0;
      }
    }
    return result;
  }
  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 */);
    const innerExpression = skipOuterExpressions(expression);
    if (isAccessExpression(innerExpression)) {
      const { target, thisArg } = factory2.createCallBinding(
        expression,
        hoistVariableDeclaration,
        languageVersion,
        /*cacheIdentifiers*/
        true
      );
      return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, []));
    }
    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 createMetadata(name, classSuper2) {
    const varDecl = factory2.createVariableDeclaration(
      name,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      factory2.createConditionalExpression(
        factory2.createLogicalAnd(
          factory2.createTypeCheck(factory2.createIdentifier("Symbol"), "function"),
          factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata")
        ),
        factory2.createToken(58 /* QuestionToken */),
        factory2.createCallExpression(
          factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"),
          /*typeArguments*/
          void 0,
          [classSuper2 ? createSymbolMetadataReference(classSuper2) : factory2.createNull()]
        ),
        factory2.createToken(59 /* ColonToken */),
        factory2.createVoidZero()
      )
    );
    return factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      factory2.createVariableDeclarationList([varDecl], 2 /* Const */)
    );
  }
  function createSymbolMetadata(target, value) {
    const defineProperty = factory2.createObjectDefinePropertyCall(
      target,
      factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata"),
      factory2.createPropertyDescriptor(
        { configurable: true, writable: true, enumerable: true, value },
        /*singleLine*/
        true
      )
    );
    return setEmitFlags(
      factory2.createIfStatement(value, factory2.createExpressionStatement(defineProperty)),
      1 /* SingleLine */
    );
  }
  function createSymbolMetadataReference(classSuper2) {
    return factory2.createBinaryExpression(
      factory2.createElementAccessExpression(
        classSuper2,
        factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata")
      ),
      61 /* QuestionQuestionToken */,
      factory2.createNull()
    );
  }
}

// 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 = 0 /* None */;
  let enclosingSuperContainerFlags = 0;
  let enclosingFunctionParameterNames;
  let capturedSuperProperties;
  let hasSuperElementAccess;
  let lexicalArgumentsBinding;
  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 argumentsVisitor(node) {
    switch (node.kind) {
      case 218 /* FunctionExpression */:
      case 262 /* FunctionDeclaration */:
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 176 /* Constructor */:
        return node;
      case 169 /* Parameter */:
      case 208 /* BindingElement */:
      case 260 /* VariableDeclaration */:
        break;
      case 80 /* Identifier */:
        if (lexicalArgumentsBinding && resolver.isArgumentsLocalBinding(node)) {
          return lexicalArgumentsBinding;
        }
        break;
    }
    return visitEachChild(node, argumentsVisitor, context);
  }
  function visitor(node) {
    if ((node.transformFlags & 256 /* ContainsES2017 */) === 0) {
      return lexicalArgumentsBinding ? argumentsVisitor(node) : node;
    }
    switch (node.kind) {
      case 134 /* AsyncKeyword */:
        return void 0;
      case 223 /* AwaitExpression */:
        return visitAwaitExpression(node);
      case 174 /* MethodDeclaration */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
      case 262 /* FunctionDeclaration */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
      case 218 /* FunctionExpression */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
      case 219 /* ArrowFunction */:
        return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
      case 211 /* PropertyAccessExpression */:
        if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */) {
          capturedSuperProperties.add(node.name.escapedText);
        }
        return visitEachChild(node, visitor, context);
      case 212 /* ElementAccessExpression */:
        if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */) {
          hasSuperElementAccess = true;
        }
        return visitEachChild(node, visitor, context);
      case 177 /* GetAccessor */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitGetAccessorDeclaration, node);
      case 178 /* SetAccessor */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitSetAccessorDeclaration, node);
      case 176 /* Constructor */:
        return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitConstructorDeclaration, node);
      case 263 /* ClassDeclaration */:
      case 231 /* 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 243 /* VariableStatement */:
          return visitVariableStatementInAsyncBody(node);
        case 248 /* ForStatement */:
          return visitForStatementInAsyncBody(node);
        case 249 /* ForInStatement */:
          return visitForInStatementInAsyncBody(node);
        case 250 /* ForOfStatement */:
          return visitForOfStatementInAsyncBody(node);
        case 299 /* CatchClause */:
          return visitCatchClauseInAsyncBody(node);
        case 241 /* Block */:
        case 255 /* SwitchStatement */:
        case 269 /* CaseBlock */:
        case 296 /* CaseClause */:
        case 297 /* DefaultClause */:
        case 258 /* TryStatement */:
        case 246 /* DoStatement */:
        case 247 /* WhileStatement */:
        case 245 /* IfStatement */:
        case 254 /* WithStatement */:
        case 256 /* 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) {
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    lexicalArgumentsBinding = void 0;
    const updated = factory2.updateConstructorDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      visitParameterList(node.parameters, visitor, context),
      transformMethodBody(node)
    );
    lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    return updated;
  }
  function visitMethodDeclaration(node) {
    let parameters;
    const functionFlags = getFunctionFlags(node);
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    lexicalArgumentsBinding = void 0;
    const updated = factory2.updateMethodDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.asteriskToken,
      node.name,
      /*questionToken*/
      void 0,
      /*typeParameters*/
      void 0,
      parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : transformMethodBody(node)
    );
    lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    return updated;
  }
  function visitGetAccessorDeclaration(node) {
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    lexicalArgumentsBinding = void 0;
    const updated = factory2.updateGetAccessorDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.name,
      visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      transformMethodBody(node)
    );
    lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    return updated;
  }
  function visitSetAccessorDeclaration(node) {
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    lexicalArgumentsBinding = void 0;
    const updated = factory2.updateSetAccessorDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.name,
      visitParameterList(node.parameters, visitor, context),
      transformMethodBody(node)
    );
    lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    return updated;
  }
  function visitFunctionDeclaration(node) {
    let parameters;
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    lexicalArgumentsBinding = void 0;
    const functionFlags = getFunctionFlags(node);
    const updated = factory2.updateFunctionDeclaration(
      node,
      visitNodes2(node.modifiers, visitor, isModifierLike),
      node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : visitFunctionBody(node.body, visitor, context)
    );
    lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    return updated;
  }
  function visitFunctionExpression(node) {
    let parameters;
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    lexicalArgumentsBinding = void 0;
    const functionFlags = getFunctionFlags(node);
    const updated = factory2.updateFunctionExpression(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      node.asteriskToken,
      node.name,
      /*typeParameters*/
      void 0,
      parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : visitFunctionBody(node.body, visitor, context)
    );
    lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    return updated;
  }
  function visitArrowFunction(node) {
    let parameters;
    const functionFlags = getFunctionFlags(node);
    return factory2.updateArrowFunction(
      node,
      visitNodes2(node.modifiers, visitor, isModifier),
      /*typeParameters*/
      void 0,
      parameters = functionFlags & 2 /* Async */ ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context),
      /*type*/
      void 0,
      node.equalsGreaterThanToken,
      functionFlags & 2 /* Async */ ? transformAsyncFunctionBody(node, parameters) : 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 & 7 /* 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.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 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.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) {
          addEmitHelper(updated, advancedAsyncSuperHelper);
        } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) {
          addEmitHelper(updated, asyncSuperHelper);
        }
      }
    }
    capturedSuperProperties = savedCapturedSuperProperties;
    hasSuperElementAccess = savedHasSuperElementAccess;
    return updated;
  }
  function createCaptureArgumentsStatement() {
    Debug.assert(lexicalArgumentsBinding);
    const variable = factory2.createVariableDeclaration(
      lexicalArgumentsBinding,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      factory2.createIdentifier("arguments")
    );
    const statement = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      [variable]
    );
    startOnNewLine(statement);
    addEmitFlags(statement, 2097152 /* CustomPrologue */);
    return statement;
  }
  function transformAsyncFunctionParameterList(node) {
    if (isSimpleParameterList(node.parameters)) {
      return visitParameterList(node.parameters, visitor, context);
    }
    const newParameters = [];
    for (const parameter of node.parameters) {
      if (parameter.initializer || parameter.dotDotDotToken) {
        if (node.kind === 219 /* ArrowFunction */) {
          const restParameter = factory2.createParameterDeclaration(
            /*modifiers*/
            void 0,
            factory2.createToken(26 /* DotDotDotToken */),
            factory2.createUniqueName("args", 8 /* ReservedInNestedScopes */)
          );
          newParameters.push(restParameter);
        }
        break;
      }
      const newParameter = factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        factory2.getGeneratedNameForNode(parameter.name, 8 /* ReservedInNestedScopes */)
      );
      newParameters.push(newParameter);
    }
    const newParametersArray = factory2.createNodeArray(newParameters);
    setTextRange(newParametersArray, node.parameters);
    return newParametersArray;
  }
  function transformAsyncFunctionBody(node, outerParameters) {
    const innerParameters = !isSimpleParameterList(node.parameters) ? visitParameterList(node.parameters, visitor, context) : void 0;
    resumeLexicalEnvironment();
    const original = getOriginalNode(node, isFunctionLike);
    const nodeType = original.type;
    const promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : void 0;
    const isArrowFunction2 = node.kind === 219 /* ArrowFunction */;
    const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
    const hasLexicalArguments = resolver.hasNodeCheckFlag(node, 512 /* CaptureArguments */);
    const captureLexicalArguments = hasLexicalArguments && !lexicalArgumentsBinding;
    if (captureLexicalArguments) {
      lexicalArgumentsBinding = factory2.createUniqueName("arguments");
    }
    let argumentsExpression;
    if (innerParameters) {
      if (isArrowFunction2) {
        const parameterBindings = [];
        Debug.assert(outerParameters.length <= node.parameters.length);
        for (let i = 0; i < node.parameters.length; i++) {
          Debug.assert(i < outerParameters.length);
          const originalParameter = node.parameters[i];
          const outerParameter = outerParameters[i];
          Debug.assertNode(outerParameter.name, isIdentifier);
          if (originalParameter.initializer || originalParameter.dotDotDotToken) {
            Debug.assert(i === outerParameters.length - 1);
            parameterBindings.push(factory2.createSpreadElement(outerParameter.name));
            break;
          }
          parameterBindings.push(outerParameter.name);
        }
        argumentsExpression = factory2.createArrayLiteralExpression(parameterBindings);
      } else {
        argumentsExpression = factory2.createIdentifier("arguments");
      }
    }
    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;
    }
    const hasLexicalThis = inHasLexicalThisContext();
    let asyncBody = transformAsyncFunctionBodyWorker(node.body);
    asyncBody = factory2.updateBlock(asyncBody, factory2.mergeLexicalEnvironment(asyncBody.statements, endLexicalEnvironment()));
    let result;
    if (!isArrowFunction2) {
      const statements = [];
      statements.push(
        factory2.createReturnStatement(
          emitHelpers().createAwaiterHelper(
            hasLexicalThis,
            argumentsExpression,
            promiseConstructor,
            innerParameters,
            asyncBody
          )
        )
      );
      const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */));
      if (emitSuperHelpers) {
        enableSubstitutionForAsyncMethodsWithSuper();
        if (capturedSuperProperties.size) {
          const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties);
          substitutedSuperAccessors[getNodeId(variableStatement)] = true;
          insertStatementsAfterStandardPrologue(statements, [variableStatement]);
        }
      }
      if (captureLexicalArguments) {
        insertStatementsAfterStandardPrologue(statements, [createCaptureArgumentsStatement()]);
      }
      const block = factory2.createBlock(
        statements,
        /*multiLine*/
        true
      );
      setTextRange(block, node.body);
      if (emitSuperHelpers && hasSuperElementAccess) {
        if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) {
          addEmitHelper(block, advancedAsyncSuperHelper);
        } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) {
          addEmitHelper(block, asyncSuperHelper);
        }
      }
      result = block;
    } else {
      result = emitHelpers().createAwaiterHelper(
        hasLexicalThis,
        argumentsExpression,
        promiseConstructor,
        innerParameters,
        asyncBody
      );
      if (captureLexicalArguments) {
        const block = factory2.converters.convertToFunctionBlock(result);
        result = factory2.updateBlock(block, factory2.mergeLexicalEnvironment(block.statements, [createCaptureArgumentsStatement()]));
      }
    }
    enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
    if (!isArrowFunction2) {
      capturedSuperProperties = savedCapturedSuperProperties;
      hasSuperElementAccess = savedHasSuperElementAccess;
      lexicalArgumentsBinding = savedLexicalArgumentsBinding;
    }
    return result;
  }
  function transformAsyncFunctionBodyWorker(body, start) {
    if (isBlock(body)) {
      return factory2.updateBlock(body, visitNodes2(body.statements, asyncBodyVisitor, isStatement, start));
    } 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(213 /* CallExpression */);
      context.enableSubstitution(211 /* PropertyAccessExpression */);
      context.enableSubstitution(212 /* ElementAccessExpression */);
      context.enableEmitNotification(263 /* ClassDeclaration */);
      context.enableEmitNotification(174 /* MethodDeclaration */);
      context.enableEmitNotification(177 /* GetAccessor */);
      context.enableEmitNotification(178 /* SetAccessor */);
      context.enableEmitNotification(176 /* Constructor */);
      context.enableEmitNotification(243 /* VariableStatement */);
    }
  }
  function onEmitNode(hint, node, emitCallback) {
    if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
      const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0);
      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 211 /* PropertyAccessExpression */:
        return substitutePropertyAccessExpression(node);
      case 212 /* ElementAccessExpression */:
        return substituteElementAccessExpression(node);
      case 213 /* 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 === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* 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.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */);
  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 = 0 /* None */;
  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 223 /* AwaitExpression */:
        return visitAwaitExpression(node);
      case 229 /* YieldExpression */:
        return visitYieldExpression(node);
      case 253 /* ReturnStatement */:
        return visitReturnStatement(node);
      case 256 /* LabeledStatement */:
        return visitLabeledStatement(node);
      case 210 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 226 /* BinaryExpression */:
        return visitBinaryExpression(node, expressionResultIsUnused2);
      case 356 /* CommaListExpression */:
        return visitCommaListExpression(node, expressionResultIsUnused2);
      case 299 /* CatchClause */:
        return visitCatchClause(node);
      case 243 /* VariableStatement */:
        return visitVariableStatement(node);
      case 260 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 246 /* DoStatement */:
      case 247 /* WhileStatement */:
      case 249 /* ForInStatement */:
        return doWithHierarchyFacts(
          visitDefault,
          node,
          0 /* IterationStatementExcludes */,
          2 /* IterationStatementIncludes */
        );
      case 250 /* ForOfStatement */:
        return visitForOfStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 248 /* ForStatement */:
        return doWithHierarchyFacts(
          visitForStatement,
          node,
          0 /* IterationStatementExcludes */,
          2 /* IterationStatementIncludes */
        );
      case 222 /* VoidExpression */:
        return visitVoidExpression(node);
      case 176 /* Constructor */:
        return doWithHierarchyFacts(
          visitConstructorDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 174 /* MethodDeclaration */:
        return doWithHierarchyFacts(
          visitMethodDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 177 /* GetAccessor */:
        return doWithHierarchyFacts(
          visitGetAccessorDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 178 /* SetAccessor */:
        return doWithHierarchyFacts(
          visitSetAccessorDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 262 /* FunctionDeclaration */:
        return doWithHierarchyFacts(
          visitFunctionDeclaration,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 218 /* FunctionExpression */:
        return doWithHierarchyFacts(
          visitFunctionExpression,
          node,
          2 /* ClassOrFunctionExcludes */,
          1 /* ClassOrFunctionIncludes */
        );
      case 219 /* ArrowFunction */:
        return doWithHierarchyFacts(
          visitArrowFunction,
          node,
          2 /* ArrowFunctionExcludes */,
          0 /* ArrowFunctionIncludes */
        );
      case 169 /* Parameter */:
        return visitParameter(node);
      case 244 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node, expressionResultIsUnused2);
      case 215 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 211 /* PropertyAccessExpression */:
        if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === 108 /* SuperKeyword */) {
          capturedSuperProperties.add(node.name.escapedText);
        }
        return visitEachChild(node, visitor, context);
      case 212 /* ElementAccessExpression */:
        if (capturedSuperProperties && node.expression.kind === 108 /* SuperKeyword */) {
          hasSuperElementAccess = true;
        }
        return visitEachChild(node, visitor, context);
      case 263 /* ClassDeclaration */:
      case 231 /* 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 === 250 /* 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 === 305 /* 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 === 303 /* 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 !== 210 /* 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, 32 /* 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),
      transformFunctionBody(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,
      transformFunctionBody(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),
      transformFunctionBody(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,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionParameterList(node) : visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(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,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionParameterList(node) : visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(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,
      transformFunctionBody(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,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionParameterList(node) : visitParameterList(node.parameters, parameterVisitor, context),
      /*type*/
      void 0,
      enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)
    );
    enclosingFunctionFlags = savedEnclosingFunctionFlags;
    parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
    return updated;
  }
  function transformAsyncGeneratorFunctionParameterList(node) {
    if (isSimpleParameterList(node.parameters)) {
      return visitParameterList(node.parameters, visitor, context);
    }
    const newParameters = [];
    for (const parameter of node.parameters) {
      if (parameter.initializer || parameter.dotDotDotToken) {
        break;
      }
      const newParameter = factory2.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        factory2.getGeneratedNameForNode(parameter.name, 8 /* ReservedInNestedScopes */)
      );
      newParameters.push(newParameter);
    }
    const newParametersArray = factory2.createNodeArray(newParameters);
    setTextRange(newParametersArray, node.parameters);
    return newParametersArray;
  }
  function transformAsyncGeneratorFunctionBody(node) {
    const innerParameters = !isSimpleParameterList(node.parameters) ? visitParameterList(node.parameters, visitor, context) : void 0;
    resumeLexicalEnvironment();
    const savedCapturedSuperProperties = capturedSuperProperties;
    const savedHasSuperElementAccess = hasSuperElementAccess;
    capturedSuperProperties = /* @__PURE__ */ new Set();
    hasSuperElementAccess = false;
    const outerStatements = [];
    let asyncBody = factory2.updateBlock(node.body, visitNodes2(node.body.statements, visitor, isStatement));
    asyncBody = factory2.updateBlock(asyncBody, factory2.mergeLexicalEnvironment(asyncBody.statements, appendObjectRestAssignmentsIfNeeded(endLexicalEnvironment(), node)));
    const returnStatement = factory2.createReturnStatement(
      emitHelpers().createAsyncGeneratorHelper(
        factory2.createFunctionExpression(
          /*modifiers*/
          void 0,
          factory2.createToken(42 /* AsteriskToken */),
          node.name && factory2.getGeneratedNameForNode(node.name),
          /*typeParameters*/
          void 0,
          innerParameters ?? [],
          /*type*/
          void 0,
          asyncBody
        ),
        !!(hierarchyFacts & 1 /* HasLexicalThis */)
      )
    );
    const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */));
    if (emitSuperHelpers) {
      enableSubstitutionForAsyncMethodsWithSuper();
      const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties);
      substitutedSuperAccessors[getNodeId(variableStatement)] = true;
      insertStatementsAfterStandardPrologue(outerStatements, [variableStatement]);
    }
    outerStatements.push(returnStatement);
    const block = factory2.updateBlock(node.body, outerStatements);
    if (emitSuperHelpers && hasSuperElementAccess) {
      if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) {
        addEmitHelper(block, advancedAsyncSuperHelper);
      } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) {
        addEmitHelper(block, asyncSuperHelper);
      }
    }
    capturedSuperProperties = savedCapturedSuperProperties;
    hasSuperElementAccess = savedHasSuperElementAccess;
    return block;
  }
  function transformFunctionBody(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(213 /* CallExpression */);
      context.enableSubstitution(211 /* PropertyAccessExpression */);
      context.enableSubstitution(212 /* ElementAccessExpression */);
      context.enableEmitNotification(263 /* ClassDeclaration */);
      context.enableEmitNotification(174 /* MethodDeclaration */);
      context.enableEmitNotification(177 /* GetAccessor */);
      context.enableEmitNotification(178 /* SetAccessor */);
      context.enableEmitNotification(176 /* Constructor */);
      context.enableEmitNotification(243 /* VariableStatement */);
    }
  }
  function onEmitNode(hint, node, emitCallback) {
    if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
      const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0);
      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 211 /* PropertyAccessExpression */:
        return substitutePropertyAccessExpression(node);
      case 212 /* ElementAccessExpression */:
        return substituteElementAccessExpression(node);
      case 213 /* 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 === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* 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 299 /* 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 213 /* CallExpression */: {
        const updated = visitNonOptionalCallExpression(
          node,
          /*captureThisArg*/
          false
        );
        Debug.assertNotNode(updated, isSyntheticReference);
        return updated;
      }
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        if (isOptionalChain(node)) {
          const updated = visitOptionalExpression(
            node,
            /*captureThisArg*/
            false,
            /*isDelete*/
            false
          );
          Debug.assertNotNode(updated, isSyntheticReference);
          return updated;
        }
        return visitEachChild(node, visitor, context);
      case 226 /* BinaryExpression */:
        if (node.operatorToken.kind === 61 /* QuestionQuestionToken */) {
          return transformNullishCoalescingExpression(node);
        }
        return visitEachChild(node, visitor, context);
      case 220 /* 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 === 211 /* 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 217 /* ParenthesizedExpression */:
        return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
      case 213 /* 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 211 /* PropertyAccessExpression */:
        case 212 /* 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 === 211 /* PropertyAccessExpression */ ? factory2.createPropertyAccessExpression(rightExpression, visitNode(segment.name, visitor, isIdentifier)) : factory2.createElementAccessExpression(rightExpression, visitNode(segment.argumentExpression, visitor, isExpression));
          break;
        case 213 /* 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) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers,
    hoistVariableDeclaration,
    startLexicalEnvironment,
    endLexicalEnvironment
  } = context;
  let exportBindings;
  let exportVars;
  let defaultExportBinding;
  let exportEqualsBinding;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    const visited = visitNode(node, visitor, isSourceFile);
    addEmitHelpers(visited, context.readEmitHelpers());
    exportVars = void 0;
    exportBindings = void 0;
    defaultExportBinding = void 0;
    return visited;
  }
  function visitor(node) {
    if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
      return node;
    }
    switch (node.kind) {
      case 307 /* SourceFile */:
        return visitSourceFile(node);
      case 241 /* Block */:
        return visitBlock(node);
      case 248 /* ForStatement */:
        return visitForStatement(node);
      case 250 /* ForOfStatement */:
        return visitForOfStatement(node);
      case 255 /* SwitchStatement */:
        return visitSwitchStatement(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitSourceFile(node) {
    const usingKind = getUsingKindOfStatements(node.statements);
    if (usingKind) {
      startLexicalEnvironment();
      exportBindings = new IdentifierNameMap();
      exportVars = [];
      const prologueCount = countPrologueStatements(node.statements);
      const topLevelStatements = [];
      addRange(topLevelStatements, visitArray(node.statements, visitor, isStatement, 0, prologueCount));
      let pos = prologueCount;
      while (pos < node.statements.length) {
        const statement = node.statements[pos];
        if (getUsingKind(statement) !== 0 /* None */) {
          if (pos > prologueCount) {
            addRange(topLevelStatements, visitNodes2(node.statements, visitor, isStatement, prologueCount, pos - prologueCount));
          }
          break;
        }
        pos++;
      }
      Debug.assert(pos < node.statements.length, "Should have encountered at least one 'using' statement.");
      const envBinding = createEnvBinding();
      const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements);
      if (exportBindings.size) {
        append(
          topLevelStatements,
          factory2.createExportDeclaration(
            /*modifiers*/
            void 0,
            /*isTypeOnly*/
            false,
            factory2.createNamedExports(arrayFrom(exportBindings.values()))
          )
        );
      }
      addRange(topLevelStatements, endLexicalEnvironment());
      if (exportVars.length) {
        topLevelStatements.push(factory2.createVariableStatement(
          factory2.createModifiersFromModifierFlags(32 /* Export */),
          factory2.createVariableDeclarationList(
            exportVars,
            1 /* Let */
          )
        ));
      }
      addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === 2 /* Async */));
      if (exportEqualsBinding) {
        topLevelStatements.push(factory2.createExportAssignment(
          /*modifiers*/
          void 0,
          /*isExportEquals*/
          true,
          exportEqualsBinding
        ));
      }
      return factory2.updateSourceFile(node, topLevelStatements);
    }
    return visitEachChild(node, visitor, context);
  }
  function visitBlock(node) {
    const usingKind = getUsingKindOfStatements(node.statements);
    if (usingKind) {
      const prologueCount = countPrologueStatements(node.statements);
      const envBinding = createEnvBinding();
      return factory2.updateBlock(
        node,
        [
          ...visitArray(node.statements, visitor, isStatement, 0, prologueCount),
          ...createDownlevelUsingStatements(
            transformUsingDeclarations(
              node.statements,
              prologueCount,
              node.statements.length,
              envBinding,
              /*topLevelStatements*/
              void 0
            ),
            envBinding,
            usingKind === 2 /* Async */
          )
        ]
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitForStatement(node) {
    if (node.initializer && isUsingVariableDeclarationList(node.initializer)) {
      return visitNode(
        factory2.createBlock([
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            node.initializer
          ),
          factory2.updateForStatement(
            node,
            /*initializer*/
            void 0,
            node.condition,
            node.incrementor,
            node.statement
          )
        ]),
        visitor,
        isStatement
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitForOfStatement(node) {
    if (isUsingVariableDeclarationList(node.initializer)) {
      const forInitializer = node.initializer;
      const forDecl = firstOrUndefined(forInitializer.declarations) || factory2.createVariableDeclaration(factory2.createTempVariable(
        /*recordTempVariable*/
        void 0
      ));
      const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === 2 /* Async */;
      const temp = factory2.getGeneratedNameForNode(forDecl.name);
      const usingVar = factory2.updateVariableDeclaration(
        forDecl,
        forDecl.name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        temp
      );
      const usingVarList = factory2.createVariableDeclarationList([usingVar], isAwaitUsing ? 6 /* AwaitUsing */ : 4 /* Using */);
      const usingVarStatement = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        usingVarList
      );
      return visitNode(
        factory2.updateForOfStatement(
          node,
          node.awaitModifier,
          factory2.createVariableDeclarationList([
            factory2.createVariableDeclaration(temp)
          ], 2 /* Const */),
          node.expression,
          isBlock(node.statement) ? factory2.updateBlock(node.statement, [
            usingVarStatement,
            ...node.statement.statements
          ]) : factory2.createBlock(
            [
              usingVarStatement,
              node.statement
            ],
            /*multiLine*/
            true
          )
        ),
        visitor,
        isStatement
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function visitCaseOrDefaultClause(node, envBinding) {
    if (getUsingKindOfStatements(node.statements) !== 0 /* None */) {
      if (isCaseClause(node)) {
        return factory2.updateCaseClause(
          node,
          visitNode(node.expression, visitor, isExpression),
          transformUsingDeclarations(
            node.statements,
            /*start*/
            0,
            node.statements.length,
            envBinding,
            /*topLevelStatements*/
            void 0
          )
        );
      } else {
        return factory2.updateDefaultClause(
          node,
          transformUsingDeclarations(
            node.statements,
            /*start*/
            0,
            node.statements.length,
            envBinding,
            /*topLevelStatements*/
            void 0
          )
        );
      }
    }
    return visitEachChild(node, visitor, context);
  }
  function visitSwitchStatement(node) {
    const usingKind = getUsingKindOfCaseOrDefaultClauses(node.caseBlock.clauses);
    if (usingKind) {
      const envBinding = createEnvBinding();
      return createDownlevelUsingStatements(
        [
          factory2.updateSwitchStatement(
            node,
            visitNode(node.expression, visitor, isExpression),
            factory2.updateCaseBlock(
              node.caseBlock,
              node.caseBlock.clauses.map((clause) => visitCaseOrDefaultClause(clause, envBinding))
            )
          )
        ],
        envBinding,
        usingKind === 2 /* Async */
      );
    }
    return visitEachChild(node, visitor, context);
  }
  function transformUsingDeclarations(statementsIn, start, end, envBinding, topLevelStatements) {
    const statements = [];
    for (let i = start; i < end; i++) {
      const statement = statementsIn[i];
      const usingKind = getUsingKind(statement);
      if (usingKind) {
        Debug.assertNode(statement, isVariableStatement);
        const declarations = [];
        for (let declaration of statement.declarationList.declarations) {
          if (!isIdentifier(declaration.name)) {
            declarations.length = 0;
            break;
          }
          if (isNamedEvaluation(declaration)) {
            declaration = transformNamedEvaluation(context, declaration);
          }
          const initializer = visitNode(declaration.initializer, visitor, isExpression) ?? factory2.createVoidZero();
          declarations.push(factory2.updateVariableDeclaration(
            declaration,
            declaration.name,
            /*exclamationToken*/
            void 0,
            /*type*/
            void 0,
            emitHelpers().createAddDisposableResourceHelper(
              envBinding,
              initializer,
              usingKind === 2 /* Async */
            )
          ));
        }
        if (declarations.length) {
          const varList = factory2.createVariableDeclarationList(declarations, 2 /* Const */);
          setOriginalNode(varList, statement.declarationList);
          setTextRange(varList, statement.declarationList);
          hoistOrAppendNode(factory2.updateVariableStatement(
            statement,
            /*modifiers*/
            void 0,
            varList
          ));
          continue;
        }
      }
      const result = visitor(statement);
      if (isArray(result)) {
        result.forEach(hoistOrAppendNode);
      } else if (result) {
        hoistOrAppendNode(result);
      }
    }
    return statements;
    function hoistOrAppendNode(node) {
      Debug.assertNode(node, isStatement);
      append(statements, hoist(node));
    }
    function hoist(node) {
      if (!topLevelStatements) return node;
      switch (node.kind) {
        case 272 /* ImportDeclaration */:
        case 271 /* ImportEqualsDeclaration */:
        case 278 /* ExportDeclaration */:
        case 262 /* FunctionDeclaration */:
          return hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements);
        case 277 /* ExportAssignment */:
          return hoistExportAssignment(node);
        case 263 /* ClassDeclaration */:
          return hoistClassDeclaration(node);
        case 243 /* VariableStatement */:
          return hoistVariableStatement(node);
      }
      return node;
    }
  }
  function hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements) {
    topLevelStatements.push(node);
    return void 0;
  }
  function hoistExportAssignment(node) {
    return node.isExportEquals ? hoistExportEquals(node) : hoistExportDefault(node);
  }
  function hoistExportDefault(node) {
    if (defaultExportBinding) {
      return node;
    }
    defaultExportBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */);
    hoistBindingIdentifier(
      defaultExportBinding,
      /*isExport*/
      true,
      "default",
      node
    );
    let expression = node.expression;
    let innerExpression = skipOuterExpressions(expression);
    if (isNamedEvaluation(innerExpression)) {
      innerExpression = transformNamedEvaluation(
        context,
        innerExpression,
        /*ignoreEmptyStringLiteral*/
        false,
        "default"
      );
      expression = factory2.restoreOuterExpressions(expression, innerExpression);
    }
    const assignment = factory2.createAssignment(defaultExportBinding, expression);
    return factory2.createExpressionStatement(assignment);
  }
  function hoistExportEquals(node) {
    if (exportEqualsBinding) {
      return node;
    }
    exportEqualsBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */);
    hoistVariableDeclaration(exportEqualsBinding);
    const assignment = factory2.createAssignment(exportEqualsBinding, node.expression);
    return factory2.createExpressionStatement(assignment);
  }
  function hoistClassDeclaration(node) {
    if (!node.name && defaultExportBinding) {
      return node;
    }
    const isExported = hasSyntacticModifier(node, 32 /* Export */);
    const isDefault = hasSyntacticModifier(node, 2048 /* Default */);
    let expression = factory2.converters.convertToClassExpression(node);
    if (node.name) {
      hoistBindingIdentifier(
        factory2.getLocalName(node),
        isExported && !isDefault,
        /*exportAlias*/
        void 0,
        node
      );
      expression = factory2.createAssignment(factory2.getDeclarationName(node), expression);
      if (isNamedEvaluation(expression)) {
        expression = transformNamedEvaluation(
          context,
          expression,
          /*ignoreEmptyStringLiteral*/
          false
        );
      }
      setOriginalNode(expression, node);
      setSourceMapRange(expression, node);
      setCommentRange(expression, node);
    }
    if (isDefault && !defaultExportBinding) {
      defaultExportBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */);
      hoistBindingIdentifier(
        defaultExportBinding,
        /*isExport*/
        true,
        "default",
        node
      );
      expression = factory2.createAssignment(defaultExportBinding, expression);
      if (isNamedEvaluation(expression)) {
        expression = transformNamedEvaluation(
          context,
          expression,
          /*ignoreEmptyStringLiteral*/
          false,
          "default"
        );
      }
      setOriginalNode(expression, node);
    }
    return factory2.createExpressionStatement(expression);
  }
  function hoistVariableStatement(node) {
    let expressions;
    const isExported = hasSyntacticModifier(node, 32 /* Export */);
    for (const variable of node.declarationList.declarations) {
      hoistBindingElement(variable, isExported, variable);
      if (variable.initializer) {
        expressions = append(expressions, hoistInitializedVariable(variable));
      }
    }
    if (expressions) {
      const statement = factory2.createExpressionStatement(factory2.inlineExpressions(expressions));
      setOriginalNode(statement, node);
      setCommentRange(statement, node);
      setSourceMapRange(statement, node);
      return statement;
    }
    return void 0;
  }
  function hoistInitializedVariable(node) {
    Debug.assertIsDefined(node.initializer);
    let target;
    if (isIdentifier(node.name)) {
      target = factory2.cloneNode(node.name);
      setEmitFlags(target, getEmitFlags(target) & ~(32768 /* LocalName */ | 16384 /* ExportName */ | 65536 /* InternalName */));
    } else {
      target = factory2.converters.convertToAssignmentPattern(node.name);
    }
    const assignment = factory2.createAssignment(target, node.initializer);
    setOriginalNode(assignment, node);
    setCommentRange(assignment, node);
    setSourceMapRange(assignment, node);
    return assignment;
  }
  function hoistBindingElement(node, isExportedDeclaration, original) {
    if (isBindingPattern(node.name)) {
      for (const element of node.name.elements) {
        if (!isOmittedExpression(element)) {
          hoistBindingElement(element, isExportedDeclaration, original);
        }
      }
    } else {
      hoistBindingIdentifier(
        node.name,
        isExportedDeclaration,
        /*exportAlias*/
        void 0,
        original
      );
    }
  }
  function hoistBindingIdentifier(node, isExport, exportAlias, original) {
    const name = isGeneratedIdentifier(node) ? node : factory2.cloneNode(node);
    if (isExport) {
      if (exportAlias === void 0 && !isLocalName(name)) {
        const varDecl = factory2.createVariableDeclaration(name);
        if (original) {
          setOriginalNode(varDecl, original);
        }
        exportVars.push(varDecl);
        return;
      }
      const localName = exportAlias !== void 0 ? name : void 0;
      const exportName = exportAlias !== void 0 ? exportAlias : name;
      const specifier = factory2.createExportSpecifier(
        /*isTypeOnly*/
        false,
        localName,
        exportName
      );
      if (original) {
        setOriginalNode(specifier, original);
      }
      exportBindings.set(name, specifier);
    }
    hoistVariableDeclaration(name);
  }
  function createEnvBinding() {
    return factory2.createUniqueName("env");
  }
  function createDownlevelUsingStatements(bodyStatements, envBinding, async) {
    const statements = [];
    const envObject = factory2.createObjectLiteralExpression([
      factory2.createPropertyAssignment("stack", factory2.createArrayLiteralExpression()),
      factory2.createPropertyAssignment("error", factory2.createVoidZero()),
      factory2.createPropertyAssignment("hasError", factory2.createFalse())
    ]);
    const envVar = factory2.createVariableDeclaration(
      envBinding,
      /*exclamationToken*/
      void 0,
      /*type*/
      void 0,
      envObject
    );
    const envVarList = factory2.createVariableDeclarationList([envVar], 2 /* Const */);
    const envVarStatement = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      envVarList
    );
    statements.push(envVarStatement);
    const tryBlock = factory2.createBlock(
      bodyStatements,
      /*multiLine*/
      true
    );
    const bodyCatchBinding = factory2.createUniqueName("e");
    const catchClause = factory2.createCatchClause(
      bodyCatchBinding,
      factory2.createBlock(
        [
          factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.createPropertyAccessExpression(envBinding, "error"),
              bodyCatchBinding
            )
          ),
          factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.createPropertyAccessExpression(envBinding, "hasError"),
              factory2.createTrue()
            )
          )
        ],
        /*multiLine*/
        true
      )
    );
    let finallyBlock;
    if (async) {
      const result = factory2.createUniqueName("result");
      finallyBlock = factory2.createBlock(
        [
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList([
              factory2.createVariableDeclaration(
                result,
                /*exclamationToken*/
                void 0,
                /*type*/
                void 0,
                emitHelpers().createDisposeResourcesHelper(envBinding)
              )
            ], 2 /* Const */)
          ),
          factory2.createIfStatement(result, factory2.createExpressionStatement(factory2.createAwaitExpression(result)))
        ],
        /*multiLine*/
        true
      );
    } else {
      finallyBlock = factory2.createBlock(
        [
          factory2.createExpressionStatement(
            emitHelpers().createDisposeResourcesHelper(envBinding)
          )
        ],
        /*multiLine*/
        true
      );
    }
    const tryStatement = factory2.createTryStatement(tryBlock, catchClause, finallyBlock);
    statements.push(tryStatement);
    return statements;
  }
}
function countPrologueStatements(statements) {
  for (let i = 0; i < statements.length; i++) {
    if (!isPrologueDirective(statements[i]) && !isCustomPrologue(statements[i])) {
      return i;
    }
  }
  return 0;
}
function isUsingVariableDeclarationList(node) {
  return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== 0 /* None */;
}
function getUsingKindOfVariableDeclarationList(node) {
  return (node.flags & 7 /* BlockScoped */) === 6 /* AwaitUsing */ ? 2 /* Async */ : (node.flags & 7 /* BlockScoped */) === 4 /* Using */ ? 1 /* Sync */ : 0 /* None */;
}
function getUsingKindOfVariableStatement(node) {
  return getUsingKindOfVariableDeclarationList(node.declarationList);
}
function getUsingKind(statement) {
  return isVariableStatement(statement) ? getUsingKindOfVariableStatement(statement) : 0 /* None */;
}
function getUsingKindOfStatements(statements) {
  let result = 0 /* None */;
  for (const statement of statements) {
    const usingKind = getUsingKind(statement);
    if (usingKind === 2 /* Async */) return 2 /* Async */;
    if (usingKind > result) result = usingKind;
  }
  return result;
}
function getUsingKindOfCaseOrDefaultClauses(clauses) {
  let result = 0 /* None */;
  for (const clause of clauses) {
    const usingKind = getUsingKindOfStatements(clause.statements);
    if (usingKind === 2 /* Async */) return 2 /* Async */;
    if (usingKind > result) result = usingKind;
  }
  return result;
}

// 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),
            /*attributes*/
            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 284 /* JsxElement */:
        return visitJsxElement(
          node,
          /*isChild*/
          false
        );
      case 285 /* JsxSelfClosingElement */:
        return visitJsxSelfClosingElement(
          node,
          /*isChild*/
          false
        );
      case 288 /* JsxFragment */:
        return visitJsxFragment(
          node,
          /*isChild*/
          false
        );
      case 294 /* JsxExpression */:
        return visitJsxExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function transformJsxChildToExpression(node) {
    switch (node.kind) {
      case 12 /* JsxText */:
        return visitJsxText(node);
      case 294 /* JsxExpression */:
        return visitJsxExpression(node);
      case 284 /* JsxElement */:
        return visitJsxElement(
          node,
          /*isChild*/
          true
        );
      case 285 /* JsxSelfClosingElement */:
        return visitJsxSelfClosingElement(
          node,
          /*isChild*/
          true
        );
      case 288 /* 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 sameMap(node.expression.properties, (p) => Debug.checkDefined(visitNode(p, visitor, isObjectLiteralElementLike)));
    }
    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(Debug.checkDefined(visitNode(prop.expression, visitor, isExpression)));
              continue;
            }
            properties.push(Debug.checkDefined(visitNode(prop, visitor)));
          }
          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 === 294 /* 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 === 284 /* 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-Z_]\w*$/i.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 226 /* 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 = 0 /* None */;
  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 /* ConstructorWithSuperCall */) !== 0 && node.kind === 253 /* 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 /* ConstructorWithSuperCall */ && 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, 229376 /* FunctionSubtreeExcludes */, 0 /* None */);
        return result;
      }
      return visitorWorker(
        node,
        /*expressionResultIsUnused*/
        false
      );
    }
    return node;
  }
  function callExpressionVisitor(node) {
    if (node.kind === 108 /* SuperKeyword */) {
      return visitSuperKeyword(
        node,
        /*isExpressionOfCall*/
        true
      );
    }
    return visitor(node);
  }
  function visitorWorker(node, expressionResultIsUnused2) {
    switch (node.kind) {
      case 126 /* StaticKeyword */:
        return void 0;
      // elide static keyword
      case 263 /* ClassDeclaration */:
        return visitClassDeclaration(node);
      case 231 /* ClassExpression */:
        return visitClassExpression(node);
      case 169 /* Parameter */:
        return visitParameter(node);
      case 262 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 219 /* ArrowFunction */:
        return visitArrowFunction(node);
      case 218 /* FunctionExpression */:
        return visitFunctionExpression(node);
      case 260 /* VariableDeclaration */:
        return visitVariableDeclaration(node);
      case 80 /* Identifier */:
        return visitIdentifier(node);
      case 261 /* VariableDeclarationList */:
        return visitVariableDeclarationList(node);
      case 255 /* SwitchStatement */:
        return visitSwitchStatement(node);
      case 269 /* CaseBlock */:
        return visitCaseBlock(node);
      case 241 /* Block */:
        return visitBlock(
          node,
          /*isFunctionBody*/
          false
        );
      case 252 /* BreakStatement */:
      case 251 /* ContinueStatement */:
        return visitBreakOrContinueStatement(node);
      case 256 /* LabeledStatement */:
        return visitLabeledStatement(node);
      case 246 /* DoStatement */:
      case 247 /* WhileStatement */:
        return visitDoOrWhileStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 248 /* ForStatement */:
        return visitForStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 249 /* ForInStatement */:
        return visitForInStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 250 /* ForOfStatement */:
        return visitForOfStatement(
          node,
          /*outermostLabeledStatement*/
          void 0
        );
      case 244 /* ExpressionStatement */:
        return visitExpressionStatement(node);
      case 210 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 299 /* CatchClause */:
        return visitCatchClause(node);
      case 304 /* ShorthandPropertyAssignment */:
        return visitShorthandPropertyAssignment(node);
      case 167 /* ComputedPropertyName */:
        return visitComputedPropertyName(node);
      case 209 /* ArrayLiteralExpression */:
        return visitArrayLiteralExpression(node);
      case 213 /* CallExpression */:
        return visitCallExpression(node);
      case 214 /* NewExpression */:
        return visitNewExpression(node);
      case 217 /* ParenthesizedExpression */:
        return visitParenthesizedExpression(node, expressionResultIsUnused2);
      case 226 /* BinaryExpression */:
        return visitBinaryExpression(node, expressionResultIsUnused2);
      case 356 /* 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 215 /* TaggedTemplateExpression */:
        return visitTaggedTemplateExpression(node);
      case 228 /* TemplateExpression */:
        return visitTemplateExpression(node);
      case 229 /* YieldExpression */:
        return visitYieldExpression(node);
      case 230 /* SpreadElement */:
        return visitSpreadElement(node);
      case 108 /* SuperKeyword */:
        return visitSuperKeyword(
          node,
          /*isExpressionOfCall*/
          false
        );
      case 110 /* ThisKeyword */:
        return visitThisKeyword(node);
      case 236 /* MetaProperty */:
        return visitMetaProperty(node);
      case 174 /* MethodDeclaration */:
        return visitMethodDeclaration(node);
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return visitAccessorDeclaration(node);
      case 243 /* VariableStatement */:
        return visitVariableStatement(node);
      case 253 /* ReturnStatement */:
        return visitReturnStatement(node);
      case 222 /* 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(createCapturedThis()), node);
  }
  function createCapturedThis() {
    return factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */);
  }
  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) {
    hierarchyFacts |= 65536 /* LexicalThis */;
    if (hierarchyFacts & 2 /* ArrowFunction */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) {
      hierarchyFacts |= 131072 /* 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 & 256 /* IdentifierHasExtendedUnicodeEscape */) {
      return setOriginalNode(
        setTextRange(
          factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)),
          node
        ),
        node
      );
    }
    return node;
  }
  function visitBreakOrContinueStatement(node) {
    if (convertedLoopState) {
      const jump = node.kind === 252 /* 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 === 252 /* BreakStatement */) {
            convertedLoopState.nonLocalJumps |= 2 /* Break */;
            labelMarker = "break";
          } else {
            convertedLoopState.nonLocalJumps |= 4 /* Continue */;
            labelMarker = "continue";
          }
        } else {
          if (node.kind === 252 /* 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, 32 /* Export */)) {
      const exportStatement = hasSyntacticModifier(node, 2048 /* 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,
        createSyntheticSuper()
      )] : [],
      /*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, 229376 /* 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 isUninitializedVariableStatement(node) {
    return isVariableStatement(node) && every(node.declarationList.declarations, (decl) => isIdentifier(decl.name) && !decl.initializer);
  }
  function containsSuperCall(node) {
    if (isSuperCall(node)) {
      return true;
    }
    if (!(node.transformFlags & 134217728 /* ContainsLexicalSuper */)) {
      return false;
    }
    switch (node.kind) {
      // stop at function boundaries
      case 219 /* ArrowFunction */:
      case 218 /* FunctionExpression */:
      case 262 /* FunctionDeclaration */:
      case 176 /* Constructor */:
      case 175 /* ClassStaticBlockDeclaration */:
        return false;
      // only step into computed property names for class and object literal elements
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 174 /* MethodDeclaration */:
      case 172 /* PropertyDeclaration */: {
        const named = node;
        if (isComputedPropertyName(named.name)) {
          return !!forEachChild(named.name, containsSuperCall);
        }
        return false;
      }
    }
    return !!forEachChild(node, containsSuperCall);
  }
  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 standardPrologueEnd = factory2.copyStandardPrologue(
      constructor.body.statements,
      prologue,
      /*statementOffset*/
      0
    );
    if (hasSynthesizedSuper || containsSuperCall(constructor.body)) {
      hierarchyFacts |= 8192 /* ConstructorWithSuperCall */;
    }
    addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, standardPrologueEnd));
    const mayReplaceThis = isDerivedClass || hierarchyFacts & 8192 /* ConstructorWithSuperCall */;
    addDefaultValueAssignmentsIfNeeded2(prologue, constructor);
    addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper);
    insertCaptureNewTargetIfNeeded(prologue, constructor);
    if (mayReplaceThis) {
      insertCaptureThisForNode(prologue, constructor, createActualThis());
    } else {
      insertCaptureThisForNodeIfNeeded(prologue, constructor);
    }
    factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
    if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) {
      statements.push(factory2.createReturnStatement(createCapturedThis()));
    }
    const body = factory2.createBlock(
      setTextRange(
        factory2.createNodeArray(
          [
            ...prologue,
            ...statements
          ]
        ),
        /*location*/
        constructor.body.statements
      ),
      /*multiLine*/
      true
    );
    setTextRange(body, constructor.body);
    return simplifyConstructor(body, constructor.body, hasSynthesizedSuper);
  }
  function isCapturedThis(node) {
    return isGeneratedIdentifier(node) && idText(node) === "_this";
  }
  function isSyntheticSuper(node) {
    return isGeneratedIdentifier(node) && idText(node) === "_super";
  }
  function isThisCapturingVariableStatement(node) {
    return isVariableStatement(node) && node.declarationList.declarations.length === 1 && isThisCapturingVariableDeclaration(node.declarationList.declarations[0]);
  }
  function isThisCapturingVariableDeclaration(node) {
    return isVariableDeclaration(node) && isCapturedThis(node.name) && !!node.initializer;
  }
  function isThisCapturingAssignment(node) {
    return isAssignmentExpression(
      node,
      /*excludeCompoundAssignment*/
      true
    ) && isCapturedThis(node.left);
  }
  function isTransformedSuperCall(node) {
    return isCallExpression(node) && isPropertyAccessExpression(node.expression) && isSyntheticSuper(node.expression.expression) && isIdentifier(node.expression.name) && (idText(node.expression.name) === "call" || idText(node.expression.name) === "apply") && node.arguments.length >= 1 && node.arguments[0].kind === 110 /* ThisKeyword */;
  }
  function isTransformedSuperCallWithFallback(node) {
    return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isTransformedSuperCall(node.left);
  }
  function isImplicitSuperCall(node) {
    return isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && isBinaryExpression(node.left) && node.left.operatorToken.kind === 38 /* ExclamationEqualsEqualsToken */ && isSyntheticSuper(node.left.left) && node.left.right.kind === 106 /* NullKeyword */ && isTransformedSuperCall(node.right) && idText(node.right.expression.name) === "apply";
  }
  function isImplicitSuperCallWithFallback(node) {
    return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isImplicitSuperCall(node.left);
  }
  function isThisCapturingTransformedSuperCallWithFallback(node) {
    return isThisCapturingAssignment(node) && isTransformedSuperCallWithFallback(node.right);
  }
  function isThisCapturingImplicitSuperCallWithFallback(node) {
    return isThisCapturingAssignment(node) && isImplicitSuperCallWithFallback(node.right);
  }
  function isTransformedSuperCallLike(node) {
    return isTransformedSuperCall(node) || isTransformedSuperCallWithFallback(node) || isThisCapturingTransformedSuperCallWithFallback(node) || isImplicitSuperCall(node) || isImplicitSuperCallWithFallback(node) || isThisCapturingImplicitSuperCallWithFallback(node);
  }
  function simplifyConstructorInlineSuperInThisCaptureVariable(body) {
    for (let i = 0; i < body.statements.length - 1; i++) {
      const statement = body.statements[i];
      if (!isThisCapturingVariableStatement(statement)) {
        continue;
      }
      const varDecl = statement.declarationList.declarations[0];
      if (varDecl.initializer.kind !== 110 /* ThisKeyword */) {
        continue;
      }
      const thisCaptureStatementIndex = i;
      let superCallIndex = i + 1;
      while (superCallIndex < body.statements.length) {
        const statement2 = body.statements[superCallIndex];
        if (isExpressionStatement(statement2)) {
          if (isTransformedSuperCallLike(skipOuterExpressions(statement2.expression))) {
            break;
          }
        }
        if (isUninitializedVariableStatement(statement2)) {
          superCallIndex++;
          continue;
        }
        return body;
      }
      const following = body.statements[superCallIndex];
      let expression = following.expression;
      if (isThisCapturingAssignment(expression)) {
        expression = expression.right;
      }
      const newVarDecl = factory2.updateVariableDeclaration(
        varDecl,
        varDecl.name,
        /*exclamationToken*/
        void 0,
        /*type*/
        void 0,
        expression
      );
      const newDeclList = factory2.updateVariableDeclarationList(statement.declarationList, [newVarDecl]);
      const newVarStatement = factory2.createVariableStatement(statement.modifiers, newDeclList);
      setOriginalNode(newVarStatement, following);
      setTextRange(newVarStatement, following);
      const newStatements = factory2.createNodeArray([
        ...body.statements.slice(0, thisCaptureStatementIndex),
        // copy statements preceding to `var _this`
        ...body.statements.slice(thisCaptureStatementIndex + 1, superCallIndex),
        // copy intervening temp variables
        newVarStatement,
        ...body.statements.slice(superCallIndex + 1)
        // copy statements following `super.call(this, ...)`
      ]);
      setTextRange(newStatements, body.statements);
      return factory2.updateBlock(body, newStatements);
    }
    return body;
  }
  function simplifyConstructorInlineSuperReturn(body, original) {
    for (const statement of original.statements) {
      if (statement.transformFlags & 134217728 /* ContainsLexicalSuper */ && !getSuperCallFromStatement(statement)) {
        return body;
      }
    }
    const canElideThisCapturingVariable = !(original.transformFlags & 16384 /* ContainsLexicalThis */) && !(hierarchyFacts & 65536 /* LexicalThis */) && !(hierarchyFacts & 131072 /* CapturedLexicalThis */);
    for (let i = body.statements.length - 1; i > 0; i--) {
      const statement = body.statements[i];
      if (isReturnStatement(statement) && statement.expression && isCapturedThis(statement.expression)) {
        const preceding = body.statements[i - 1];
        let expression;
        if (isExpressionStatement(preceding) && isThisCapturingTransformedSuperCallWithFallback(skipOuterExpressions(preceding.expression))) {
          expression = preceding.expression;
        } else if (canElideThisCapturingVariable && isThisCapturingVariableStatement(preceding)) {
          const varDecl = preceding.declarationList.declarations[0];
          if (isTransformedSuperCallLike(skipOuterExpressions(varDecl.initializer))) {
            expression = factory2.createAssignment(
              createCapturedThis(),
              varDecl.initializer
            );
          }
        }
        if (!expression) {
          break;
        }
        const newReturnStatement = factory2.createReturnStatement(expression);
        setOriginalNode(newReturnStatement, preceding);
        setTextRange(newReturnStatement, preceding);
        const newStatements = factory2.createNodeArray([
          ...body.statements.slice(0, i - 1),
          // copy all statements preceding `_super.call(this, ...)`
          newReturnStatement,
          ...body.statements.slice(i + 1)
          // copy all statements following `return _this;`
        ]);
        setTextRange(newStatements, body.statements);
        return factory2.updateBlock(body, newStatements);
      }
    }
    return body;
  }
  function elideUnusedThisCaptureWorker(node) {
    if (isThisCapturingVariableStatement(node)) {
      const varDecl = node.declarationList.declarations[0];
      if (varDecl.initializer.kind === 110 /* ThisKeyword */) {
        return void 0;
      }
    } else if (isThisCapturingAssignment(node)) {
      return factory2.createPartiallyEmittedExpression(node.right, node);
    }
    switch (node.kind) {
      // stop at function boundaries
      case 219 /* ArrowFunction */:
      case 218 /* FunctionExpression */:
      case 262 /* FunctionDeclaration */:
      case 176 /* Constructor */:
      case 175 /* ClassStaticBlockDeclaration */:
        return node;
      // only step into computed property names for class and object literal elements
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 174 /* MethodDeclaration */:
      case 172 /* PropertyDeclaration */: {
        const named = node;
        if (isComputedPropertyName(named.name)) {
          return factory2.replacePropertyName(named, visitEachChild(
            named.name,
            elideUnusedThisCaptureWorker,
            /*context*/
            void 0
          ));
        }
        return node;
      }
    }
    return visitEachChild(
      node,
      elideUnusedThisCaptureWorker,
      /*context*/
      void 0
    );
  }
  function simplifyConstructorElideUnusedThisCapture(body, original) {
    if (original.transformFlags & 16384 /* ContainsLexicalThis */ || hierarchyFacts & 65536 /* LexicalThis */ || hierarchyFacts & 131072 /* CapturedLexicalThis */) {
      return body;
    }
    for (const statement of original.statements) {
      if (statement.transformFlags & 134217728 /* ContainsLexicalSuper */ && !getSuperCallFromStatement(statement)) {
        return body;
      }
    }
    return factory2.updateBlock(body, visitNodes2(body.statements, elideUnusedThisCaptureWorker, isStatement));
  }
  function injectSuperPresenceCheckWorker(node) {
    if (isTransformedSuperCall(node) && node.arguments.length === 2 && isIdentifier(node.arguments[1]) && idText(node.arguments[1]) === "arguments") {
      return factory2.createLogicalAnd(
        factory2.createStrictInequality(
          createSyntheticSuper(),
          factory2.createNull()
        ),
        node
      );
    }
    switch (node.kind) {
      // stop at function boundaries
      case 219 /* ArrowFunction */:
      case 218 /* FunctionExpression */:
      case 262 /* FunctionDeclaration */:
      case 176 /* Constructor */:
      case 175 /* ClassStaticBlockDeclaration */:
        return node;
      // only step into computed property names for class and object literal elements
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 174 /* MethodDeclaration */:
      case 172 /* PropertyDeclaration */: {
        const named = node;
        if (isComputedPropertyName(named.name)) {
          return factory2.replacePropertyName(named, visitEachChild(
            named.name,
            injectSuperPresenceCheckWorker,
            /*context*/
            void 0
          ));
        }
        return node;
      }
    }
    return visitEachChild(
      node,
      injectSuperPresenceCheckWorker,
      /*context*/
      void 0
    );
  }
  function complicateConstructorInjectSuperPresenceCheck(body) {
    return factory2.updateBlock(body, visitNodes2(body.statements, injectSuperPresenceCheckWorker, isStatement));
  }
  function simplifyConstructor(body, original, hasSynthesizedSuper) {
    const inputBody = body;
    body = simplifyConstructorInlineSuperInThisCaptureVariable(body);
    body = simplifyConstructorInlineSuperReturn(body, original);
    if (body !== inputBody) {
      body = simplifyConstructorElideUnusedThisCapture(body, original);
    }
    if (hasSynthesizedSuper) {
      body = complicateConstructorInjectSuperPresenceCheck(body);
    }
    return body;
  }
  function isSufficientlyCoveredByReturnStatements(statement) {
    if (statement.kind === 253 /* ReturnStatement */) {
      return true;
    } else if (statement.kind === 245 /* IfStatement */) {
      const ifStatement = statement;
      if (ifStatement.elseStatement) {
        return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
      }
    } else if (statement.kind === 241 /* 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(
          createSyntheticSuper(),
          factory2.createNull()
        ),
        factory2.createFunctionApplyCall(
          createSyntheticSuper(),
          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 & 131072 /* CapturedLexicalThis */ && node.kind !== 219 /* ArrowFunction */) {
      insertCaptureThisForNode(statements, node, factory2.createThis());
      return true;
    }
    return false;
  }
  function insertCaptureThisForNode(statements, node, initializer) {
    enableSubstitutionsForCapturedThis();
    const captureThisStatement = factory2.createVariableStatement(
      /*modifiers*/
      void 0,
      factory2.createVariableDeclarationList([
        factory2.createVariableDeclaration(
          createCapturedThis(),
          /*exclamationToken*/
          void 0,
          /*type*/
          void 0,
          initializer
        )
      ])
    );
    setEmitFlags(captureThisStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */);
    setSourceMapRange(captureThisStatement, node);
    insertStatementAfterCustomPrologue(statements, captureThisStatement);
  }
  function insertCaptureNewTargetIfNeeded(statements, node) {
    if (hierarchyFacts & 32768 /* NewTarget */) {
      let newTarget;
      switch (node.kind) {
        case 219 /* ArrowFunction */:
          return statements;
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          newTarget = factory2.createVoidZero();
          break;
        case 176 /* Constructor */:
          newTarget = factory2.createPropertyAccessExpression(
            setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */),
            "constructor"
          );
          break;
        case 262 /* FunctionDeclaration */:
        case 218 /* 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 */);
      insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
    }
    return statements;
  }
  function addClassMembers(statements, node) {
    for (const member of node.members) {
      switch (member.kind) {
        case 240 /* SemicolonClassElement */:
          statements.push(transformSemicolonClassElementToStatement(member));
          break;
        case 174 /* MethodDeclaration */:
          statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
          break;
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          const accessors = getAllAccessorDeclarations(node.members, member);
          if (member === accessors.firstAccessor) {
            statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
          }
          break;
        case 176 /* Constructor */:
        case 175 /* 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 |= 131072 /* 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,
      transformFunctionBody(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 = transformFunctionBody(node);
    const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name;
    exitSubtree(ancestorFacts, 229376 /* 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 = transformFunctionBody(node);
    const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name;
    exitSubtree(ancestorFacts, 229376 /* 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 = transformFunctionBody(node);
    if (hierarchyFacts & 32768 /* NewTarget */ && !name && (node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */)) {
      name = factory2.getGeneratedNameForNode(node);
    }
    exitSubtree(ancestorFacts, 229376 /* 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 transformFunctionBody(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 === 219 /* 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);
    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, isFunctionBody) {
    if (isFunctionBody) {
      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, 32 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
    let updated;
    if (convertedLoopState && (node.declarationList.flags & 7 /* 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 & 7 /* BlockScoped */ || node.transformFlags & 524288 /* ContainsBindingPattern */) {
      if (node.flags & 7 /* 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 isCapturedInFunction = resolver.hasNodeCheckFlag(node, 16384 /* CapturedBlockScopedBinding */);
    const isDeclaredInLoop = resolver.hasNodeCheckFlag(node, 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(visitNode(statement, visitor, isStatement, factory2.liftToBlock) ?? setTextRange(factory2.createEmptyStatement(), statement), node, convertedLoopState && resetLabel);
  }
  function visitIterationStatement(node, outermostLabeledStatement) {
    switch (node.kind) {
      case 246 /* DoStatement */:
      case 247 /* WhileStatement */:
        return visitDoOrWhileStatement(node, outermostLabeledStatement);
      case 248 /* ForStatement */:
        return visitForStatement(node, outermostLabeledStatement);
      case 249 /* ForInStatement */:
        return visitForInStatement(node, outermostLabeledStatement);
      case 250 /* 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 & 7 /* 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 === 167 /* 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.hasNodeCheckFlag(node, 8192 /* ContainsCapturedBlockScopeBinding */);
  }
  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.hasNodeCheckFlag(node, 4096 /* LoopWithCapturedBlockScopedBinding */);
  }
  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 clone = convertIterationStatementCore(node, initializerFunction, factory2.createBlock(
          bodyFunction.part,
          /*multiLine*/
          true
        ));
        loop = factory2.restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel);
      }
    } else {
      const clone = convertIterationStatementCore(node, initializerFunction, Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock)));
      loop = factory2.restoreEnclosingLabel(clone, outermostLabeledStatement, convertedLoopState && resetLabel);
    }
    statements.push(loop);
    return statements;
  }
  function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
    switch (node.kind) {
      case 248 /* ForStatement */:
        return convertForStatement(node, initializerFunction, convertedLoopBody);
      case 249 /* ForInStatement */:
        return convertForInStatement(node, convertedLoopBody);
      case 250 /* ForOfStatement */:
        return convertForOfStatement(node, convertedLoopBody);
      case 246 /* DoStatement */:
        return convertDoStatement(node, convertedLoopBody);
      case 247 /* 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 248 /* ForStatement */:
      case 249 /* ForInStatement */:
      case 250 /* ForOfStatement */:
        const initializer = node.initializer;
        if (initializer && initializer.kind === 261 /* VariableDeclarationList */) {
          loopInitializer = initializer;
        }
        break;
    }
    const loopParameters = [];
    const loopOutParameters = [];
    if (loopInitializer && getCombinedNodeFlags(loopInitializer) & 7 /* 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 needsOutParam = resolver.hasNodeCheckFlag(decl, 65536 /* NeedsLoopOutParameter */);
      if (needsOutParam || hasCapturedBindingsInForHead) {
        const outParamName = factory2.createUniqueName("out_" + idText(name));
        let flags = 0 /* None */;
        if (needsOutParam) {
          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, start) {
    const properties = node.properties;
    const numProperties = properties.length;
    for (let i = start; i < numProperties; i++) {
      const property = properties[i];
      switch (property.kind) {
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          const accessors = getAllAccessorDeclarations(node.properties, property);
          if (property === accessors.firstAccessor) {
            expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
          }
          break;
        case 174 /* MethodDeclaration */:
          expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
          break;
        case 303 /* PropertyAssignment */:
          expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
          break;
        case 304 /* 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 = transformFunctionBody(node);
    if (node.kind === 177 /* 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, 229376 /* 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 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(createCapturedThis(), initializer) : initializer;
      }
      return setOriginalNode(resultingCall, node);
    }
    if (isSuperCall(node)) {
      hierarchyFacts |= 131072 /* CapturedLexicalThis */;
    }
    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 createSyntheticSuper() {
    return factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
  }
  function visitSuperKeyword(node, isExpressionOfCall) {
    const expression = hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(setOriginalNode(createSyntheticSuper(), node), "prototype") : createSyntheticSuper();
    setOriginalNode(expression, node);
    setCommentRange(expression, node);
    setSourceMapRange(expression, node);
    return expression;
  }
  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(176 /* Constructor */);
      context.enableEmitNotification(174 /* MethodDeclaration */);
      context.enableEmitNotification(177 /* GetAccessor */);
      context.enableEmitNotification(178 /* SetAccessor */);
      context.enableEmitNotification(219 /* ArrowFunction */);
      context.enableEmitNotification(218 /* FunctionExpression */);
      context.enableEmitNotification(262 /* 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 208 /* BindingElement */:
      case 263 /* ClassDeclaration */:
      case 266 /* EnumDeclaration */:
      case 260 /* 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(createCapturedThis(), 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 !== 244 /* ExpressionStatement */) {
      return false;
    }
    const statementExpression = statement.expression;
    if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== 213 /* 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 !== 230 /* SpreadElement */) {
      return false;
    }
    const expression = callArgument.expression;
    return isIdentifier(expression) && expression.escapedText === "arguments";
  }
}

// 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 246 /* DoStatement */:
        return visitDoStatement(node);
      case 247 /* WhileStatement */:
        return visitWhileStatement(node);
      case 255 /* SwitchStatement */:
        return visitSwitchStatement(node);
      case 256 /* LabeledStatement */:
        return visitLabeledStatement(node);
      default:
        return visitJavaScriptInGeneratorFunctionBody(node);
    }
  }
  function visitJavaScriptInGeneratorFunctionBody(node) {
    switch (node.kind) {
      case 262 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 218 /* FunctionExpression */:
        return visitFunctionExpression(node);
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return visitAccessorDeclaration(node);
      case 243 /* VariableStatement */:
        return visitVariableStatement(node);
      case 248 /* ForStatement */:
        return visitForStatement(node);
      case 249 /* ForInStatement */:
        return visitForInStatement(node);
      case 252 /* BreakStatement */:
        return visitBreakStatement(node);
      case 251 /* ContinueStatement */:
        return visitContinueStatement(node);
      case 253 /* 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 226 /* BinaryExpression */:
        return visitBinaryExpression(node);
      case 356 /* CommaListExpression */:
        return visitCommaListExpression(node);
      case 227 /* ConditionalExpression */:
        return visitConditionalExpression(node);
      case 229 /* YieldExpression */:
        return visitYieldExpression(node);
      case 209 /* ArrayLiteralExpression */:
        return visitArrayLiteralExpression(node);
      case 210 /* ObjectLiteralExpression */:
        return visitObjectLiteralExpression(node);
      case 212 /* ElementAccessExpression */:
        return visitElementAccessExpression(node);
      case 213 /* CallExpression */:
        return visitCallExpression(node);
      case 214 /* NewExpression */:
        return visitNewExpression(node);
      default:
        return visitEachChild(node, visitor, context);
    }
  }
  function visitGenerator(node) {
    switch (node.kind) {
      case 262 /* FunctionDeclaration */:
        return visitFunctionDeclaration(node);
      case 218 /* 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, vi