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

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

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

// src/compiler/transformers/module/esnextAnd2015.ts
function transformECMAScriptModule(context) {
  const {
    factory: factory2,
    getEmitHelperFactory: emitHelpers
  } = context;
  const host = context.getEmitHost();
  const resolver = context.getEmitResolver();
  const compilerOptions = context.getCompilerOptions();
  const languageVersion = getEmitScriptTarget(compilerOptions);
  const previousOnEmitNode = context.onEmitNode;
  const previousOnSubstituteNode = context.onSubstituteNode;
  context.onEmitNode = onEmitNode;
  context.onSubstituteNode = onSubstituteNode;
  context.enableEmitNotification(307 /* SourceFile */);
  context.enableSubstitution(80 /* Identifier */);
  const noSubstitution = /* @__PURE__ */ new Set();
  let importsAndRequiresToRewriteOrShim;
  let helperNameSubstitutions;
  let currentSourceFile;
  let importRequireStatements;
  return chainBundle(context, transformSourceFile);
  function transformSourceFile(node) {
    if (node.isDeclarationFile) {
      return node;
    }
    if (isExternalModule(node) || getIsolatedModules(compilerOptions)) {
      currentSourceFile = node;
      importRequireStatements = void 0;
      if (compilerOptions.rewriteRelativeImportExtensions && (currentSourceFile.flags & 4194304 /* PossiblyContainsDynamicImport */ || isInJSFile(node))) {
        forEachDynamicImportOrRequireCall(
          node,
          /*includeTypeSpaceImports*/
          false,
          /*requireStringLiteralLikeArgument*/
          false,
          (node2) => {
            if (!isStringLiteralLike(node2.arguments[0]) || shouldRewriteModuleSpecifier(node2.arguments[0].text, compilerOptions)) {
              importsAndRequiresToRewriteOrShim = append(importsAndRequiresToRewriteOrShim, node2);
            }
          }
        );
      }
      let result = updateExternalModule(node);
      addEmitHelpers(result, context.readEmitHelpers());
      currentSourceFile = void 0;
      if (importRequireStatements) {
        result = factory2.updateSourceFile(
          result,
          setTextRange(factory2.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements)
        );
      }
      if (!isExternalModule(node) || getEmitModuleKind(compilerOptions) === 200 /* Preserve */ || some(result.statements, isExternalModuleIndicator)) {
        return result;
      }
      return factory2.updateSourceFile(
        result,
        setTextRange(factory2.createNodeArray([...result.statements, createEmptyExports(factory2)]), result.statements)
      );
    }
    return node;
  }
  function updateExternalModule(node) {
    const externalHelpersImportDeclaration = createExternalHelpersImportDeclarationIfNeeded(factory2, emitHelpers(), node, compilerOptions);
    if (externalHelpersImportDeclaration) {
      const statements = [];
      const statementOffset = factory2.copyPrologue(node.statements, statements);
      addRange(statements, visitArray([externalHelpersImportDeclaration], visitor, isStatement));
      addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset));
      return factory2.updateSourceFile(
        node,
        setTextRange(factory2.createNodeArray(statements), node.statements)
      );
    } else {
      return visitEachChild(node, visitor, context);
    }
  }
  function visitor(node) {
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
        return getEmitModuleKind(compilerOptions) >= 100 /* Node16 */ ? visitImportEqualsDeclaration(node) : void 0;
      case 277 /* ExportAssignment */:
        return visitExportAssignment(node);
      case 278 /* ExportDeclaration */:
        const exportDecl = node;
        return visitExportDeclaration(exportDecl);
      case 272 /* ImportDeclaration */:
        return visitImportDeclaration(node);
      case 213 /* CallExpression */:
        if (node === (importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim[0])) {
          return visitImportOrRequireCall(importsAndRequiresToRewriteOrShim.shift());
        }
        break;
      default:
        if ((importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim.length) && rangeContainsRange(node, importsAndRequiresToRewriteOrShim[0])) {
          return visitEachChild(node, visitor, context);
        }
    }
    return node;
  }
  function visitImportDeclaration(node) {
    if (!compilerOptions.rewriteRelativeImportExtensions) {
      return node;
    }
    const updatedModuleSpecifier = rewriteModuleSpecifier(node.moduleSpecifier, compilerOptions);
    if (updatedModuleSpecifier === node.moduleSpecifier) {
      return node;
    }
    return factory2.updateImportDeclaration(
      node,
      node.modifiers,
      node.importClause,
      updatedModuleSpecifier,
      node.attributes
    );
  }
  function visitImportOrRequireCall(node) {
    return factory2.updateCallExpression(
      node,
      node.expression,
      node.typeArguments,
      [
        isStringLiteralLike(node.arguments[0]) ? rewriteModuleSpecifier(node.arguments[0], compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(node.arguments[0]),
        ...node.arguments.slice(1)
      ]
    );
  }
  function createRequireCall(importNode) {
    const moduleName = getExternalModuleNameLiteral(factory2, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions);
    const args = [];
    if (moduleName) {
      args.push(rewriteModuleSpecifier(moduleName, compilerOptions));
    }
    if (getEmitModuleKind(compilerOptions) === 200 /* Preserve */) {
      return factory2.createCallExpression(
        factory2.createIdentifier("require"),
        /*typeArguments*/
        void 0,
        args
      );
    }
    if (!importRequireStatements) {
      const createRequireName = factory2.createUniqueName("_createRequire", 16 /* Optimistic */ | 32 /* FileLevel */);
      const importStatement = factory2.createImportDeclaration(
        /*modifiers*/
        void 0,
        factory2.createImportClause(
          /*isTypeOnly*/
          false,
          /*name*/
          void 0,
          factory2.createNamedImports([
            factory2.createImportSpecifier(
              /*isTypeOnly*/
              false,
              factory2.createIdentifier("createRequire"),
              createRequireName
            )
          ])
        ),
        factory2.createStringLiteral("module"),
        /*attributes*/
        void 0
      );
      const requireHelperName = factory2.createUniqueName("__require", 16 /* Optimistic */ | 32 /* FileLevel */);
      const requireStatement = factory2.createVariableStatement(
        /*modifiers*/
        void 0,
        factory2.createVariableDeclarationList(
          [
            factory2.createVariableDeclaration(
              requireHelperName,
              /*exclamationToken*/
              void 0,
              /*type*/
              void 0,
              factory2.createCallExpression(
                factory2.cloneNode(createRequireName),
                /*typeArguments*/
                void 0,
                [
                  factory2.createPropertyAccessExpression(factory2.createMetaProperty(102 /* ImportKeyword */, factory2.createIdentifier("meta")), factory2.createIdentifier("url"))
                ]
              )
            )
          ],
          /*flags*/
          languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
        )
      );
      importRequireStatements = [importStatement, requireStatement];
    }
    const name = importRequireStatements[1].declarationList.declarations[0].name;
    Debug.assertNode(name, isIdentifier);
    return factory2.createCallExpression(
      factory2.cloneNode(name),
      /*typeArguments*/
      void 0,
      args
    );
  }
  function visitImportEqualsDeclaration(node) {
    Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
    let statements;
    statements = append(
      statements,
      setOriginalNode(
        setTextRange(
          factory2.createVariableStatement(
            /*modifiers*/
            void 0,
            factory2.createVariableDeclarationList(
              [
                factory2.createVariableDeclaration(
                  factory2.cloneNode(node.name),
                  /*exclamationToken*/
                  void 0,
                  /*type*/
                  void 0,
                  createRequireCall(node)
                )
              ],
              /*flags*/
              languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */
            )
          ),
          node
        ),
        node
      )
    );
    statements = appendExportsOfImportEqualsDeclaration(statements, node);
    return singleOrMany(statements);
  }
  function appendExportsOfImportEqualsDeclaration(statements, node) {
    if (hasSyntacticModifier(node, 32 /* Export */)) {
      statements = append(
        statements,
        factory2.createExportDeclaration(
          /*modifiers*/
          void 0,
          node.isTypeOnly,
          factory2.createNamedExports([factory2.createExportSpecifier(
            /*isTypeOnly*/
            false,
            /*propertyName*/
            void 0,
            idText(node.name)
          )])
        )
      );
    }
    return statements;
  }
  function visitExportAssignment(node) {
    if (node.isExportEquals) {
      if (getEmitModuleKind(compilerOptions) === 200 /* Preserve */) {
        const statement = setOriginalNode(
          factory2.createExpressionStatement(
            factory2.createAssignment(
              factory2.createPropertyAccessExpression(
                factory2.createIdentifier("module"),
                "exports"
              ),
              node.expression
            )
          ),
          node
        );
        return statement;
      }
      return void 0;
    }
    return node;
  }
  function visitExportDeclaration(node) {
    const updatedModuleSpecifier = rewriteModuleSpecifier(node.moduleSpecifier, compilerOptions);
    if (compilerOptions.module !== void 0 && compilerOptions.module > 5 /* ES2015 */ || !node.exportClause || !isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
      return !node.moduleSpecifier || updatedModuleSpecifier === node.moduleSpecifier ? node : factory2.updateExportDeclaration(
        node,
        node.modifiers,
        node.isTypeOnly,
        node.exportClause,
        updatedModuleSpecifier,
        node.attributes
      );
    }
    const oldIdentifier = node.exportClause.name;
    const synthName = factory2.getGeneratedNameForNode(oldIdentifier);
    const importDecl = factory2.createImportDeclaration(
      /*modifiers*/
      void 0,
      factory2.createImportClause(
        /*isTypeOnly*/
        false,
        /*name*/
        void 0,
        factory2.createNamespaceImport(
          synthName
        )
      ),
      updatedModuleSpecifier,
      node.attributes
    );
    setOriginalNode(importDecl, node.exportClause);
    const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory2.createExportDefault(synthName) : factory2.createExportDeclaration(
      /*modifiers*/
      void 0,
      /*isTypeOnly*/
      false,
      factory2.createNamedExports([factory2.createExportSpecifier(
        /*isTypeOnly*/
        false,
        synthName,
        oldIdentifier
      )])
    );
    setOriginalNode(exportDecl, node);
    return [importDecl, exportDecl];
  }
  function onEmitNode(hint, node, emitCallback) {
    if (isSourceFile(node)) {
      if ((isExternalModule(node) || getIsolatedModules(compilerOptions)) && compilerOptions.importHelpers) {
        helperNameSubstitutions = /* @__PURE__ */ new Map();
      }
      currentSourceFile = node;
      previousOnEmitNode(hint, node, emitCallback);
      currentSourceFile = void 0;
      helperNameSubstitutions = void 0;
    } else {
      previousOnEmitNode(hint, node, emitCallback);
    }
  }
  function onSubstituteNode(hint, node) {
    node = previousOnSubstituteNode(hint, node);
    if (node.id && noSubstitution.has(node.id)) {
      return node;
    }
    if (isIdentifier(node) && getEmitFlags(node) & 8192 /* HelperName */) {
      return substituteHelperName(node);
    }
    return node;
  }
  function substituteHelperName(node) {
    const externalHelpersModuleName = currentSourceFile && getExternalHelpersModuleName(currentSourceFile);
    if (externalHelpersModuleName) {
      noSubstitution.add(getNodeId(node));
      return factory2.createPropertyAccessExpression(externalHelpersModuleName, node);
    }
    if (helperNameSubstitutions) {
      const name = idText(node);
      let substitution = helperNameSubstitutions.get(name);
      if (!substitution) {
        helperNameSubstitutions.set(name, substitution = factory2.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
      }
      return substitution;
    }
    return node;
  }
}

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

// src/compiler/transformers/declarations/diagnostics.ts
function canProduceDiagnostics(node) {
  return isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isSetAccessor(node) || isGetAccessor(node) || isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isParameter(node) || isTypeParameterDeclaration(node) || isExpressionWithTypeArguments(node) || isImportEqualsDeclaration(node) || isTypeAliasDeclaration(node) || isConstructorDeclaration(node) || isIndexSignatureDeclaration(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isJSDocTypeAlias(node);
}
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
  if (isSetAccessor(node) || isGetAccessor(node)) {
    return getAccessorNameVisibilityError;
  } else if (isMethodSignature(node) || isMethodDeclaration(node)) {
    return getMethodNameVisibilityError;
  } else {
    return createGetSymbolAccessibilityDiagnosticForNode(node);
  }
  function getAccessorNameVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    if (isStatic(node)) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
    } else if (node.parent.kind === 263 /* ClassDeclaration */) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
    } else {
      return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
    }
  }
  function getMethodNameVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    if (isStatic(node)) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
    } else if (node.parent.kind === 263 /* ClassDeclaration */) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
    } else {
      return symbolAccessibilityResult.errorModuleName ? Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
    }
  }
}
function createGetSymbolAccessibilityDiagnosticForNode(node) {
  if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node) || isBinaryExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) {
    return getVariableDeclarationTypeVisibilityError;
  } else if (isSetAccessor(node) || isGetAccessor(node)) {
    return getAccessorDeclarationTypeVisibilityError;
  } else if (isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isIndexSignatureDeclaration(node)) {
    return getReturnTypeVisibilityError;
  } else if (isParameter(node)) {
    if (isParameterPropertyDeclaration(node, node.parent) && hasSyntacticModifier(node.parent, 2 /* Private */)) {
      return getVariableDeclarationTypeVisibilityError;
    }
    return getParameterDeclarationTypeVisibilityError;
  } else if (isTypeParameterDeclaration(node)) {
    return getTypeParameterConstraintVisibilityError;
  } else if (isExpressionWithTypeArguments(node)) {
    return getHeritageClauseVisibilityError;
  } else if (isImportEqualsDeclaration(node)) {
    return getImportEntityNameVisibilityError;
  } else if (isTypeAliasDeclaration(node) || isJSDocTypeAlias(node)) {
    return getTypeAliasDeclarationVisibilityError;
  } else {
    return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${Debug.formatSyntaxKind(node.kind)}`);
  }
  function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */) {
      return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
    } else if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */ || node.kind === 226 /* BinaryExpression */ || node.kind === 171 /* PropertySignature */ || node.kind === 169 /* Parameter */ && hasSyntacticModifier(node.parent, 2 /* Private */)) {
      if (isStatic(node)) {
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
      } else if (node.parent.kind === 263 /* ClassDeclaration */ || node.kind === 169 /* Parameter */) {
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
      } else {
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
      }
    }
  }
  function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
    let diagnosticMessage;
    if (node.kind === 178 /* SetAccessor */) {
      if (isStatic(node)) {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
      } else {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
      }
    } else {
      if (isStatic(node)) {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
      } else {
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
      }
    }
    return {
      diagnosticMessage,
      errorNode: node.name,
      typeName: node.name
    };
  }
  function getReturnTypeVisibilityError(symbolAccessibilityResult) {
    let diagnosticMessage;
    switch (node.kind) {
      case 180 /* ConstructSignature */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
        break;
      case 179 /* CallSignature */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
        break;
      case 181 /* IndexSignature */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
        break;
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        if (isStatic(node)) {
          diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
        } else if (node.parent.kind === 263 /* ClassDeclaration */) {
          diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
        } else {
          diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
        }
        break;
      case 262 /* FunctionDeclaration */:
        diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
        break;
      default:
        return Debug.fail("This is unknown kind for signature: " + node.kind);
    }
    return {
      diagnosticMessage,
      errorNode: node.name || node
    };
  }
  function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
    const diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
    return diagnosticMessage !== void 0 ? {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    } : void 0;
  }
  function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
    switch (node.parent.kind) {
      case 176 /* Constructor */:
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
      case 180 /* ConstructSignature */:
      case 185 /* ConstructorType */:
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
      case 179 /* CallSignature */:
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
      case 181 /* IndexSignature */:
        return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        if (isStatic(node.parent)) {
          return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
        } else if (node.parent.parent.kind === 263 /* ClassDeclaration */) {
          return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
        } else {
          return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
        }
      case 262 /* FunctionDeclaration */:
      case 184 /* FunctionType */:
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
      case 178 /* SetAccessor */:
      case 177 /* GetAccessor */:
        return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
      default:
        return Debug.fail(`Unknown parent for parameter: ${Debug.formatSyntaxKind(node.parent.kind)}`);
    }
  }
  function getTypeParameterConstraintVisibilityError() {
    let diagnosticMessage;
    switch (node.parent.kind) {
      case 263 /* ClassDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
        break;
      case 264 /* InterfaceDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
        break;
      case 200 /* MappedType */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
        break;
      case 185 /* ConstructorType */:
      case 180 /* ConstructSignature */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
        break;
      case 179 /* CallSignature */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
        break;
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        if (isStatic(node.parent)) {
          diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
        } else if (node.parent.parent.kind === 263 /* ClassDeclaration */) {
          diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
        } else {
          diagnosticMessage = Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
        }
        break;
      case 184 /* FunctionType */:
      case 262 /* FunctionDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
        break;
      case 195 /* InferType */:
        diagnosticMessage = Diagnostics.Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1;
        break;
      case 265 /* TypeAliasDeclaration */:
        diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
        break;
      default:
        return Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
    }
    return {
      diagnosticMessage,
      errorNode: node,
      typeName: node.name
    };
  }
  function getHeritageClauseVisibilityError() {
    let diagnosticMessage;
    if (isClassDeclaration(node.parent.parent)) {
      diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === 119 /* ImplementsKeyword */ ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
    } else {
      diagnosticMessage = Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
    }
    return {
      diagnosticMessage,
      errorNode: node,
      typeName: getNameOfDeclaration(node.parent.parent)
    };
  }
  function getImportEntityNameVisibilityError() {
    return {
      diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1,
      errorNode: node,
      typeName: node.name
    };
  }
  function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) {
    return {
      diagnosticMessage: symbolAccessibilityResult.errorModuleName ? Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 : Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
      errorNode: isJSDocTypeAlias(node) ? Debug.checkDefined(node.typeExpression) : node.type,
      typeName: isJSDocTypeAlias(node) ? getNameOfDeclaration(node) : node.name
    };
  }
}
function createGetIsolatedDeclarationErrors(resolver) {
  const relatedSuggestionByDeclarationKind = {
    [219 /* ArrowFunction */]: Diagnostics.Add_a_return_type_to_the_function_expression,
    [218 /* FunctionExpression */]: Diagnostics.Add_a_return_type_to_the_function_expression,
    [174 /* MethodDeclaration */]: Diagnostics.Add_a_return_type_to_the_method,
    [177 /* GetAccessor */]: Diagnostics.Add_a_return_type_to_the_get_accessor_declaration,
    [178 /* SetAccessor */]: Diagnostics.Add_a_type_to_parameter_of_the_set_accessor_declaration,
    [262 /* FunctionDeclaration */]: Diagnostics.Add_a_return_type_to_the_function_declaration,
    [180 /* ConstructSignature */]: Diagnostics.Add_a_return_type_to_the_function_declaration,
    [169 /* Parameter */]: Diagnostics.Add_a_type_annotation_to_the_parameter_0,
    [260 /* VariableDeclaration */]: Diagnostics.Add_a_type_annotation_to_the_variable_0,
    [172 /* PropertyDeclaration */]: Diagnostics.Add_a_type_annotation_to_the_property_0,
    [171 /* PropertySignature */]: Diagnostics.Add_a_type_annotation_to_the_property_0,
    [277 /* ExportAssignment */]: Diagnostics.Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it
  };
  const errorByDeclarationKind = {
    [218 /* FunctionExpression */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations,
    [262 /* FunctionDeclaration */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations,
    [219 /* ArrowFunction */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations,
    [174 /* MethodDeclaration */]: Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations,
    [180 /* ConstructSignature */]: Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations,
    [177 /* GetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations,
    [178 /* SetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations,
    [169 /* Parameter */]: Diagnostics.Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations,
    [260 /* VariableDeclaration */]: Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations,
    [172 /* PropertyDeclaration */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations,
    [171 /* PropertySignature */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations,
    [167 /* ComputedPropertyName */]: Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations,
    [305 /* SpreadAssignment */]: Diagnostics.Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations,
    [304 /* ShorthandPropertyAssignment */]: Diagnostics.Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations,
    [209 /* ArrayLiteralExpression */]: Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations,
    [277 /* ExportAssignment */]: Diagnostics.Default_exports_can_t_be_inferred_with_isolatedDeclarations,
    [230 /* SpreadElement */]: Diagnostics.Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations
  };
  return getDiagnostic;
  function getDiagnostic(node) {
    const heritageClause = findAncestor(node, isHeritageClause);
    if (heritageClause) {
      return createDiagnosticForNode(node, Diagnostics.Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations);
    }
    if ((isPartOfTypeNode(node) || isTypeQueryNode(node.parent)) && (isEntityName(node) || isEntityNameExpression(node))) {
      return createEntityInTypeNodeError(node);
    }
    Debug.type(node);
    switch (node.kind) {
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return createAccessorTypeError(node);
      case 167 /* ComputedPropertyName */:
      case 304 /* ShorthandPropertyAssignment */:
      case 305 /* SpreadAssignment */:
        return createObjectLiteralError(node);
      case 209 /* ArrayLiteralExpression */:
      case 230 /* SpreadElement */:
        return createArrayLiteralError(node);
      case 174 /* MethodDeclaration */:
      case 180 /* ConstructSignature */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 262 /* FunctionDeclaration */:
        return createReturnTypeError(node);
      case 208 /* BindingElement */:
        return createBindingElementError(node);
      case 172 /* PropertyDeclaration */:
      case 260 /* VariableDeclaration */:
        return createVariableOrPropertyError(node);
      case 169 /* Parameter */:
        return createParameterError(node);
      case 303 /* PropertyAssignment */:
        return createExpressionError(node.initializer);
      case 231 /* ClassExpression */:
        return createClassExpressionError(node);
      default:
        assertType(node);
        return createExpressionError(node);
    }
  }
  function findNearestDeclaration(node) {
    const result = findAncestor(node, (n) => isExportAssignment(n) || isStatement(n) || isVariableDeclaration(n) || isPropertyDeclaration(n) || isParameter(n));
    if (!result) return void 0;
    if (isExportAssignment(result)) return result;
    if (isReturnStatement(result)) {
      return findAncestor(result, (n) => isFunctionLikeDeclaration(n) && !isConstructorDeclaration(n));
    }
    return isStatement(result) ? void 0 : result;
  }
  function createAccessorTypeError(node) {
    const { getAccessor, setAccessor } = getAllAccessorDeclarations(node.symbol.declarations, node);
    const targetNode = (isSetAccessor(node) ? node.parameters[0] : node) ?? node;
    const diag2 = createDiagnosticForNode(targetNode, errorByDeclarationKind[node.kind]);
    if (setAccessor) {
      addRelatedInfo(diag2, createDiagnosticForNode(setAccessor, relatedSuggestionByDeclarationKind[setAccessor.kind]));
    }
    if (getAccessor) {
      addRelatedInfo(diag2, createDiagnosticForNode(getAccessor, relatedSuggestionByDeclarationKind[getAccessor.kind]));
    }
    return diag2;
  }
  function addParentDeclarationRelatedInfo(node, diag2) {
    const parentDeclaration = findNearestDeclaration(node);
    if (parentDeclaration) {
      const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode(
        parentDeclaration.name,
        /*includeTrivia*/
        false
      );
      addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr));
    }
    return diag2;
  }
  function createObjectLiteralError(node) {
    const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]);
    addParentDeclarationRelatedInfo(node, diag2);
    return diag2;
  }
  function createArrayLiteralError(node) {
    const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]);
    addParentDeclarationRelatedInfo(node, diag2);
    return diag2;
  }
  function createReturnTypeError(node) {
    const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]);
    addParentDeclarationRelatedInfo(node, diag2);
    addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind]));
    return diag2;
  }
  function createBindingElementError(node) {
    return createDiagnosticForNode(node, Diagnostics.Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations);
  }
  function createVariableOrPropertyError(node) {
    const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]);
    const targetStr = getTextOfNode(
      node.name,
      /*includeTrivia*/
      false
    );
    addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind], targetStr));
    return diag2;
  }
  function createParameterError(node) {
    if (isSetAccessor(node.parent)) {
      return createAccessorTypeError(node.parent);
    }
    const addUndefined = resolver.requiresAddingImplicitUndefined(
      node,
      /*enclosingDeclaration*/
      void 0
    );
    if (!addUndefined && node.initializer) {
      return createExpressionError(node.initializer);
    }
    const message = addUndefined ? Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations : errorByDeclarationKind[node.kind];
    const diag2 = createDiagnosticForNode(node, message);
    const targetStr = getTextOfNode(
      node.name,
      /*includeTrivia*/
      false
    );
    addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind], targetStr));
    return diag2;
  }
  function createClassExpressionError(node) {
    return createExpressionError(node, Diagnostics.Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations);
  }
  function createEntityInTypeNodeError(node) {
    const diag2 = createDiagnosticForNode(node, Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations, getTextOfNode(
      node,
      /*includeTrivia*/
      false
    ));
    addParentDeclarationRelatedInfo(node, diag2);
    return diag2;
  }
  function createExpressionError(node, diagnosticMessage) {
    const parentDeclaration = findNearestDeclaration(node);
    let diag2;
    if (parentDeclaration) {
      const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode(
        parentDeclaration.name,
        /*includeTrivia*/
        false
      );
      const parent = findAncestor(node.parent, (n) => isExportAssignment(n) || (isStatement(n) ? "quit" : !isParenthesizedExpression(n) && !isTypeAssertionExpression(n) && !isAsExpression(n)));
      if (parentDeclaration === parent) {
        diag2 = createDiagnosticForNode(node, diagnosticMessage ?? errorByDeclarationKind[parentDeclaration.kind]);
        addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr));
      } else {
        diag2 = createDiagnosticForNode(node, diagnosticMessage ?? Diagnostics.Expression_type_can_t_be_inferred_with_isolatedDeclarations);
        addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr));
        addRelatedInfo(diag2, createDiagnosticForNode(node, Diagnostics.Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit));
      }
    } else {
      diag2 = createDiagnosticForNode(node, diagnosticMessage ?? Diagnostics.Expression_type_can_t_be_inferred_with_isolatedDeclarations);
    }
    return diag2;
  }
}

// src/compiler/transformers/declarations.ts
function getDeclarationDiagnostics(host, resolver, file) {
  const compilerOptions = host.getCompilerOptions();
  const files = filter(getSourceFilesToEmit(host, file), isSourceFileNotJson);
  return contains(files, file) ? transformNodes(
    resolver,
    host,
    factory,
    compilerOptions,
    [file],
    [transformDeclarations],
    /*allowDtsFiles*/
    false
  ).diagnostics : void 0;
}
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */;
var declarationEmitInternalNodeBuilderFlags = 8 /* AllowUnresolvedNames */;
function transformDeclarations(context) {
  const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context");
  let getSymbolAccessibilityDiagnostic = throwDiagnostic;
  let needsDeclare = true;
  let isBundledEmit = false;
  let resultHasExternalModuleIndicator = false;
  let needsScopeFixMarker = false;
  let resultHasScopeMarker = false;
  let enclosingDeclaration;
  let lateMarkedStatements;
  let lateStatementReplacementMap;
  let suppressNewDiagnosticContexts;
  const { factory: factory2 } = context;
  const host = context.getEmitHost();
  let restoreFallbackNode = () => void 0;
  const symbolTracker = {
    trackSymbol,
    reportInaccessibleThisError,
    reportInaccessibleUniqueSymbolError,
    reportCyclicStructureError,
    reportPrivateInBaseOfClassExpression,
    reportLikelyUnsafeImportRequiredError,
    reportTruncationError,
    moduleResolverHost: host,
    reportNonlocalAugmentation,
    reportNonSerializableProperty,
    reportInferenceFallback,
    pushErrorFallbackNode(node) {
      const currentFallback = errorFallbackNode;
      const currentRestore = restoreFallbackNode;
      restoreFallbackNode = () => {
        restoreFallbackNode = currentRestore;
        errorFallbackNode = currentFallback;
      };
      errorFallbackNode = node;
    },
    popErrorFallbackNode() {
      restoreFallbackNode();
    }
  };
  let errorNameNode;
  let errorFallbackNode;
  let currentSourceFile;
  let rawReferencedFiles;
  let rawTypeReferenceDirectives;
  let rawLibReferenceDirectives;
  const resolver = context.getEmitResolver();
  const options = context.getCompilerOptions();
  const getIsolatedDeclarationError = createGetIsolatedDeclarationErrors(resolver);
  const { stripInternal, isolatedDeclarations } = options;
  return transformRoot;
  function reportExpandoFunctionErrors(node) {
    resolver.getPropertiesOfContainerFunction(node).forEach((p) => {
      if (isExpandoPropertyDeclaration(p.valueDeclaration)) {
        const errorTarget = isBinaryExpression(p.valueDeclaration) ? p.valueDeclaration.left : p.valueDeclaration;
        context.addDiagnostic(createDiagnosticForNode(
          errorTarget,
          Diagnostics.Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function
        ));
      }
    });
  }
  function reportInferenceFallback(node) {
    if (!isolatedDeclarations || isSourceFileJS(currentSourceFile)) return;
    if (getSourceFileOfNode(node) !== currentSourceFile) return;
    if (isVariableDeclaration(node) && resolver.isExpandoFunctionDeclaration(node)) {
      reportExpandoFunctionErrors(node);
    } else {
      context.addDiagnostic(getIsolatedDeclarationError(node));
    }
  }
  function handleSymbolAccessibilityError(symbolAccessibilityResult) {
    if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
      if (symbolAccessibilityResult.aliasesToMakeVisible) {
        if (!lateMarkedStatements) {
          lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
        } else {
          for (const ref of symbolAccessibilityResult.aliasesToMakeVisible) {
            pushIfUnique(lateMarkedStatements, ref);
          }
        }
      }
    } else if (symbolAccessibilityResult.accessibility !== 3 /* NotResolved */) {
      const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
      if (errorInfo) {
        if (errorInfo.typeName) {
          context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
        } else {
          context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
        }
        return true;
      }
    }
    return false;
  }
  function trackSymbol(symbol, enclosingDeclaration2, meaning) {
    if (symbol.flags & 262144 /* TypeParameter */) return false;
    const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible(
      symbol,
      enclosingDeclaration2,
      meaning,
      /*shouldComputeAliasToMarkVisible*/
      true
    ));
    return issuedDiagnostic;
  }
  function reportPrivateInBaseOfClassExpression(propertyName) {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(
        addRelatedInfo(
          createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected, propertyName),
          ...isVariableDeclaration((errorNameNode || errorFallbackNode).parent) ? [createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Add_a_type_annotation_to_the_variable_0, errorDeclarationNameWithFallback())] : []
        )
      );
    }
  }
  function errorDeclarationNameWithFallback() {
    return errorNameNode ? declarationNameToString(errorNameNode) : errorFallbackNode && getNameOfDeclaration(errorFallbackNode) ? declarationNameToString(getNameOfDeclaration(errorFallbackNode)) : errorFallbackNode && isExportAssignment(errorFallbackNode) ? errorFallbackNode.isExportEquals ? "export=" : "default" : "(Missing)";
  }
  function reportInaccessibleUniqueSymbolError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "unique symbol"));
    }
  }
  function reportCyclicStructureError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, errorDeclarationNameWithFallback()));
    }
  }
  function reportInaccessibleThisError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), "this"));
    }
  }
  function reportLikelyUnsafeImportRequiredError(specifier) {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, errorDeclarationNameWithFallback(), specifier));
    }
  }
  function reportTruncationError() {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
    }
  }
  function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
    var _a;
    const primaryDeclaration = (_a = parentSymbol.declarations) == null ? void 0 : _a.find((d) => getSourceFileOfNode(d) === containingFile);
    const augmentingDeclarations = filter(symbol.declarations, (d) => getSourceFileOfNode(d) !== containingFile);
    if (primaryDeclaration && augmentingDeclarations) {
      for (const augmentations of augmentingDeclarations) {
        context.addDiagnostic(addRelatedInfo(
          createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized),
          createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file)
        ));
      }
    }
  }
  function reportNonSerializableProperty(propertyName) {
    if (errorNameNode || errorFallbackNode) {
      context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.The_type_of_this_node_cannot_be_serialized_because_its_property_0_cannot_be_serialized, propertyName));
    }
  }
  function transformDeclarationsForJS(sourceFile) {
    const oldDiag = getSymbolAccessibilityDiagnostic;
    getSymbolAccessibilityDiagnostic = (s) => s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : {
      diagnosticMessage: s.errorModuleName ? Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
      errorNode: s.errorNode || sourceFile
    };
    const result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker);
    getSymbolAccessibilityDiagnostic = oldDiag;
    return result;
  }
  function transformRoot(node) {
    if (node.kind === 307 /* SourceFile */ && node.isDeclarationFile) {
      return node;
    }
    if (node.kind === 308 /* Bundle */) {
      isBundledEmit = true;
      rawReferencedFiles = [];
      rawTypeReferenceDirectives = [];
      rawLibReferenceDirectives = [];
      let hasNoDefaultLib = false;
      const bundle = factory2.createBundle(
        map(node.sourceFiles, (sourceFile) => {
          if (sourceFile.isDeclarationFile) return void 0;
          hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib;
          currentSourceFile = sourceFile;
          enclosingDeclaration = sourceFile;
          lateMarkedStatements = void 0;
          suppressNewDiagnosticContexts = false;
          lateStatementReplacementMap = /* @__PURE__ */ new Map();
          getSymbolAccessibilityDiagnostic = throwDiagnostic;
          needsScopeFixMarker = false;
          resultHasScopeMarker = false;
          collectFileReferences(sourceFile);
          if (isExternalOrCommonJsModule(sourceFile) || isJsonSourceFile(sourceFile)) {
            resultHasExternalModuleIndicator = false;
            needsDeclare = false;
            const statements = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement);
            const newFile = factory2.updateSourceFile(
              sourceFile,
              [factory2.createModuleDeclaration(
                [factory2.createModifier(138 /* DeclareKeyword */)],
                factory2.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)),
                factory2.createModuleBlock(setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements))
              )],
              /*isDeclarationFile*/
              true,
              /*referencedFiles*/
              [],
              /*typeReferences*/
              [],
              /*hasNoDefaultLib*/
              false,
              /*libReferences*/
              []
            );
            return newFile;
          }
          needsDeclare = true;
          const updated = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement);
          return factory2.updateSourceFile(
            sourceFile,
            transformAndReplaceLatePaintedStatements(updated),
            /*isDeclarationFile*/
            true,
            /*referencedFiles*/
            [],
            /*typeReferences*/
            [],
            /*hasNoDefaultLib*/
            false,
            /*libReferences*/
            []
          );
        })
      );
      const outputFilePath2 = getDirectoryPath(normalizeSlashes(getOutputPathsFor(
        node,
        host,
        /*forceDtsPaths*/
        true
      ).declarationFilePath));
      bundle.syntheticFileReferences = getReferencedFiles(outputFilePath2);
      bundle.syntheticTypeReferences = getTypeReferences();
      bundle.syntheticLibReferences = getLibReferences();
      bundle.hasNoDefaultLib = hasNoDefaultLib;
      return bundle;
    }
    needsDeclare = true;
    needsScopeFixMarker = false;
    resultHasScopeMarker = false;
    enclosingDeclaration = node;
    currentSourceFile = node;
    getSymbolAccessibilityDiagnostic = throwDiagnostic;
    isBundledEmit = false;
    resultHasExternalModuleIndicator = false;
    suppressNewDiagnosticContexts = false;
    lateMarkedStatements = void 0;
    lateStatementReplacementMap = /* @__PURE__ */ new Map();
    rawReferencedFiles = [];
    rawTypeReferenceDirectives = [];
    rawLibReferenceDirectives = [];
    collectFileReferences(currentSourceFile);
    let combinedStatements;
    if (isSourceFileJS(currentSourceFile)) {
      combinedStatements = factory2.createNodeArray(transformDeclarationsForJS(node));
    } else {
      const statements = visitNodes2(node.statements, visitDeclarationStatements, isStatement);
      combinedStatements = setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
      if (isExternalModule(node) && (!resultHasExternalModuleIndicator || needsScopeFixMarker && !resultHasScopeMarker)) {
        combinedStatements = setTextRange(factory2.createNodeArray([...combinedStatements, createEmptyExports(factory2)]), combinedStatements);
      }
    }
    const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(
      node,
      host,
      /*forceDtsPaths*/
      true
    ).declarationFilePath));
    return factory2.updateSourceFile(
      node,
      combinedStatements,
      /*isDeclarationFile*/
      true,
      getReferencedFiles(outputFilePath),
      getTypeReferences(),
      node.hasNoDefaultLib,
      getLibReferences()
    );
    function collectFileReferences(sourceFile) {
      rawReferencedFiles = concatenate(rawReferencedFiles, map(sourceFile.referencedFiles, (f) => [sourceFile, f]));
      rawTypeReferenceDirectives = concatenate(rawTypeReferenceDirectives, sourceFile.typeReferenceDirectives);
      rawLibReferenceDirectives = concatenate(rawLibReferenceDirectives, sourceFile.libReferenceDirectives);
    }
    function copyFileReferenceAsSynthetic(ref) {
      const newRef = { ...ref };
      newRef.pos = -1;
      newRef.end = -1;
      return newRef;
    }
    function getTypeReferences() {
      return mapDefined(rawTypeReferenceDirectives, (ref) => {
        if (!ref.preserve) return void 0;
        return copyFileReferenceAsSynthetic(ref);
      });
    }
    function getLibReferences() {
      return mapDefined(rawLibReferenceDirectives, (ref) => {
        if (!ref.preserve) return void 0;
        return copyFileReferenceAsSynthetic(ref);
      });
    }
    function getReferencedFiles(outputFilePath2) {
      return mapDefined(rawReferencedFiles, ([sourceFile, ref]) => {
        if (!ref.preserve) return void 0;
        const file = host.getSourceFileFromReference(sourceFile, ref);
        if (!file) {
          return void 0;
        }
        let declFileName;
        if (file.isDeclarationFile) {
          declFileName = file.fileName;
        } else {
          if (isBundledEmit && contains(node.sourceFiles, file)) return;
          const paths = getOutputPathsFor(
            file,
            host,
            /*forceDtsPaths*/
            true
          );
          declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
        }
        if (!declFileName) return void 0;
        const fileName = getRelativePathToDirectoryOrUrl(
          outputFilePath2,
          declFileName,
          host.getCurrentDirectory(),
          host.getCanonicalFileName,
          /*isAbsolutePathAnUrl*/
          false
        );
        const newRef = copyFileReferenceAsSynthetic(ref);
        newRef.fileName = fileName;
        return newRef;
      });
    }
  }
  function filterBindingPatternInitializers(name) {
    if (name.kind === 80 /* Identifier */) {
      return name;
    } else {
      if (name.kind === 207 /* ArrayBindingPattern */) {
        return factory2.updateArrayBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isArrayBindingElement));
      } else {
        return factory2.updateObjectBindingPattern(name, visitNodes2(name.elements, visitBindingElement, isBindingElement));
      }
    }
    function visitBindingElement(elem) {
      if (elem.kind === 232 /* OmittedExpression */) {
        return elem;
      }
      if (elem.propertyName && isComputedPropertyName(elem.propertyName) && isEntityNameExpression(elem.propertyName.expression)) {
        checkEntityNameVisibility(elem.propertyName.expression, enclosingDeclaration);
      }
      return factory2.updateBindingElement(
        elem,
        elem.dotDotDotToken,
        elem.propertyName,
        filterBindingPatternInitializers(elem.name),
        /*initializer*/
        void 0
      );
    }
  }
  function ensureParameter(p, modifierMask) {
    let oldDiag;
    if (!suppressNewDiagnosticContexts) {
      oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p);
    }
    const newParam = factory2.updateParameterDeclaration(
      p,
      maskModifiers(factory2, p, modifierMask),
      p.dotDotDotToken,
      filterBindingPatternInitializers(p.name),
      resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0,
      ensureType(
        p,
        /*ignorePrivate*/
        true
      ),
      // Ignore private param props, since this type is going straight back into a param
      ensureNoInitializer(p)
    );
    if (!suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = oldDiag;
    }
    return newParam;
  }
  function shouldPrintWithInitializer(node) {
    return canHaveLiteralInitializer(node) && !!node.initializer && resolver.isLiteralConstDeclaration(getParseTreeNode(node));
  }
  function ensureNoInitializer(node) {
    if (shouldPrintWithInitializer(node)) {
      const unwrappedInitializer = unwrapParenthesizedExpression(node.initializer);
      if (!isPrimitiveLiteralValue(unwrappedInitializer)) {
        reportInferenceFallback(node);
      }
      return resolver.createLiteralConstValue(getParseTreeNode(node, canHaveLiteralInitializer), symbolTracker);
    }
    return void 0;
  }
  function ensureType(node, ignorePrivate) {
    if (!ignorePrivate && hasEffectiveModifier(node, 2 /* Private */)) {
      return;
    }
    if (shouldPrintWithInitializer(node)) {
      return;
    }
    if (!isExportAssignment(node) && !isBindingElement(node) && node.type && (!isParameter(node) || !resolver.requiresAddingImplicitUndefined(node, enclosingDeclaration))) {
      return visitNode(node.type, visitDeclarationSubtree, isTypeNode);
    }
    const oldErrorNameNode = errorNameNode;
    errorNameNode = node.name;
    let oldDiag;
    if (!suppressNewDiagnosticContexts) {
      oldDiag = getSymbolAccessibilityDiagnostic;
      if (canProduceDiagnostics(node)) {
        getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node);
      }
    }
    let typeNode;
    if (hasInferredType(node)) {
      typeNode = resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker);
    } else if (isFunctionLike(node)) {
      typeNode = resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker);
    } else {
      Debug.assertNever(node);
    }
    errorNameNode = oldErrorNameNode;
    if (!suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = oldDiag;
    }
    return typeNode ?? factory2.createKeywordTypeNode(133 /* AnyKeyword */);
  }
  function isDeclarationAndNotVisible(node) {
    node = getParseTreeNode(node);
    switch (node.kind) {
      case 262 /* FunctionDeclaration */:
      case 267 /* ModuleDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 263 /* ClassDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 266 /* EnumDeclaration */:
        return !resolver.isDeclarationVisible(node);
      // The following should be doing their own visibility checks based on filtering their members
      case 260 /* VariableDeclaration */:
        return !getBindingNameVisible(node);
      case 271 /* ImportEqualsDeclaration */:
      case 272 /* ImportDeclaration */:
      case 278 /* ExportDeclaration */:
      case 277 /* ExportAssignment */:
        return false;
      case 175 /* ClassStaticBlockDeclaration */:
        return true;
    }
    return false;
  }
  function shouldEmitFunctionProperties(input) {
    var _a;
    if (input.body) {
      return true;
    }
    const overloadSignatures = (_a = input.symbol.declarations) == null ? void 0 : _a.filter((decl) => isFunctionDeclaration(decl) && !decl.body);
    return !overloadSignatures || overloadSignatures.indexOf(input) === overloadSignatures.length - 1;
  }
  function getBindingNameVisible(elem) {
    if (isOmittedExpression(elem)) {
      return false;
    }
    if (isBindingPattern(elem.name)) {
      return some(elem.name.elements, getBindingNameVisible);
    } else {
      return resolver.isDeclarationVisible(elem);
    }
  }
  function updateParamsList(node, params, modifierMask) {
    if (hasEffectiveModifier(node, 2 /* Private */)) {
      return factory2.createNodeArray();
    }
    const newParams = map(params, (p) => ensureParameter(p, modifierMask));
    if (!newParams) {
      return factory2.createNodeArray();
    }
    return factory2.createNodeArray(newParams, params.hasTrailingComma);
  }
  function updateAccessorParamsList(input, isPrivate) {
    let newParams;
    if (!isPrivate) {
      const thisParameter = getThisParameter(input);
      if (thisParameter) {
        newParams = [ensureParameter(thisParameter)];
      }
    }
    if (isSetAccessorDeclaration(input)) {
      let newValueParameter;
      if (!isPrivate) {
        const valueParameter = getSetAccessorValueParameter(input);
        if (valueParameter) {
          newValueParameter = ensureParameter(valueParameter);
        }
      }
      if (!newValueParameter) {
        newValueParameter = factory2.createParameterDeclaration(
          /*modifiers*/
          void 0,
          /*dotDotDotToken*/
          void 0,
          "value"
        );
      }
      newParams = append(newParams, newValueParameter);
    }
    return factory2.createNodeArray(newParams || emptyArray);
  }
  function ensureTypeParams(node, params) {
    return hasEffectiveModifier(node, 2 /* Private */) ? void 0 : visitNodes2(params, visitDeclarationSubtree, isTypeParameterDeclaration);
  }
  function isEnclosingDeclaration(node) {
    return isSourceFile(node) || isTypeAliasDeclaration(node) || isModuleDeclaration(node) || isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionLike(node) || isIndexSignatureDeclaration(node) || isMappedTypeNode(node);
  }
  function checkEntityNameVisibility(entityName, enclosingDeclaration2) {
    const visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration2);
    handleSymbolAccessibilityError(visibilityResult);
  }
  function preserveJsDoc(updated, original) {
    if (hasJSDocNodes(updated) && hasJSDocNodes(original)) {
      updated.jsDoc = original.jsDoc;
    }
    return setCommentRange(updated, getCommentRange(original));
  }
  function rewriteModuleSpecifier2(parent, input) {
    if (!input) return void 0;
    resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 267 /* ModuleDeclaration */ && parent.kind !== 205 /* ImportType */;
    if (isStringLiteralLike(input)) {
      if (isBundledEmit) {
        const newName = getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
        if (newName) {
          return factory2.createStringLiteral(newName);
        }
      }
    }
    return input;
  }
  function transformImportEqualsDeclaration(decl) {
    if (!resolver.isDeclarationVisible(decl)) return;
    if (decl.moduleReference.kind === 283 /* ExternalModuleReference */) {
      const specifier = getExternalModuleImportEqualsDeclarationExpression(decl);
      return factory2.updateImportEqualsDeclaration(
        decl,
        decl.modifiers,
        decl.isTypeOnly,
        decl.name,
        factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier2(decl, specifier))
      );
    } else {
      const oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(decl);
      checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
      getSymbolAccessibilityDiagnostic = oldDiag;
      return decl;
    }
  }
  function transformImportDeclaration(decl) {
    if (!decl.importClause) {
      return factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        decl.importClause,
        rewriteModuleSpecifier2(decl, decl.moduleSpecifier),
        tryGetResolutionModeOverride(decl.attributes)
      );
    }
    const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : void 0;
    if (!decl.importClause.namedBindings) {
      return visibleDefaultBinding && factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        factory2.updateImportClause(
          decl.importClause,
          decl.importClause.isTypeOnly,
          visibleDefaultBinding,
          /*namedBindings*/
          void 0
        ),
        rewriteModuleSpecifier2(decl, decl.moduleSpecifier),
        tryGetResolutionModeOverride(decl.attributes)
      );
    }
    if (decl.importClause.namedBindings.kind === 274 /* NamespaceImport */) {
      const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : (
        /*namedBindings*/
        void 0
      );
      return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        factory2.updateImportClause(
          decl.importClause,
          decl.importClause.isTypeOnly,
          visibleDefaultBinding,
          namedBindings
        ),
        rewriteModuleSpecifier2(decl, decl.moduleSpecifier),
        tryGetResolutionModeOverride(decl.attributes)
      ) : void 0;
    }
    const bindingList = mapDefined(decl.importClause.namedBindings.elements, (b) => resolver.isDeclarationVisible(b) ? b : void 0);
    if (bindingList && bindingList.length || visibleDefaultBinding) {
      return factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        factory2.updateImportClause(
          decl.importClause,
          decl.importClause.isTypeOnly,
          visibleDefaultBinding,
          bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0
        ),
        rewriteModuleSpecifier2(decl, decl.moduleSpecifier),
        tryGetResolutionModeOverride(decl.attributes)
      );
    }
    if (resolver.isImportRequiredByAugmentation(decl)) {
      if (isolatedDeclarations) {
        context.addDiagnostic(createDiagnosticForNode(decl, Diagnostics.Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_supported_with_isolatedDeclarations));
      }
      return factory2.updateImportDeclaration(
        decl,
        decl.modifiers,
        /*importClause*/
        void 0,
        rewriteModuleSpecifier2(decl, decl.moduleSpecifier),
        tryGetResolutionModeOverride(decl.attributes)
      );
    }
  }
  function tryGetResolutionModeOverride(node) {
    const mode = getResolutionModeOverride(node);
    return node && mode !== void 0 ? node : void 0;
  }
  function transformAndReplaceLatePaintedStatements(statements) {
    while (length(lateMarkedStatements)) {
      const i = lateMarkedStatements.shift();
      if (!isLateVisibilityPaintedStatement(i)) {
        return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${Debug.formatSyntaxKind(i.kind)}`);
      }
      const priorNeedsDeclare = needsDeclare;
      needsDeclare = i.parent && isSourceFile(i.parent) && !(isExternalModule(i.parent) && isBundledEmit);
      const result = transformTopLevelDeclaration(i);
      needsDeclare = priorNeedsDeclare;
      lateStatementReplacementMap.set(getOriginalNodeId(i), result);
    }
    return visitNodes2(statements, visitLateVisibilityMarkedStatements, isStatement);
    function visitLateVisibilityMarkedStatements(statement) {
      if (isLateVisibilityPaintedStatement(statement)) {
        const key = getOriginalNodeId(statement);
        if (lateStatementReplacementMap.has(key)) {
          const result = lateStatementReplacementMap.get(key);
          lateStatementReplacementMap.delete(key);
          if (result) {
            if (isArray(result) ? some(result, needsScopeMarker) : needsScopeMarker(result)) {
              needsScopeFixMarker = true;
            }
            if (isSourceFile(statement.parent) && (isArray(result) ? some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result))) {
              resultHasExternalModuleIndicator = true;
            }
          }
          return result;
        }
      }
      return statement;
    }
  }
  function visitDeclarationSubtree(input) {
    if (shouldStripInternal(input)) return;
    if (isDeclaration(input)) {
      if (isDeclarationAndNotVisible(input)) return;
      if (hasDynamicName(input)) {
        if (isolatedDeclarations) {
          if (!resolver.isDefinitelyReferenceToGlobalSymbolObject(input.name.expression)) {
            if (isClassDeclaration(input.parent) || isObjectLiteralExpression(input.parent)) {
              context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations));
              return;
            } else if (
              // Type declarations just need to double-check that the input computed name is an entity name expression
              (isInterfaceDeclaration(input.parent) || isTypeLiteralNode(input.parent)) && !isEntityNameExpression(input.name.expression)
            ) {
              context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations));
              return;
            }
          }
        } else if (!resolver.isLateBound(getParseTreeNode(input)) || !isEntityNameExpression(input.name.expression)) {
          return;
        }
      }
    }
    if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return;
    if (isSemicolonClassElement(input)) return;
    let previousEnclosingDeclaration;
    if (isEnclosingDeclaration(input)) {
      previousEnclosingDeclaration = enclosingDeclaration;
      enclosingDeclaration = input;
    }
    const oldDiag = getSymbolAccessibilityDiagnostic;
    const canProduceDiagnostic = canProduceDiagnostics(input);
    const oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
    let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 187 /* TypeLiteral */ || input.kind === 200 /* MappedType */) && input.parent.kind !== 265 /* TypeAliasDeclaration */;
    if (isMethodDeclaration(input) || isMethodSignature(input)) {
      if (hasEffectiveModifier(input, 2 /* Private */)) {
        if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return;
        return cleanup(factory2.createPropertyDeclaration(
          ensureModifiers(input),
          input.name,
          /*questionOrExclamationToken*/
          void 0,
          /*type*/
          void 0,
          /*initializer*/
          void 0
        ));
      }
    }
    if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input);
    }
    if (isTypeQueryNode(input)) {
      checkEntityNameVisibility(input.exprName, enclosingDeclaration);
    }
    if (shouldEnterSuppressNewDiagnosticsContextContext) {
      suppressNewDiagnosticContexts = true;
    }
    if (isProcessedComponent(input)) {
      switch (input.kind) {
        case 233 /* ExpressionWithTypeArguments */: {
          if (isEntityName(input.expression) || isEntityNameExpression(input.expression)) {
            checkEntityNameVisibility(input.expression, enclosingDeclaration);
          }
          const node = visitEachChild(input, visitDeclarationSubtree, context);
          return cleanup(factory2.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
        }
        case 183 /* TypeReference */: {
          checkEntityNameVisibility(input.typeName, enclosingDeclaration);
          const node = visitEachChild(input, visitDeclarationSubtree, context);
          return cleanup(factory2.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
        }
        case 180 /* ConstructSignature */:
          return cleanup(factory2.updateConstructSignature(
            input,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input)
          ));
        case 176 /* Constructor */: {
          const ctor = factory2.createConstructorDeclaration(
            /*modifiers*/
            ensureModifiers(input),
            updateParamsList(input, input.parameters, 0 /* None */),
            /*body*/
            void 0
          );
          return cleanup(ctor);
        }
        case 174 /* MethodDeclaration */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          const sig = factory2.createMethodDeclaration(
            ensureModifiers(input),
            /*asteriskToken*/
            void 0,
            input.name,
            input.questionToken,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input),
            /*body*/
            void 0
          );
          return cleanup(sig);
        }
        case 177 /* GetAccessor */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updateGetAccessorDeclaration(
            input,
            ensureModifiers(input),
            input.name,
            updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)),
            ensureType(input),
            /*body*/
            void 0
          ));
        }
        case 178 /* SetAccessor */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updateSetAccessorDeclaration(
            input,
            ensureModifiers(input),
            input.name,
            updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)),
            /*body*/
            void 0
          ));
        }
        case 172 /* PropertyDeclaration */:
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updatePropertyDeclaration(
            input,
            ensureModifiers(input),
            input.name,
            input.questionToken,
            ensureType(input),
            ensureNoInitializer(input)
          ));
        case 171 /* PropertySignature */:
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updatePropertySignature(
            input,
            ensureModifiers(input),
            input.name,
            input.questionToken,
            ensureType(input)
          ));
        case 173 /* MethodSignature */: {
          if (isPrivateIdentifier(input.name)) {
            return cleanup(
              /*returnValue*/
              void 0
            );
          }
          return cleanup(factory2.updateMethodSignature(
            input,
            ensureModifiers(input),
            input.name,
            input.questionToken,
            ensureTypeParams(input, input.typeParameters),
            updateParamsList(input, input.parameters),
            ensureType(input)
          ));
        }
        case 179 /* CallSignature */: {
          return cleanup(
            factory2.updateCallSignature(
              input,
              ensureTypeParams(input, input.typeParameters),
              updateParamsList(input, input.parameters),
              ensureType(input)
            )
          );
        }
        case 181 /* IndexSignature */: {
          return cleanup(factory2.updateIndexSignature(
            input,
            ensureModifiers(input),
            updateParamsList(input, input.parameters),
            visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(133 /* AnyKeyword */)
          ));
        }
        case 260 /* VariableDeclaration */: {
          if (isBindingPattern(input.name)) {
            return recreateBindingPattern(input.name);
          }
          shouldEnterSuppressNewDiagnosticsContextContext = true;
          suppressNewDiagnosticContexts = true;
          return cleanup(factory2.updateVariableDeclaration(
            input,
            input.name,
            /*exclamationToken*/
            void 0,
            ensureType(input),
            ensureNoInitializer(input)
          ));
        }
        case 168 /* TypeParameter */: {
          if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
            return cleanup(factory2.updateTypeParameterDeclaration(
              input,
              input.modifiers,
              input.name,
              /*constraint*/
              void 0,
              /*defaultType*/
              void 0
            ));
          }
          return cleanup(visitEachChild(input, visitDeclarationSubtree, context));
        }
        case 194 /* ConditionalType */: {
          const checkType = visitNode(input.checkType, visitDeclarationSubtree, isTypeNode);
          const extendsType = visitNode(input.extendsType, visitDeclarationSubtree, isTypeNode);
          const oldEnclosingDecl = enclosingDeclaration;
          enclosingDeclaration = input.trueType;
          const trueType = visitNode(input.trueType, visitDeclarationSubtree, isTypeNode);
          enclosingDeclaration = oldEnclosingDecl;
          const falseType = visitNode(input.falseType, visitDeclarationSubtree, isTypeNode);
          Debug.assert(checkType);
          Debug.assert(extendsType);
          Debug.assert(trueType);
          Debug.assert(falseType);
          return cleanup(factory2.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
        }
        case 184 /* FunctionType */: {
          return cleanup(factory2.updateFunctionTypeNode(
            input,
            visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration),
            updateParamsList(input, input.parameters),
            Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode))
          ));
        }
        case 185 /* ConstructorType */: {
          return cleanup(factory2.updateConstructorTypeNode(
            input,
            ensureModifiers(input),
            visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration),
            updateParamsList(input, input.parameters),
            Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode))
          ));
        }
        case 205 /* ImportType */: {
          if (!isLiteralImportTypeNode(input)) return cleanup(input);
          return cleanup(factory2.updateImportTypeNode(
            input,
            factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier2(input, input.argument.literal)),
            input.attributes,
            input.qualifier,
            visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode),
            input.isTypeOf
          ));
        }
        default:
          Debug.assertNever(input, `Attempted to process unhandled node kind: ${Debug.formatSyntaxKind(input.kind)}`);
      }
    }
    if (isTupleTypeNode(input) && getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === getLineAndCharacterOfPosition(currentSourceFile, input.end).line) {
      setEmitFlags(input, 1 /* SingleLine */);
    }
    return cleanup(visitEachChild(input, visitDeclarationSubtree, context));
    function cleanup(returnValue) {
      if (returnValue && canProduceDiagnostic && hasDynamicName(input)) {
        checkName(input);
      }
      if (isEnclosingDeclaration(input)) {
        enclosingDeclaration = previousEnclosingDeclaration;
      }
      if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
        getSymbolAccessibilityDiagnostic = oldDiag;
      }
      if (shouldEnterSuppressNewDiagnosticsContextContext) {
        suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
      }
      if (returnValue === input) {
        return returnValue;
      }
      return returnValue && setOriginalNode(preserveJsDoc(returnValue, input), input);
    }
  }
  function isPrivateMethodTypeParameter(node) {
    return node.parent.kind === 174 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 2 /* Private */);
  }
  function visitDeclarationStatements(input) {
    if (!isPreservedDeclarationStatement(input)) {
      return;
    }
    if (shouldStripInternal(input)) return;
    switch (input.kind) {
      case 278 /* ExportDeclaration */: {
        if (isSourceFile(input.parent)) {
          resultHasExternalModuleIndicator = true;
        }
        resultHasScopeMarker = true;
        return factory2.updateExportDeclaration(
          input,
          input.modifiers,
          input.isTypeOnly,
          input.exportClause,
          rewriteModuleSpecifier2(input, input.moduleSpecifier),
          tryGetResolutionModeOverride(input.attributes)
        );
      }
      case 277 /* ExportAssignment */: {
        if (isSourceFile(input.parent)) {
          resultHasExternalModuleIndicator = true;
        }
        resultHasScopeMarker = true;
        if (input.expression.kind === 80 /* Identifier */) {
          return input;
        } else {
          const newId = factory2.createUniqueName("_default", 16 /* Optimistic */);
          getSymbolAccessibilityDiagnostic = () => ({
            diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
            errorNode: input
          });
          errorFallbackNode = input;
          const type = ensureType(input);
          const varDecl = factory2.createVariableDeclaration(
            newId,
            /*exclamationToken*/
            void 0,
            type,
            /*initializer*/
            void 0
          );
          errorFallbackNode = void 0;
          const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */));
          preserveJsDoc(statement, input);
          removeAllComments(input);
          return [statement, factory2.updateExportAssignment(input, input.modifiers, newId)];
        }
      }
    }
    const result = transformTopLevelDeclaration(input);
    lateStatementReplacementMap.set(getOriginalNodeId(input), result);
    return input;
  }
  function stripExportModifiers(statement) {
    if (isImportEqualsDeclaration(statement) || hasEffectiveModifier(statement, 2048 /* Default */) || !canHaveModifiers(statement)) {
      return statement;
    }
    const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(statement) & (131071 /* All */ ^ 32 /* Export */));
    return factory2.replaceModifiers(statement, modifiers);
  }
  function updateModuleDeclarationAndKeyword(node, modifiers, name, body) {
    const updated = factory2.updateModuleDeclaration(node, modifiers, name, body);
    if (isAmbientModule(updated) || updated.flags & 32 /* Namespace */) {
      return updated;
    }
    const fixed = factory2.createModuleDeclaration(
      updated.modifiers,
      updated.name,
      updated.body,
      updated.flags | 32 /* Namespace */
    );
    setOriginalNode(fixed, updated);
    setTextRange(fixed, updated);
    return fixed;
  }
  function transformTopLevelDeclaration(input) {
    if (lateMarkedStatements) {
      while (orderedRemoveItem(lateMarkedStatements, input)) ;
    }
    if (shouldStripInternal(input)) return;
    switch (input.kind) {
      case 271 /* ImportEqualsDeclaration */: {
        return transformImportEqualsDeclaration(input);
      }
      case 272 /* ImportDeclaration */: {
        return transformImportDeclaration(input);
      }
    }
    if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return;
    if (isJSDocImportTag(input)) return;
    if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return;
    let previousEnclosingDeclaration;
    if (isEnclosingDeclaration(input)) {
      previousEnclosingDeclaration = enclosingDeclaration;
      enclosingDeclaration = input;
    }
    const canProdiceDiagnostic = canProduceDiagnostics(input);
    const oldDiag = getSymbolAccessibilityDiagnostic;
    if (canProdiceDiagnostic) {
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input);
    }
    const previousNeedsDeclare = needsDeclare;
    switch (input.kind) {
      case 265 /* TypeAliasDeclaration */: {
        needsDeclare = false;
        const clean2 = cleanup(factory2.updateTypeAliasDeclaration(
          input,
          ensureModifiers(input),
          input.name,
          visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration),
          Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode))
        ));
        needsDeclare = previousNeedsDeclare;
        return clean2;
      }
      case 264 /* InterfaceDeclaration */: {
        return cleanup(factory2.updateInterfaceDeclaration(
          input,
          ensureModifiers(input),
          input.name,
          ensureTypeParams(input, input.typeParameters),
          transformHeritageClauses(input.heritageClauses),
          visitNodes2(input.members, visitDeclarationSubtree, isTypeElement)
        ));
      }
      case 262 /* FunctionDeclaration */: {
        const clean2 = cleanup(factory2.updateFunctionDeclaration(
          input,
          ensureModifiers(input),
          /*asteriskToken*/
          void 0,
          input.name,
          ensureTypeParams(input, input.typeParameters),
          updateParamsList(input, input.parameters),
          ensureType(input),
          /*body*/
          void 0
        ));
        if (clean2 && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) {
          const props = resolver.getPropertiesOfContainerFunction(input);
          if (isolatedDeclarations) {
            reportExpandoFunctionErrors(input);
          }
          const fakespace = parseNodeFactory.createModuleDeclaration(
            /*modifiers*/
            void 0,
            clean2.name || factory2.createIdentifier("_default"),
            factory2.createModuleBlock([]),
            32 /* Namespace */
          );
          setParent(fakespace, enclosingDeclaration);
          fakespace.locals = createSymbolTable(props);
          fakespace.symbol = props[0].parent;
          const exportMappings = [];
          let declarations = mapDefined(props, (p) => {
            if (!isExpandoPropertyDeclaration(p.valueDeclaration)) {
              return void 0;
            }
            const nameStr = unescapeLeadingUnderscores(p.escapedName);
            if (!isIdentifierText(nameStr, 99 /* ESNext */)) {
              return void 0;
            }
            getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
            const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags | 2 /* NoSyntacticPrinter */, symbolTracker);
            getSymbolAccessibilityDiagnostic = oldDiag;
            const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr);
            const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr);
            if (isNonContextualKeywordName) {
              exportMappings.push([name, nameStr]);
            }
            const varDecl = factory2.createVariableDeclaration(
              name,
              /*exclamationToken*/
              void 0,
              type,
              /*initializer*/
              void 0
            );
            return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [factory2.createToken(95 /* ExportKeyword */)], factory2.createVariableDeclarationList([varDecl]));
          });
          if (!exportMappings.length) {
            declarations = mapDefined(declarations, (declaration) => factory2.replaceModifiers(declaration, 0 /* None */));
          } else {
            declarations.push(factory2.createExportDeclaration(
              /*modifiers*/
              void 0,
              /*isTypeOnly*/
              false,
              factory2.createNamedExports(map(exportMappings, ([gen, exp]) => {
                return factory2.createExportSpecifier(
                  /*isTypeOnly*/
                  false,
                  gen,
                  exp
                );
              }))
            ));
          }
          const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 32 /* Namespace */);
          if (!hasEffectiveModifier(clean2, 2048 /* Default */)) {
            return [clean2, namespaceDecl];
          }
          const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~2080 /* ExportDefault */ | 128 /* Ambient */);
          const cleanDeclaration = factory2.updateFunctionDeclaration(
            clean2,
            modifiers,
            /*asteriskToken*/
            void 0,
            clean2.name,
            clean2.typeParameters,
            clean2.parameters,
            clean2.type,
            /*body*/
            void 0
          );
          const namespaceDeclaration = factory2.updateModuleDeclaration(
            namespaceDecl,
            modifiers,
            namespaceDecl.name,
            namespaceDecl.body
          );
          const exportDefaultDeclaration = factory2.createExportAssignment(
            /*modifiers*/
            void 0,
            /*isExportEquals*/
            false,
            namespaceDecl.name
          );
          if (isSourceFile(input.parent)) {
            resultHasExternalModuleIndicator = true;
          }
          resultHasScopeMarker = true;
          return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
        } else {
          return clean2;
        }
      }
      case 267 /* ModuleDeclaration */: {
        needsDeclare = false;
        const inner = input.body;
        if (inner && inner.kind === 268 /* ModuleBlock */) {
          const oldNeedsScopeFix = needsScopeFixMarker;
          const oldHasScopeFix = resultHasScopeMarker;
          resultHasScopeMarker = false;
          needsScopeFixMarker = false;
          const statements = visitNodes2(inner.statements, visitDeclarationStatements, isStatement);
          let lateStatements = transformAndReplaceLatePaintedStatements(statements);
          if (input.flags & 33554432 /* Ambient */) {
            needsScopeFixMarker = false;
          }
          if (!isGlobalScopeAugmentation(input) && !hasScopeMarker2(lateStatements) && !resultHasScopeMarker) {
            if (needsScopeFixMarker) {
              lateStatements = factory2.createNodeArray([...lateStatements, createEmptyExports(factory2)]);
            } else {
              lateStatements = visitNodes2(lateStatements, stripExportModifiers, isStatement);
            }
          }
          const body = factory2.updateModuleBlock(inner, lateStatements);
          needsDeclare = previousNeedsDeclare;
          needsScopeFixMarker = oldNeedsScopeFix;
          resultHasScopeMarker = oldHasScopeFix;
          const mods = ensureModifiers(input);
          return cleanup(updateModuleDeclarationAndKeyword(
            input,
            mods,
            isExternalModuleAugmentation(input) ? rewriteModuleSpecifier2(input, input.name) : input.name,
            body
          ));
        } else {
          needsDeclare = previousNeedsDeclare;
          const mods = ensureModifiers(input);
          needsDeclare = false;
          visitNode(inner, visitDeclarationStatements);
          const id = getOriginalNodeId(inner);
          const body = lateStatementReplacementMap.get(id);
          lateStatementReplacementMap.delete(id);
          return cleanup(updateModuleDeclarationAndKeyword(
            input,
            mods,
            input.name,
            body
          ));
        }
      }
      case 263 /* ClassDeclaration */: {
        errorNameNode = input.name;
        errorFallbackNode = input;
        const modifiers = factory2.createNodeArray(ensureModifiers(input));
        const typeParameters = ensureTypeParams(input, input.typeParameters);
        const ctor = getFirstConstructorWithBody(input);
        let parameterProperties;
        if (ctor) {
          const oldDiag2 = getSymbolAccessibilityDiagnostic;
          parameterProperties = compact(flatMap(ctor.parameters, (param) => {
            if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return;
            getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param);
            if (param.name.kind === 80 /* Identifier */) {
              return preserveJsDoc(
                factory2.createPropertyDeclaration(
                  ensureModifiers(param),
                  param.name,
                  param.questionToken,
                  ensureType(param),
                  ensureNoInitializer(param)
                ),
                param
              );
            } else {
              return walkBindingPattern(param.name);
            }
            function walkBindingPattern(pattern) {
              let elems;
              for (const elem of pattern.elements) {
                if (isOmittedExpression(elem)) continue;
                if (isBindingPattern(elem.name)) {
                  elems = concatenate(elems, walkBindingPattern(elem.name));
                }
                elems = elems || [];
                elems.push(factory2.createPropertyDeclaration(
                  ensureModifiers(param),
                  elem.name,
                  /*questionOrExclamationToken*/
                  void 0,
                  ensureType(elem),
                  /*initializer*/
                  void 0
                ));
              }
              return elems;
            }
          }));
          getSymbolAccessibilityDiagnostic = oldDiag2;
        }
        const hasPrivateIdentifier = some(input.members, (member) => !!member.name && isPrivateIdentifier(member.name));
        const privateIdentifier = hasPrivateIdentifier ? [
          factory2.createPropertyDeclaration(
            /*modifiers*/
            void 0,
            factory2.createPrivateIdentifier("#private"),
            /*questionOrExclamationToken*/
            void 0,
            /*type*/
            void 0,
            /*initializer*/
            void 0
          )
        ] : void 0;
        const lateIndexes = resolver.createLateBoundIndexSignatures(input, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker);
        const memberNodes = concatenate(concatenate(concatenate(privateIdentifier, lateIndexes), parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement));
        const members = factory2.createNodeArray(memberNodes);
        const extendsClause = getEffectiveBaseTypeNode(input);
        if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */) {
          const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default";
          const newId = factory2.createUniqueName(`${oldId}_base`, 16 /* Optimistic */);
          getSymbolAccessibilityDiagnostic = () => ({
            diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
            errorNode: extendsClause,
            typeName: input.name
          });
          const varDecl = factory2.createVariableDeclaration(
            newId,
            /*exclamationToken*/
            void 0,
            resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker),
            /*initializer*/
            void 0
          );
          const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */));
          const heritageClauses = factory2.createNodeArray(map(input.heritageClauses, (clause) => {
            if (clause.token === 96 /* ExtendsKeyword */) {
              const oldDiag2 = getSymbolAccessibilityDiagnostic;
              getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
              const newClause = factory2.updateHeritageClause(clause, map(clause.types, (t) => factory2.updateExpressionWithTypeArguments(t, newId, visitNodes2(t.typeArguments, visitDeclarationSubtree, isTypeNode))));
              getSymbolAccessibilityDiagnostic = oldDiag2;
              return newClause;
            }
            return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */)), visitDeclarationSubtree, isExpressionWithTypeArguments));
          }));
          return [
            statement,
            cleanup(factory2.updateClassDeclaration(
              input,
              modifiers,
              input.name,
              typeParameters,
              heritageClauses,
              members
            ))
          ];
        } else {
          const heritageClauses = transformHeritageClauses(input.heritageClauses);
          return cleanup(factory2.updateClassDeclaration(
            input,
            modifiers,
            input.name,
            typeParameters,
            heritageClauses,
            members
          ));
        }
      }
      case 243 /* VariableStatement */: {
        return cleanup(transformVariableStatement(input));
      }
      case 266 /* EnumDeclaration */: {
        return cleanup(factory2.updateEnumDeclaration(
          input,
          factory2.createNodeArray(ensureModifiers(input)),
          input.name,
          factory2.createNodeArray(mapDefined(input.members, (m) => {
            if (shouldStripInternal(m)) return;
            const enumValue = resolver.getEnumMemberValue(m);
            const constValue = enumValue == null ? void 0 : enumValue.value;
            if (isolatedDeclarations && m.initializer && (enumValue == null ? void 0 : enumValue.hasExternalReferences) && // This will be its own compiler error instead, so don't report.
            !isComputedPropertyName(m.name)) {
              context.addDiagnostic(createDiagnosticForNode(m, Diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations));
            }
            const newInitializer = constValue === void 0 ? void 0 : typeof constValue === "string" ? factory2.createStringLiteral(constValue) : constValue < 0 ? factory2.createPrefixUnaryExpression(41 /* MinusToken */, factory2.createNumericLiteral(-constValue)) : factory2.createNumericLiteral(constValue);
            return preserveJsDoc(factory2.updateEnumMember(m, m.name, newInitializer), m);
          }))
        ));
      }
    }
    return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${Debug.formatSyntaxKind(input.kind)}`);
    function cleanup(node) {
      if (isEnclosingDeclaration(input)) {
        enclosingDeclaration = previousEnclosingDeclaration;
      }
      if (canProdiceDiagnostic) {
        getSymbolAccessibilityDiagnostic = oldDiag;
      }
      if (input.kind === 267 /* ModuleDeclaration */) {
        needsDeclare = previousNeedsDeclare;
      }
      if (node === input) {
        return node;
      }
      errorFallbackNode = void 0;
      errorNameNode = void 0;
      return node && setOriginalNode(preserveJsDoc(node, input), input);
    }
  }
  function transformVariableStatement(input) {
    if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return;
    const nodes = visitNodes2(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration);
    if (!length(nodes)) return;
    const modifiers = factory2.createNodeArray(ensureModifiers(input));
    let declList;
    if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) {
      declList = factory2.createVariableDeclarationList(nodes, 2 /* Const */);
      setOriginalNode(declList, input.declarationList);
      setTextRange(declList, input.declarationList);
      setCommentRange(declList, input.declarationList);
    } else {
      declList = factory2.updateVariableDeclarationList(input.declarationList, nodes);
    }
    return factory2.updateVariableStatement(input, modifiers, declList);
  }
  function recreateBindingPattern(d) {
    return flatten(mapDefined(d.elements, (e) => recreateBindingElement(e)));
  }
  function recreateBindingElement(e) {
    if (e.kind === 232 /* OmittedExpression */) {
      return;
    }
    if (e.name) {
      if (!getBindingNameVisible(e)) return;
      if (isBindingPattern(e.name)) {
        return recreateBindingPattern(e.name);
      } else {
        return factory2.createVariableDeclaration(
          e.name,
          /*exclamationToken*/
          void 0,
          ensureType(e),
          /*initializer*/
          void 0
        );
      }
    }
  }
  function checkName(node) {
    let oldDiag;
    if (!suppressNewDiagnosticContexts) {
      oldDiag = getSymbolAccessibilityDiagnostic;
      getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node);
    }
    errorNameNode = node.name;
    Debug.assert(hasDynamicName(node));
    const decl = node;
    const entityName = decl.name.expression;
    checkEntityNameVisibility(entityName, enclosingDeclaration);
    if (!suppressNewDiagnosticContexts) {
      getSymbolAccessibilityDiagnostic = oldDiag;
    }
    errorNameNode = void 0;
  }
  function shouldStripInternal(node) {
    return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
  }
  function isScopeMarker2(node) {
    return isExportAssignment(node) || isExportDeclaration(node);
  }
  function hasScopeMarker2(statements) {
    return some(statements, isScopeMarker2);
  }
  function ensureModifiers(node) {
    const currentFlags = getEffectiveModifierFlags(node);
    const newFlags = ensureModifierFlags(node);
    if (currentFlags === newFlags) {
      return visitArray(node.modifiers, (n) => tryCast(n, isModifier), isModifier);
    }
    return factory2.createModifiersFromModifierFlags(newFlags);
  }
  function ensureModifierFlags(node) {
    let mask = 131071 /* All */ ^ (1 /* Public */ | 1024 /* Async */ | 16 /* Override */);
    let additions = needsDeclare && !isAlwaysType(node) ? 128 /* Ambient */ : 0 /* None */;
    const parentIsFile = node.parent.kind === 307 /* SourceFile */;
    if (!parentIsFile || isBundledEmit && parentIsFile && isExternalModule(node.parent)) {
      mask ^= 128 /* Ambient */;
      additions = 0 /* None */;
    }
    return maskModifierFlags(node, mask, additions);
  }
  function transformHeritageClauses(nodes) {
    return factory2.createNodeArray(filter(
      map(nodes, (clause) => factory2.updateHeritageClause(
        clause,
        visitNodes2(
          factory2.createNodeArray(filter(clause.types, (t) => {
            return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */;
          })),
          visitDeclarationSubtree,
          isExpressionWithTypeArguments
        )
      )),
      (clause) => clause.types && !!clause.types.length
    ));
  }
}
function isAlwaysType(node) {
  if (node.kind === 264 /* InterfaceDeclaration */) {
    return true;
  }
  return false;
}
function maskModifiers(factory2, node, modifierMask, modifierAdditions) {
  return factory2.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
}
function maskModifierFlags(node, modifierMask = 131071 /* All */ ^ 1 /* Public */, modifierAdditions = 0 /* None */) {
  let flags = getEffectiveModifierFlags(node) & modifierMask | modifierAdditions;
  if (flags & 2048 /* Default */ && !(flags & 32 /* Export */)) {
    flags ^= 32 /* Export */;
  }
  if (flags & 2048 /* Default */ && flags & 128 /* Ambient */) {
    flags ^= 128 /* Ambient */;
  }
  return flags;
}
function canHaveLiteralInitializer(node) {
  switch (node.kind) {
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
      return !hasEffectiveModifier(node, 2 /* Private */);
    case 169 /* Parameter */:
    case 260 /* VariableDeclaration */:
      return true;
  }
  return false;
}
function isPreservedDeclarationStatement(node) {
  switch (node.kind) {
    case 262 /* FunctionDeclaration */:
    case 267 /* ModuleDeclaration */:
    case 271 /* ImportEqualsDeclaration */:
    case 264 /* InterfaceDeclaration */:
    case 263 /* ClassDeclaration */:
    case 265 /* TypeAliasDeclaration */:
    case 266 /* EnumDeclaration */:
    case 243 /* VariableStatement */:
    case 272 /* ImportDeclaration */:
    case 278 /* ExportDeclaration */:
    case 277 /* ExportAssignment */:
      return true;
  }
  return false;
}
function isProcessedComponent(node) {
  switch (node.kind) {
    case 180 /* ConstructSignature */:
    case 176 /* Constructor */:
    case 174 /* MethodDeclaration */:
    case 177 /* GetAccessor */:
    case 178 /* SetAccessor */:
    case 172 /* PropertyDeclaration */:
    case 171 /* PropertySignature */:
    case 173 /* MethodSignature */:
    case 179 /* CallSignature */:
    case 181 /* IndexSignature */:
    case 260 /* VariableDeclaration */:
    case 168 /* TypeParameter */:
    case 233 /* ExpressionWithTypeArguments */:
    case 183 /* TypeReference */:
    case 194 /* ConditionalType */:
    case 184 /* FunctionType */:
    case 185 /* ConstructorType */:
    case 205 /* ImportType */:
      return true;
  }
  return false;
}

// src/compiler/transfo