From dcad07ffd29854e2b93a86da0ba197f6eec21698 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 25 Jan 2023 20:14:47 +0000 Subject: [PATCH] Update LKG --- lib/tsc.js | 34 +- lib/tsserver.js | 87 +- lib/tsserverlibrary.d.ts | 2 +- lib/tsserverlibrary.js | 85 +- lib/typescript.d.ts | 2 +- lib/typescript.js | 79 +- lib/typingsInstaller.js | 5661 +++++++++++++++++++++++++++++++++++++- 7 files changed, 5835 insertions(+), 115 deletions(-) diff --git a/lib/tsc.js b/lib/tsc.js index f572475b0eb04..26516cd868574 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -11724,6 +11724,20 @@ function getScriptTargetFeatures() { BigUint64Array: ["at"], ObjectConstructor: ["hasOwn"], Error: ["cause"] + }, + es2023: { + Array: ["findLastIndex", "findLast"], + Int8Array: ["findLastIndex", "findLast"], + Uint8Array: ["findLastIndex", "findLast"], + Uint8ClampedArray: ["findLastIndex", "findLast"], + Int16Array: ["findLastIndex", "findLast"], + Uint16Array: ["findLastIndex", "findLast"], + Int32Array: ["findLastIndex", "findLast"], + Uint32Array: ["findLastIndex", "findLast"], + Float32Array: ["findLastIndex", "findLast"], + Float64Array: ["findLastIndex", "findLast"], + BigInt64Array: ["findLastIndex", "findLast"], + BigUint64Array: ["findLastIndex", "findLast"] } }; } @@ -46308,7 +46322,7 @@ function createTypeChecker(host) { return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); - const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinter({ removeComments: true, neverAsciiEscape: true }) : createPrinter({ removeComments: true }); + const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -46330,7 +46344,7 @@ function createTypeChecker(host) { sigOutput = kind === 1 /* Construct */ ? 177 /* ConstructSignature */ : 176 /* CallSignature */; } const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -46347,8 +46361,7 @@ function createTypeChecker(host) { const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); if (typeNode === void 0) return Debug.fail("should always get typenode"); - const options = { removeComments: type !== unresolvedType }; - const printer = createPrinter(options); + const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -49699,7 +49712,7 @@ function createTypeChecker(host) { typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217 ); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -64727,7 +64740,7 @@ function createTypeChecker(host) { return getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { - return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 295 /* CatchClause */ || node2.kind === 169 /* PropertyDeclaration */); + return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 169 /* PropertyDeclaration */); } function isSymbolAssigned(symbol) { if (!symbol.valueDeclaration) { @@ -64988,14 +65001,13 @@ function createTypeChecker(host) { const isParameter2 = getRootDeclaration(declaration).kind === 166 /* Parameter */; const declarationContainer = getControlFlowContainer(declaration); let flowContainer = getControlFlowContainer(node); - const isCatch = flowContainer.kind === 295 /* CatchClause */; const isOuterVariable = flowContainer !== declarationContainer; const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); const isModuleExports = symbol.flags & 134217728 /* ModuleExports */; while (flowContainer !== declarationContainer && (flowContainer.kind === 215 /* FunctionExpression */ || flowContainer.kind === 216 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter2 && !isSymbolAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - const assumeInitialized = isParameter2 || isCatch || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; + const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; const initialType = assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer); if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { @@ -78255,7 +78267,7 @@ function createTypeChecker(host) { if (typeAnnotationNode) { checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); } - const isIllegalExportDefaultInCJS = !node.isExportEquals && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 16777216 /* Ambient */) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); if (node.expression.kind === 79 /* Identifier */) { const id = node.expression; const sym = resolveEntityName( @@ -106274,6 +106286,10 @@ function emitUsingBuildInfoWorker(config, host, getCommandLine, customTransforme ); return outputFiles; } +var createPrinterWithDefaults = memoize(() => createPrinter({})); +var createPrinterWithRemoveComments = memoize(() => createPrinter({ removeComments: true })); +var createPrinterWithRemoveCommentsNeverAsciiEscape = memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); +var createPrinterWithRemoveCommentsOmitTrailingSemicolon = memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); function createPrinter(printerOptions = {}, handlers = {}) { const { hasGlobalName, diff --git a/lib/tsserver.js b/lib/tsserver.js index ec5cf96a87517..31db324c0bdd3 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -429,6 +429,10 @@ __export(server_exports, { createPatternMatcher: () => createPatternMatcher, createPrependNodes: () => createPrependNodes, createPrinter: () => createPrinter, + createPrinterWithDefaults: () => createPrinterWithDefaults, + createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, createProgram: () => createProgram, createProgramHost: () => createProgramHost, createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, @@ -15492,6 +15496,20 @@ function getScriptTargetFeatures() { BigUint64Array: ["at"], ObjectConstructor: ["hasOwn"], Error: ["cause"] + }, + es2023: { + Array: ["findLastIndex", "findLast"], + Int8Array: ["findLastIndex", "findLast"], + Uint8Array: ["findLastIndex", "findLast"], + Uint8ClampedArray: ["findLastIndex", "findLast"], + Int16Array: ["findLastIndex", "findLast"], + Uint16Array: ["findLastIndex", "findLast"], + Int32Array: ["findLastIndex", "findLast"], + Uint32Array: ["findLastIndex", "findLast"], + Float32Array: ["findLastIndex", "findLast"], + Float64Array: ["findLastIndex", "findLast"], + BigInt64Array: ["findLastIndex", "findLast"], + BigUint64Array: ["findLastIndex", "findLast"] } }; } @@ -50977,7 +50995,7 @@ function createTypeChecker(host) { return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); - const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinter({ removeComments: true, neverAsciiEscape: true }) : createPrinter({ removeComments: true }); + const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -50999,7 +51017,7 @@ function createTypeChecker(host) { sigOutput = kind === 1 /* Construct */ ? 177 /* ConstructSignature */ : 176 /* CallSignature */; } const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -51016,8 +51034,7 @@ function createTypeChecker(host) { const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); if (typeNode === void 0) return Debug.fail("should always get typenode"); - const options = { removeComments: type !== unresolvedType }; - const printer = createPrinter(options); + const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -54368,7 +54385,7 @@ function createTypeChecker(host) { typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217 ); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -69396,7 +69413,7 @@ function createTypeChecker(host) { return getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { - return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 295 /* CatchClause */ || node2.kind === 169 /* PropertyDeclaration */); + return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 169 /* PropertyDeclaration */); } function isSymbolAssigned(symbol) { if (!symbol.valueDeclaration) { @@ -69657,14 +69674,13 @@ function createTypeChecker(host) { const isParameter2 = getRootDeclaration(declaration).kind === 166 /* Parameter */; const declarationContainer = getControlFlowContainer(declaration); let flowContainer = getControlFlowContainer(node); - const isCatch = flowContainer.kind === 295 /* CatchClause */; const isOuterVariable = flowContainer !== declarationContainer; const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); const isModuleExports = symbol.flags & 134217728 /* ModuleExports */; while (flowContainer !== declarationContainer && (flowContainer.kind === 215 /* FunctionExpression */ || flowContainer.kind === 216 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter2 && !isSymbolAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - const assumeInitialized = isParameter2 || isCatch || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; + const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; const initialType = assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer); if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { @@ -82924,7 +82940,7 @@ function createTypeChecker(host) { if (typeAnnotationNode) { checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); } - const isIllegalExportDefaultInCJS = !node.isExportEquals && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 16777216 /* Ambient */) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); if (node.expression.kind === 79 /* Identifier */) { const id = node.expression; const sym = resolveEntityName( @@ -111125,6 +111141,10 @@ function emitUsingBuildInfoWorker(config, host, getCommandLine, customTransforme ); return outputFiles; } +var createPrinterWithDefaults = memoize(() => createPrinter({})); +var createPrinterWithRemoveComments = memoize(() => createPrinter({ removeComments: true })); +var createPrinterWithRemoveCommentsNeverAsciiEscape = memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); +var createPrinterWithRemoveCommentsOmitTrailingSemicolon = memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); function createPrinter(printerOptions = {}, handlers = {}) { const { hasGlobalName, @@ -126912,6 +126932,10 @@ __export(ts_exports3, { createPatternMatcher: () => createPatternMatcher, createPrependNodes: () => createPrependNodes, createPrinter: () => createPrinter, + createPrinterWithDefaults: () => createPrinterWithDefaults, + createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, createProgram: () => createProgram, createProgramHost: () => createProgramHost, createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, @@ -131004,7 +131028,7 @@ function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, f function nodeToDisplayParts(node, enclosingDeclaration) { const file = enclosingDeclaration.getSourceFile(); return mapToDisplayParts((writer) => { - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); printer.writeNode(4 /* Unspecified */, node, file, writer); }); } @@ -137389,12 +137413,9 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h Debug.assertEqual(action.type, "install package"); return host.installPackage ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition2(fileName, position, options) { - return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost( - host, - /*formatSettings*/ - void 0 - ), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); + function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) { + const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0; + return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { if (openingBrace === 60 /* lessThan */) { @@ -138575,10 +138596,10 @@ var LanguageServiceShimObject = class extends ShimBase { } ); } - getDocCommentTemplateAtPosition(fileName, position, options) { + getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) { return this.forwardJSONCall( `getDocCommentTemplateAtPosition('${fileName}', ${position})`, - () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options) + () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) ); } /// NAVIGATE TO @@ -139470,7 +139491,7 @@ function getCallHierarchyItemName(program, node) { } } if (text === void 0) { - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); text = usingSingleLineStringWriter((writer) => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer)); } return { text, pos: declName.getStart(), end: declName.getEnd() }; @@ -146192,7 +146213,7 @@ function getDeleteAction(context, { name, jsDocHost, jsDocParameterTag }) { Diagnostics.Delete_all_unused_param_tags ); } -function getRenameAction(context, { name, signature, jsDocParameterTag }) { +function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) { if (!length(signature.parameters)) return void 0; const sourceFile = context.sourceFile; @@ -146215,7 +146236,7 @@ function getRenameAction(context, { name, signature, jsDocParameterTag }) { jsDocParameterTag.isNameFirst, jsDocParameterTag.comment ); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, signature, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); } function getInfo10(sourceFile, pos) { @@ -157240,8 +157261,7 @@ function provideInlayHints(context) { } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - const options = { removeComments: true }; - const printer = createPrinter(options); + const printer = createPrinterWithRemoveComments(); return usingSingleLineStringWriter((writer) => { const typeNode = checker.typeToTypeNode( type, @@ -157331,6 +157351,8 @@ var jsDocTagNames = [ "lends", "license", "link", + "linkcode", + "linkplain", "listens", "member", "memberof", @@ -157343,6 +157365,7 @@ var jsDocTagNames = [ "package", "param", "private", + "prop", "property", "protected", "public", @@ -164169,7 +164192,7 @@ function createTypeHelpItems(symbol, { argumentCount, argumentsSpan: applicableS } function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { const typeSymbolDisplay = symbolToDisplayParts(checker, symbol); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const parameters = typeParameters.map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const documentation = symbol.getDocumentationComment(checker); const tags = symbol.getJsDocTags(checker); @@ -164213,7 +164236,7 @@ function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, chec } function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { const typeParameters = (candidateSignature.target || candidateSignature).typeParameters; - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const parameters = (typeParameters || emptyArray).map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; return checker.getExpandedParameters(candidateSignature).map((paramList) => { @@ -164225,7 +164248,7 @@ function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclara }); } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const typeParameterParts = mapToDisplayParts((writer) => { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { const args = factory.createNodeArray(candidateSignature.typeParameters.map((p) => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags))); @@ -164600,7 +164623,6 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so let hasAddedSymbolInfo = false; const isThisExpression = location.kind === 108 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); let type; - let printer; let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; @@ -164993,10 +165015,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so } return { displayParts, documentation, symbolKind, tags: tags.length === 0 ? void 0 : tags }; function getPrinter() { - if (!printer) { - printer = createPrinter({ removeComments: true }); - } - return printer; + return createPrinterWithRemoveComments(); } function prefixNextMeaning() { if (displayParts.length) { @@ -178153,7 +178172,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter getDocCommentTemplate(args) { const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file)); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file)); } getSpanOfEnclosingComment(args) { const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); @@ -181076,6 +181095,10 @@ start(initializeNodeSystem(), require("os").platform()); createPatternMatcher, createPrependNodes, createPrinter, + createPrinterWithDefaults, + createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon, createProgram, createProgramHost, createPropertyNameNodeForIdentifierOrLiteral, diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index d37896300e8f8..65f9a35b41dc6 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -9990,7 +9990,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions, formatOptions?: FormatCodeSettings): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 11d554ba63f83..f16c5a06498a0 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -13247,6 +13247,20 @@ ${lanes.join("\n")} BigUint64Array: ["at"], ObjectConstructor: ["hasOwn"], Error: ["cause"] + }, + es2023: { + Array: ["findLastIndex", "findLast"], + Int8Array: ["findLastIndex", "findLast"], + Uint8Array: ["findLastIndex", "findLast"], + Uint8ClampedArray: ["findLastIndex", "findLast"], + Int16Array: ["findLastIndex", "findLast"], + Uint16Array: ["findLastIndex", "findLast"], + Int32Array: ["findLastIndex", "findLast"], + Uint32Array: ["findLastIndex", "findLast"], + Float32Array: ["findLastIndex", "findLast"], + Float64Array: ["findLastIndex", "findLast"], + BigInt64Array: ["findLastIndex", "findLast"], + BigUint64Array: ["findLastIndex", "findLast"] } }; } @@ -48708,7 +48722,7 @@ ${lanes.join("\n")} return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); - const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinter({ removeComments: true, neverAsciiEscape: true }) : createPrinter({ removeComments: true }); + const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -48730,7 +48744,7 @@ ${lanes.join("\n")} sigOutput = kind === 1 /* Construct */ ? 177 /* ConstructSignature */ : 176 /* CallSignature */; } const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -48747,8 +48761,7 @@ ${lanes.join("\n")} const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); if (typeNode === void 0) return Debug.fail("should always get typenode"); - const options = { removeComments: type !== unresolvedType }; - const printer = createPrinter(options); + const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -52099,7 +52112,7 @@ ${lanes.join("\n")} typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217 ); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -67127,7 +67140,7 @@ ${lanes.join("\n")} return getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { - return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 295 /* CatchClause */ || node2.kind === 169 /* PropertyDeclaration */); + return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 169 /* PropertyDeclaration */); } function isSymbolAssigned(symbol) { if (!symbol.valueDeclaration) { @@ -67388,14 +67401,13 @@ ${lanes.join("\n")} const isParameter2 = getRootDeclaration(declaration).kind === 166 /* Parameter */; const declarationContainer = getControlFlowContainer(declaration); let flowContainer = getControlFlowContainer(node); - const isCatch = flowContainer.kind === 295 /* CatchClause */; const isOuterVariable = flowContainer !== declarationContainer; const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); const isModuleExports = symbol.flags & 134217728 /* ModuleExports */; while (flowContainer !== declarationContainer && (flowContainer.kind === 215 /* FunctionExpression */ || flowContainer.kind === 216 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter2 && !isSymbolAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - const assumeInitialized = isParameter2 || isCatch || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; + const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; const initialType = assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer); if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { @@ -80655,7 +80667,7 @@ ${lanes.join("\n")} if (typeAnnotationNode) { checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); } - const isIllegalExportDefaultInCJS = !node.isExportEquals && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 16777216 /* Ambient */) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); if (node.expression.kind === 79 /* Identifier */) { const id = node.expression; const sym = resolveEntityName( @@ -113784,7 +113796,7 @@ ${lanes.join("\n")} function getEmitListItem(emit, parenthesizerRule) { return emit.length === 1 ? emitListItemNoParenthesizer : typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector : emitListItemWithParenthesizerRule; } - var brackets, notImplementedResolver, TempFlags; + var brackets, notImplementedResolver, createPrinterWithDefaults, createPrinterWithRemoveComments, createPrinterWithRemoveCommentsNeverAsciiEscape, createPrinterWithRemoveCommentsOmitTrailingSemicolon, TempFlags; var init_emitter = __esm({ "src/compiler/emitter.ts"() { "use strict"; @@ -113835,6 +113847,10 @@ ${lanes.join("\n")} getDeclarationStatementsForSourceFile: notImplemented, isImportRequiredByAugmentation: notImplemented }; + createPrinterWithDefaults = memoize(() => createPrinter({})); + createPrinterWithRemoveComments = memoize(() => createPrinter({ removeComments: true })); + createPrinterWithRemoveCommentsNeverAsciiEscape = memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); + createPrinterWithRemoveCommentsOmitTrailingSemicolon = memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); TempFlags = /* @__PURE__ */ ((TempFlags2) => { TempFlags2[TempFlags2["Auto"] = 0] = "Auto"; TempFlags2[TempFlags2["CountMask"] = 268435455] = "CountMask"; @@ -126889,7 +126905,7 @@ ${lanes.join("\n")} function nodeToDisplayParts(node, enclosingDeclaration) { const file = enclosingDeclaration.getSourceFile(); return mapToDisplayParts((writer) => { - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); printer.writeNode(4 /* Unspecified */, node, file, writer); }); } @@ -132743,12 +132759,9 @@ ${lanes.join("\n")} Debug.assertEqual(action.type, "install package"); return host.installPackage ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition2(fileName, position, options) { - return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost( - host, - /*formatSettings*/ - void 0 - ), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); + function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) { + const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0; + return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { if (openingBrace === 60 /* lessThan */) { @@ -134620,10 +134633,10 @@ ${lanes.join("\n")} } ); } - getDocCommentTemplateAtPosition(fileName, position, options) { + getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) { return this.forwardJSONCall( `getDocCommentTemplateAtPosition('${fileName}', ${position})`, - () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options) + () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) ); } /// NAVIGATE TO @@ -135517,7 +135530,7 @@ ${lanes.join("\n")} } } if (text === void 0) { - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); text = usingSingleLineStringWriter((writer) => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer)); } return { text, pos: declName.getStart(), end: declName.getEnd() }; @@ -142522,7 +142535,7 @@ ${lanes.join("\n")} Diagnostics.Delete_all_unused_param_tags ); } - function getRenameAction(context, { name, signature, jsDocParameterTag }) { + function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) { if (!length(signature.parameters)) return void 0; const sourceFile = context.sourceFile; @@ -142545,7 +142558,7 @@ ${lanes.join("\n")} jsDocParameterTag.isNameFirst, jsDocParameterTag.comment ); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, signature, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); } function getInfo10(sourceFile, pos) { @@ -153998,8 +154011,7 @@ ${lanes.join("\n")} } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - const options = { removeComments: true }; - const printer = createPrinter(options); + const printer = createPrinterWithRemoveComments(); return usingSingleLineStringWriter((writer) => { const typeNode = checker.typeToTypeNode( type, @@ -154415,6 +154427,8 @@ ${lanes.join("\n")} "lends", "license", "link", + "linkcode", + "linkplain", "listens", "member", "memberof", @@ -154427,6 +154441,7 @@ ${lanes.join("\n")} "package", "param", "private", + "prop", "property", "protected", "public", @@ -161171,7 +161186,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { const typeSymbolDisplay = symbolToDisplayParts(checker, symbol); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const parameters = typeParameters.map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const documentation = symbol.getDocumentationComment(checker); const tags = symbol.getJsDocTags(checker); @@ -161214,7 +161229,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { const typeParameters = (candidateSignature.target || candidateSignature).typeParameters; - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const parameters = (typeParameters || emptyArray).map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; return checker.getExpandedParameters(candidateSignature).map((paramList) => { @@ -161226,7 +161241,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const typeParameterParts = mapToDisplayParts((writer) => { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { const args = factory.createNodeArray(candidateSignature.typeParameters.map((p) => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags))); @@ -161632,7 +161647,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let hasAddedSymbolInfo = false; const isThisExpression = location.kind === 108 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); let type; - let printer; let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; @@ -162025,10 +162039,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return { displayParts, documentation, symbolKind, tags: tags.length === 0 ? void 0 : tags }; function getPrinter() { - if (!printer) { - printer = createPrinter({ removeComments: true }); - } - return printer; + return createPrinterWithRemoveComments(); } function prefixNextMeaning() { if (displayParts.length) { @@ -175499,7 +175510,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter getDocCommentTemplate(args) { const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file)); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file)); } getSpanOfEnclosingComment(args) { const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); @@ -177735,6 +177746,10 @@ ${e.message}`; createPatternMatcher: () => createPatternMatcher, createPrependNodes: () => createPrependNodes, createPrinter: () => createPrinter, + createPrinterWithDefaults: () => createPrinterWithDefaults, + createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, createProgram: () => createProgram, createProgramHost: () => createProgramHost, createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, @@ -180087,6 +180102,10 @@ ${e.message}`; createPatternMatcher: () => createPatternMatcher, createPrependNodes: () => createPrependNodes, createPrinter: () => createPrinter, + createPrinterWithDefaults: () => createPrinterWithDefaults, + createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, createProgram: () => createProgram, createProgramHost: () => createProgramHost, createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index c9eeb8a00a1a5..e973a18179380 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -6088,7 +6088,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions, formatOptions?: FormatCodeSettings): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. diff --git a/lib/typescript.js b/lib/typescript.js index 6a3f7a4f37324..cdd6065a75b05 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -13247,6 +13247,20 @@ ${lanes.join("\n")} BigUint64Array: ["at"], ObjectConstructor: ["hasOwn"], Error: ["cause"] + }, + es2023: { + Array: ["findLastIndex", "findLast"], + Int8Array: ["findLastIndex", "findLast"], + Uint8Array: ["findLastIndex", "findLast"], + Uint8ClampedArray: ["findLastIndex", "findLast"], + Int16Array: ["findLastIndex", "findLast"], + Uint16Array: ["findLastIndex", "findLast"], + Int32Array: ["findLastIndex", "findLast"], + Uint32Array: ["findLastIndex", "findLast"], + Float32Array: ["findLastIndex", "findLast"], + Float64Array: ["findLastIndex", "findLast"], + BigInt64Array: ["findLastIndex", "findLast"], + BigUint64Array: ["findLastIndex", "findLast"] } }; } @@ -48708,7 +48722,7 @@ ${lanes.join("\n")} return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); - const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinter({ removeComments: true, neverAsciiEscape: true }) : createPrinter({ removeComments: true }); + const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 308 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -48730,7 +48744,7 @@ ${lanes.join("\n")} sigOutput = kind === 1 /* Construct */ ? 177 /* ConstructSignature */ : 176 /* CallSignature */; } const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -48747,8 +48761,7 @@ ${lanes.join("\n")} const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); if (typeNode === void 0) return Debug.fail("should always get typenode"); - const options = { removeComments: type !== unresolvedType }; - const printer = createPrinter(options); + const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -52099,7 +52112,7 @@ ${lanes.join("\n")} typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217 ); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( 4 /* Unspecified */, @@ -67127,7 +67140,7 @@ ${lanes.join("\n")} return getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { - return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 295 /* CatchClause */ || node2.kind === 169 /* PropertyDeclaration */); + return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 265 /* ModuleBlock */ || node2.kind === 308 /* SourceFile */ || node2.kind === 169 /* PropertyDeclaration */); } function isSymbolAssigned(symbol) { if (!symbol.valueDeclaration) { @@ -67388,14 +67401,13 @@ ${lanes.join("\n")} const isParameter2 = getRootDeclaration(declaration).kind === 166 /* Parameter */; const declarationContainer = getControlFlowContainer(declaration); let flowContainer = getControlFlowContainer(node); - const isCatch = flowContainer.kind === 295 /* CatchClause */; const isOuterVariable = flowContainer !== declarationContainer; const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); const isModuleExports = symbol.flags & 134217728 /* ModuleExports */; while (flowContainer !== declarationContainer && (flowContainer.kind === 215 /* FunctionExpression */ || flowContainer.kind === 216 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter2 && !isSymbolAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - const assumeInitialized = isParameter2 || isCatch || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; + const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 278 /* ExportSpecifier */) || node.parent.kind === 232 /* NonNullExpression */ || declaration.kind === 257 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 16777216 /* Ambient */; const initialType = assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer); if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { @@ -80655,7 +80667,7 @@ ${lanes.join("\n")} if (typeAnnotationNode) { checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); } - const isIllegalExportDefaultInCJS = !node.isExportEquals && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 16777216 /* Ambient */) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); if (node.expression.kind === 79 /* Identifier */) { const id = node.expression; const sym = resolveEntityName( @@ -113784,7 +113796,7 @@ ${lanes.join("\n")} function getEmitListItem(emit, parenthesizerRule) { return emit.length === 1 ? emitListItemNoParenthesizer : typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector : emitListItemWithParenthesizerRule; } - var brackets, notImplementedResolver, TempFlags; + var brackets, notImplementedResolver, createPrinterWithDefaults, createPrinterWithRemoveComments, createPrinterWithRemoveCommentsNeverAsciiEscape, createPrinterWithRemoveCommentsOmitTrailingSemicolon, TempFlags; var init_emitter = __esm({ "src/compiler/emitter.ts"() { "use strict"; @@ -113835,6 +113847,10 @@ ${lanes.join("\n")} getDeclarationStatementsForSourceFile: notImplemented, isImportRequiredByAugmentation: notImplemented }; + createPrinterWithDefaults = memoize(() => createPrinter({})); + createPrinterWithRemoveComments = memoize(() => createPrinter({ removeComments: true })); + createPrinterWithRemoveCommentsNeverAsciiEscape = memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); + createPrinterWithRemoveCommentsOmitTrailingSemicolon = memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); TempFlags = /* @__PURE__ */ ((TempFlags2) => { TempFlags2[TempFlags2["Auto"] = 0] = "Auto"; TempFlags2[TempFlags2["CountMask"] = 268435455] = "CountMask"; @@ -126903,7 +126919,7 @@ ${lanes.join("\n")} function nodeToDisplayParts(node, enclosingDeclaration) { const file = enclosingDeclaration.getSourceFile(); return mapToDisplayParts((writer) => { - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); printer.writeNode(4 /* Unspecified */, node, file, writer); }); } @@ -132757,12 +132773,9 @@ ${lanes.join("\n")} Debug.assertEqual(action.type, "install package"); return host.installPackage ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition2(fileName, position, options) { - return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost( - host, - /*formatSettings*/ - void 0 - ), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); + function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) { + const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0; + return ts_JsDoc_exports.getDocCommentTemplateAtPosition(getNewLineOrDefaultFromHost(host, formatSettings), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { if (openingBrace === 60 /* lessThan */) { @@ -134634,10 +134647,10 @@ ${lanes.join("\n")} } ); } - getDocCommentTemplateAtPosition(fileName, position, options) { + getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) { return this.forwardJSONCall( `getDocCommentTemplateAtPosition('${fileName}', ${position})`, - () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options) + () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) ); } /// NAVIGATE TO @@ -135531,7 +135544,7 @@ ${lanes.join("\n")} } } if (text === void 0) { - const printer = createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); text = usingSingleLineStringWriter((writer) => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer)); } return { text, pos: declName.getStart(), end: declName.getEnd() }; @@ -142536,7 +142549,7 @@ ${lanes.join("\n")} Diagnostics.Delete_all_unused_param_tags ); } - function getRenameAction(context, { name, signature, jsDocParameterTag }) { + function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) { if (!length(signature.parameters)) return void 0; const sourceFile = context.sourceFile; @@ -142559,7 +142572,7 @@ ${lanes.join("\n")} jsDocParameterTag.isNameFirst, jsDocParameterTag.comment ); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, signature, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); } function getInfo10(sourceFile, pos) { @@ -154012,8 +154025,7 @@ ${lanes.join("\n")} } function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - const options = { removeComments: true }; - const printer = createPrinter(options); + const printer = createPrinterWithRemoveComments(); return usingSingleLineStringWriter((writer) => { const typeNode = checker.typeToTypeNode( type, @@ -154429,6 +154441,8 @@ ${lanes.join("\n")} "lends", "license", "link", + "linkcode", + "linkplain", "listens", "member", "memberof", @@ -154441,6 +154455,7 @@ ${lanes.join("\n")} "package", "param", "private", + "prop", "property", "protected", "public", @@ -161185,7 +161200,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { const typeSymbolDisplay = symbolToDisplayParts(checker, symbol); - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const parameters = typeParameters.map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const documentation = symbol.getDocumentationComment(checker); const tags = symbol.getJsDocTags(checker); @@ -161228,7 +161243,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { const typeParameters = (candidateSignature.target || candidateSignature).typeParameters; - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const parameters = (typeParameters || emptyArray).map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; return checker.getExpandedParameters(candidateSignature).map((paramList) => { @@ -161240,7 +161255,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - const printer = createPrinter({ removeComments: true }); + const printer = createPrinterWithRemoveComments(); const typeParameterParts = mapToDisplayParts((writer) => { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { const args = factory.createNodeArray(candidateSignature.typeParameters.map((p) => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags))); @@ -161646,7 +161661,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let hasAddedSymbolInfo = false; const isThisExpression = location.kind === 108 /* ThisKeyword */ && isInExpressionContext(location) || isThisInTypeQuery(location); let type; - let printer; let documentationFromAlias; let tagsFromAlias; let hasMultipleSignatures = false; @@ -162039,10 +162053,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return { displayParts, documentation, symbolKind, tags: tags.length === 0 ? void 0 : tags }; function getPrinter() { - if (!printer) { - printer = createPrinter({ removeComments: true }); - } - return printer; + return createPrinterWithRemoveComments(); } function prefixNextMeaning() { if (displayParts.length) { @@ -166920,6 +166931,10 @@ ${options.prefix}` : "\n" : options.prefix createPatternMatcher: () => createPatternMatcher, createPrependNodes: () => createPrependNodes, createPrinter: () => createPrinter, + createPrinterWithDefaults: () => createPrinterWithDefaults, + createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, + createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, + createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, createProgram: () => createProgram, createProgramHost: () => createProgramHost, createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 2b20b45f48052..2d892a7d711e4 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -102,6 +102,17 @@ function find(array, predicate, startIndex) { } return void 0; } +function findLast(array, predicate, startIndex) { + if (array === void 0) + return void 0; + for (let i = startIndex != null ? startIndex : array.length - 1; i >= 0; i--) { + const value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return void 0; +} function findIndex(array, predicate, startIndex) { if (array === void 0) return -1; @@ -473,6 +484,15 @@ function arrayToMap(array, makeKey, makeValue = identity) { } return result; } +function clone(object) { + const result = {}; + for (const id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; +} function createMultiMap() { const map2 = /* @__PURE__ */ new Map(); map2.add = multiMapAdd; @@ -2297,6 +2317,30 @@ var perfLogger = (etwModule == null ? void 0 : etwModule.logEvent) ? etwModule : // src/compiler/performance.ts var performanceImpl; +function createTimerIf(condition, measureName, startMarkName, endMarkName) { + return condition ? createTimer(measureName, startMarkName, endMarkName) : nullTimer; +} +function createTimer(measureName, startMarkName, endMarkName) { + let enterCount = 0; + return { + enter, + exit + }; + function enter() { + if (++enterCount === 1) { + mark(startMarkName); + } + } + function exit() { + if (--enterCount === 0) { + mark(endMarkName); + measure(measureName, startMarkName, endMarkName); + } else if (enterCount < 0) { + Debug.fail("enter/exit count does not match."); + } + } +} +var nullTimer = { enter: noop, exit: noop }; var enabled = false; var timeorigin = timestamp(); var marks = /* @__PURE__ */ new Map(); @@ -3078,6 +3122,19 @@ var RelationComparisonResult = /* @__PURE__ */ ((RelationComparisonResult3) => { RelationComparisonResult3[RelationComparisonResult3["ReportsMask"] = 24] = "ReportsMask"; return RelationComparisonResult3; })(RelationComparisonResult || {}); +var GeneratedIdentifierFlags = /* @__PURE__ */ ((GeneratedIdentifierFlags2) => { + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["None"] = 0] = "None"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Node"] = 4] = "Node"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["KindMask"] = 7] = "KindMask"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["FileLevel"] = 32] = "FileLevel"; + GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["AllowNameSubstitution"] = 64] = "AllowNameSubstitution"; + return GeneratedIdentifierFlags2; +})(GeneratedIdentifierFlags || {}); var FlowFlags = /* @__PURE__ */ ((FlowFlags2) => { FlowFlags2[FlowFlags2["Unreachable"] = 1] = "Unreachable"; FlowFlags2[FlowFlags2["Start"] = 2] = "Start"; @@ -7476,6 +7533,17 @@ function computeLineOfPosition(lineStarts, position, lowerBound) { } return lineNumber; } +function getLinesBetweenPositions(sourceFile, pos1, pos2) { + if (pos1 === pos2) + return 0; + const lineStarts = getLineStarts(sourceFile); + const lower = Math.min(pos1, pos2); + const isNegative = lower === pos2; + const upper = isNegative ? pos1 : pos2; + const lowerLine = computeLineOfPosition(lineStarts, lower); + const upperLine = computeLineOfPosition(lineStarts, upper, lowerLine); + return isNegative ? lowerLine - upperLine : upperLine - lowerLine; +} function getLineAndCharacterOfPosition(sourceFile, position) { return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); } @@ -7730,6 +7798,30 @@ function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { } return accumulator; } +function forEachLeadingCommentRange(text, pos, cb, state) { + return iterateCommentRanges( + /*reduce*/ + false, + text, + pos, + /*trailing*/ + false, + cb, + state + ); +} +function forEachTrailingCommentRange(text, pos, cb, state) { + return iterateCommentRanges( + /*reduce*/ + false, + text, + pos, + /*trailing*/ + true, + cb, + state + ); +} function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { return iterateCommentRanges( /*reduce*/ @@ -9366,6 +9458,17 @@ function getCombinedModifierFlags(node) { function getCombinedNodeFlags(node) { return getCombinedFlags(node, (n) => n.flags); } +function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== void 0) { + node = node.original; + } + } + if (!node || !nodeTest) { + return node; + } + return nodeTest(node) ? node : void 0; +} function findAncestor(node, callback) { while (node) { const result = callback(node); @@ -9664,6 +9767,15 @@ function getJSDocTagsWorker(node, noCache) { function getFirstJSDocTag(node, predicate, noCache) { return find(getJSDocTagsWorker(node, noCache), predicate); } +function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment : comment == null ? void 0 : comment.map((c) => c.kind === 324 /* JSDocText */ ? c.text : formatJSDocLink(c)).join(""); +} +function formatJSDocLink(link) { + const kind = link.kind === 327 /* JSDocLink */ ? "link" : link.kind === 328 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; + const name = link.name ? entityNameToString(link.name) : ""; + const space = link.name && link.text.startsWith("://") ? "" : " "; + return `{@${kind} ${name}${space}${link.text}}`; +} function isMemberName(node) { return node.kind === 79 /* Identifier */ || node.kind === 80 /* PrivateIdentifier */; } @@ -9701,9 +9813,24 @@ function isNonNullChain(node) { function isNamedExportBindings(node) { return node.kind === 277 /* NamespaceExport */ || node.kind === 276 /* NamedExports */; } +function isUnparsedTextLike(node) { + switch (node.kind) { + case 305 /* UnparsedText */: + case 306 /* UnparsedInternalText */: + return true; + default: + return false; + } +} +function isUnparsedNode(node) { + return isUnparsedTextLike(node) || node.kind === 303 /* UnparsedPrologue */ || node.kind === 307 /* UnparsedSyntheticReference */; +} function isNodeKind(kind) { return kind >= 163 /* FirstNode */; } +function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 162 /* LastToken */; +} function isNodeArray(array) { return hasProperty(array, "pos") && hasProperty(array, "end"); } @@ -10167,6 +10294,9 @@ function isCaseOrDefaultClause(node) { function isJSDocNode(node) { return node.kind >= 312 /* FirstJSDocNode */ && node.kind <= 353 /* LastJSDocNode */; } +function isJSDocTag(node) { + return node.kind >= 330 /* FirstJSDocTagNode */ && node.kind <= 353 /* LastJSDocTagNode */; +} function hasJSDocNodes(node) { if (!canHaveJSDoc(node)) return false; @@ -10176,6 +10306,28 @@ function hasJSDocNodes(node) { function hasInitializer(node) { return !!node.initializer; } +var MAX_SMI_X86 = 1073741823; +function guessIndentation(lines) { + let indentation = MAX_SMI_X86; + for (const line of lines) { + if (!line.length) { + continue; + } + let i = 0; + for (; i < line.length && i < indentation; i++) { + if (!isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? void 0 : indentation; +} function isStringLiteralLike(node) { return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */; } @@ -10274,6 +10426,9 @@ function getEndLinePosition(line, sourceFile) { return pos; } } +function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); +} function nodeIsMissing(node) { if (node === void 0) { return true; @@ -10283,6 +10438,16 @@ function nodeIsMissing(node) { function nodeIsPresent(node) { return !nodeIsMissing(node); } +function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { + if (text.charCodeAt(commentPos + 1) === 47 /* slash */ && commentPos + 2 < commentEnd && text.charCodeAt(commentPos + 2) === 47 /* slash */) { + const textSubStr = text.substring(commentPos, commentEnd); + return fullTripleSlashReferencePathRegEx.test(textSubStr) || fullTripleSlashAMDReferencePathRegEx.test(textSubStr) || fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) || defaultLibReferenceRegEx.test(textSubStr) ? true : false; + } + return false; +} +function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && text.charCodeAt(start + 2) === 33 /* exclamation */; +} function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; @@ -10336,6 +10501,65 @@ function getEmitFlags(node) { const emitNode = node.emitNode; return emitNode && emitNode.flags || 0; } +function getInternalEmitFlags(node) { + const emitNode = node.emitNode; + return emitNode && emitNode.internalFlags || 0; +} +function getLiteralText(node, sourceFile, flags) { + var _a2; + if (sourceFile && canUseOriginalText(node, flags)) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + switch (node.kind) { + case 10 /* StringLiteral */: { + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } + } + case 14 /* NoSubstitutionTemplateLiteral */: + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: { + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const rawText = (_a2 = node.rawText) != null ? _a2 : escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); + switch (node.kind) { + case 14 /* NoSubstitutionTemplateLiteral */: + return "`" + rawText + "`"; + case 15 /* TemplateHead */: + return "`" + rawText + "${"; + case 16 /* TemplateMiddle */: + return "}" + rawText + "${"; + case 17 /* TemplateTail */: + return "}" + rawText + "`"; + } + break; + } + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return node.text; + case 13 /* RegularExpressionLiteral */: + if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) { + return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/"); + } + return node.text; + } + return Debug.fail(`Literal kind '${node.kind}' not accounted for.`); +} +function canUseOriginalText(node, flags) { + if (nodeIsSynthesized(node) || !node.parent || flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) { + return false; + } + if (isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) { + return !!(flags & 8 /* AllowNumericSeparator */); + } + return !isBigIntLiteral(node); +} +function makeIdentifierFromModuleName(moduleName) { + return getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); +} function isBlockOrCatchScoped(declaration) { return (getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); } @@ -10418,6 +10642,27 @@ function tryGetTextOfPropertyName(name) { function getTextOfPropertyName(name) { return Debug.checkDefined(tryGetTextOfPropertyName(name)); } +function entityNameToString(name) { + switch (name.kind) { + case 108 /* ThisKeyword */: + return "this"; + case 80 /* PrivateIdentifier */: + case 79 /* Identifier */: + return getFullWidth(name) === 0 ? idText(name) : getTextOfNode(name); + case 163 /* QualifiedName */: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 208 /* PropertyAccessExpression */: + if (isIdentifier(name.name) || isPrivateIdentifier(name.name)) { + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } else { + return Debug.assertNever(name.name); + } + case 314 /* JSDocMemberName */: + return entityNameToString(name.left) + entityNameToString(name.right); + default: + return Debug.assertNever(name); + } +} function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) { const span = getErrorSpanForNode(sourceFile, node); return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); @@ -10521,6 +10766,15 @@ function isJsonSourceFile(file) { function isEnumConst(node) { return !!(getCombinedModifierFlags(node) & 2048 /* Const */); } +function isVarConst(node) { + return !!(getCombinedNodeFlags(node) & 2 /* Const */); +} +function isLet(node) { + return !!(getCombinedNodeFlags(node) & 1 /* Let */); +} +function isLiteralImportTypeNode(n) { + return isImportTypeNode(n) && isLiteralTypeNode(n.argument) && isStringLiteral(n.argument.literal); +} function isPrologueDirective(node) { return node.kind === 241 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */; } @@ -10536,10 +10790,17 @@ function isHoistedVariable(node) { function isHoistedVariableStatement(node) { return isCustomPrologue(node) && isVariableStatement(node) && every(node.declarationList.declarations, isHoistedVariable); } +function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return node.kind !== 11 /* JsxText */ ? getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : void 0; +} function getJSDocCommentRanges(node, text) { const commentRanges = node.kind === 166 /* Parameter */ || node.kind === 165 /* TypeParameter */ || node.kind === 215 /* FunctionExpression */ || node.kind === 216 /* ArrowFunction */ || node.kind === 214 /* ParenthesizedExpression */ || node.kind === 257 /* VariableDeclaration */ || node.kind === 278 /* ExportSpecifier */ ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); return filter(commentRanges, (comment) => text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); } +var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; +var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; +var fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; +var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isVariableLike(node) { if (node) { switch (node.kind) { @@ -10656,6 +10917,9 @@ function isPartOfTypeQuery(node) { function isInJSFile(node) { return !!node && !!(node.flags & 262144 /* JavaScriptFile */); } +function isInJsonFile(node) { + return !!node && !!(node.flags & 67108864 /* JsonFile */); +} function isInJSDoc(node) { return !!node && !!(node.flags & 8388608 /* JSDoc */); } @@ -10902,6 +11166,23 @@ function isFunctionSymbol(symbol) { const decl = symbol.valueDeclaration; return decl.kind === 259 /* FunctionDeclaration */ || isVariableDeclaration(decl) && decl.initializer && isFunctionLike(decl.initializer); } +function getExternalModuleName(node) { + switch (node.kind) { + case 269 /* ImportDeclaration */: + case 275 /* ExportDeclaration */: + return node.moduleSpecifier; + case 268 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 280 /* ExternalModuleReference */ ? node.moduleReference.expression : void 0; + case 202 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : void 0; + case 210 /* CallExpression */: + return node.arguments[0]; + case 264 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : void 0; + default: + return Debug.assertNever(node); + } +} function isJSDocConstructSignature(node) { const param = isJSDocFunctionType(node) ? firstOrUndefined(node.parameters) : void 0; const name = tryCast(param && param.name, isIdentifier); @@ -11130,6 +11411,14 @@ function skipParentheses(node, excludeJSDocTypeAssertions) { const flags = excludeJSDocTypeAssertions ? 1 /* Parentheses */ | 16 /* ExcludeJSDocTypeAssertion */ : 1 /* Parentheses */; return skipOuterExpressions(node, flags); } +function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; +} function isIdentifierName(node) { const parent = node.parent; switch (parent.kind) { @@ -11416,9 +11705,16 @@ function getBinaryOperatorPrecedence(kind) { } return -1; } +var templateSubstitutionRegExp = /\$\{/g; +function escapeTemplateSubstitution(str) { + return str.replace(templateSubstitutionRegExp, "\\${"); +} function hasInvalidEscape(template) { return template && !!(isNoSubstitutionTemplateLiteral(template) ? template.templateFlags : template.head.templateFlags || some(template.templateSpans, (span) => !!span.literal.templateFlags)); } +var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; +var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; +var backtickQuoteEscapedCharsRegExp = /\r\n|[\\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; var escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -11439,10 +11735,231 @@ var escapedCharsMap = new Map(Object.entries({ "\r\n": "\\r\\n" // special case for CRLFs in backticks })); +function encodeUtf16EscapeSequence(charCode) { + const hexCharCode = charCode.toString(16).toUpperCase(); + const paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; +} +function getReplacement(c, offset, input) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + const lookAhead = input.charCodeAt(offset + c.length); + if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) { + return "\\x00"; + } + return "\\0"; + } + return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0)); +} +function escapeString(s, quoteChar) { + const escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getReplacement); +} +var nonAsciiCharacters = /[^\u0000-\u007F]/g; +function escapeNonAsciiString(s, quoteChar) { + s = escapeString(s, quoteChar); + return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, (c) => encodeUtf16EscapeSequence(c.charCodeAt(0))) : s; +} +var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g; +var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g; var jsxEscapedCharsMap = new Map(Object.entries({ '"': """, "'": "'" })); +function encodeJsxCharacterEntity(charCode) { + const hexCharCode = charCode.toString(16).toUpperCase(); + return "&#x" + hexCharCode + ";"; +} +function getJsxAttributeStringReplacement(c) { + if (c.charCodeAt(0) === 0 /* nullCharacter */) { + return "�"; + } + return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0)); +} +function escapeJsxAttributeString(s, quoteChar) { + const escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp : jsxDoubleQuoteEscapedCharsRegExp; + return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement); +} +var indentStrings = ["", " "]; +function getIndentString(level) { + const singleLevel = indentStrings[1]; + for (let current = indentStrings.length; current <= level; current++) { + indentStrings.push(indentStrings[current - 1] + singleLevel); + } + return indentStrings[level]; +} +function getIndentSize() { + return indentStrings[1].length; +} +function createTextWriter(newLine) { + let output; + let indent2; + let lineStart; + let lineCount; + let linePos; + let hasTrailingComment = false; + function updateLineCountAndPosFor(s) { + const lineStartsOfS = computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + last(lineStartsOfS); + lineStart = linePos - output.length === 0; + } else { + lineStart = false; + } + } + function writeText(s) { + if (s && s.length) { + if (lineStart) { + s = getIndentString(indent2) + s; + lineStart = false; + } + output += s; + updateLineCountAndPosFor(s); + } + } + function write(s) { + if (s) + hasTrailingComment = false; + writeText(s); + } + function writeComment(s) { + if (s) + hasTrailingComment = true; + writeText(s); + } + function reset() { + output = ""; + indent2 = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + hasTrailingComment = false; + } + function rawWrite(s) { + if (s !== void 0) { + output += s; + updateLineCountAndPosFor(s); + hasTrailingComment = false; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + } + } + function writeLine(force) { + if (!lineStart || force) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + hasTrailingComment = false; + } + } + function getTextPosWithWriteLine() { + return lineStart ? output.length : output.length + newLine.length; + } + reset(); + return { + write, + rawWrite, + writeLiteral, + writeLine, + increaseIndent: () => { + indent2++; + }, + decreaseIndent: () => { + indent2--; + }, + getIndent: () => indent2, + getTextPos: () => output.length, + getLine: () => lineCount, + getColumn: () => lineStart ? indent2 * getIndentSize() : output.length - linePos, + getText: () => output, + isAtStartOfLine: () => lineStart, + hasTrailingComment: () => hasTrailingComment, + hasTrailingWhitespace: () => !!output.length && isWhiteSpaceLike(output.charCodeAt(output.length - 1)), + clear: reset, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: (s, _) => write(s), + writeTrailingSemicolon: write, + writeComment, + getTextPosWithWriteLine + }; +} +function getTrailingSemicolonDeferringWriter(writer) { + let pendingTrailingSemicolon = false; + function commitPendingTrailingSemicolon() { + if (pendingTrailingSemicolon) { + writer.writeTrailingSemicolon(";"); + pendingTrailingSemicolon = false; + } + } + return { + ...writer, + writeTrailingSemicolon() { + pendingTrailingSemicolon = true; + }, + writeLiteral(s) { + commitPendingTrailingSemicolon(); + writer.writeLiteral(s); + }, + writeStringLiteral(s) { + commitPendingTrailingSemicolon(); + writer.writeStringLiteral(s); + }, + writeSymbol(s, sym) { + commitPendingTrailingSemicolon(); + writer.writeSymbol(s, sym); + }, + writePunctuation(s) { + commitPendingTrailingSemicolon(); + writer.writePunctuation(s); + }, + writeKeyword(s) { + commitPendingTrailingSemicolon(); + writer.writeKeyword(s); + }, + writeOperator(s) { + commitPendingTrailingSemicolon(); + writer.writeOperator(s); + }, + writeParameter(s) { + commitPendingTrailingSemicolon(); + writer.writeParameter(s); + }, + writeSpace(s) { + commitPendingTrailingSemicolon(); + writer.writeSpace(s); + }, + writeProperty(s) { + commitPendingTrailingSemicolon(); + writer.writeProperty(s); + }, + writeComment(s) { + commitPendingTrailingSemicolon(); + writer.writeComment(s); + }, + writeLine() { + commitPendingTrailingSemicolon(); + writer.writeLine(); + }, + increaseIndent() { + commitPendingTrailingSemicolon(); + writer.increaseIndent(); + }, + decreaseIndent() { + commitPendingTrailingSemicolon(); + writer.decreaseIndent(); + } + }; +} function hostUsesCaseSensitiveFileNames(host) { return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; } @@ -11476,12 +11993,156 @@ function writeFileEnsuringDirectories(path2, data, writeByteOrderMark, writeFile writeFile2(path2, data, writeByteOrderMark); } } +function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return computeLineOfPosition(lineMap, pos); +} function isThisIdentifier(node) { return !!node && node.kind === 79 /* Identifier */ && identifierIsThisKeyword(node); } function identifierIsThisKeyword(id) { return id.escapedText === "this"; } +function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); +} +function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } +} +function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } +} +function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.writeSpace(" "); + } + let emitInterveningSeparator = false; + for (const comment of comments) { + if (emitInterveningSeparator) { + writer.writeSpace(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.writeSpace(" "); + } + } +} +function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + let leadingComments; + let currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = filter(getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal); + } + } else { + leadingComments = getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + const detachedComments = []; + let lastComment; + for (const comment of leadingComments) { + if (lastComment) { + const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + const commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, last(detachedComments).end); + const nodeLine = getLineOfLocalPositionFromLineMap(lineMap, skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments( + text, + lineMap, + writer, + detachedComments, + /*leadingSeparator*/ + false, + /*trailingSeparator*/ + true, + newLine, + writeComment + ); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: last(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedCommentLocal(comment) { + return isPinnedComment(text, comment.pos); + } +} +function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) { + const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, commentPos); + const lineCount = lineMap.length; + let firstCommentLineIndent; + for (let pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + const nextLineStart = currentLine + 1 === lineCount ? text.length + 1 : lineMap[currentLine + 1]; + if (pos !== commentPos) { + if (firstCommentLineIndent === void 0) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + const currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + const indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } else { + writer.writeComment(text.substring(commentPos, commentEnd)); + } +} +function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + const end = Math.min(commentEnd, nextLineStart - 1); + const currentLineText = trimString(text.substring(pos, end)); + if (currentLineText) { + writer.writeComment(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } else { + writer.rawWrite(newLine); + } +} +function calculateIndent(text, pos, end) { + let currentLineIndent = 0; + for (; pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + currentLineIndent += getIndentSize() - currentLineIndent % getIndentSize(); + } else { + currentLineIndent++; + } + } + return currentLineIndent; +} function hasSyntacticModifier(node, flags) { return !!getSelectedSyntacticModifierFlags(node, flags); } @@ -11662,6 +12323,118 @@ function readJson(path2, host) { function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } +var carriageReturnLineFeed = "\r\n"; +var lineFeed = "\n"; +function getNewLineCharacter(options) { + switch (options.newLine) { + case 0 /* CarriageReturnLineFeed */: + return carriageReturnLineFeed; + case 1 /* LineFeed */: + case void 0: + return lineFeed; + } +} +function createRange(pos, end = pos) { + Debug.assert(end >= pos || end === -1); + return { pos, end }; +} +function moveRangePos(range, pos) { + return createRange(pos, range.end); +} +function moveRangePastDecorators(node) { + const lastDecorator = canHaveModifiers(node) ? findLast(node.modifiers, isDecorator) : void 0; + return lastDecorator && !positionIsSynthesized(lastDecorator.end) ? moveRangePos(node, lastDecorator.end) : node; +} +function moveRangePastModifiers(node) { + if (isPropertyDeclaration(node) || isMethodDeclaration(node)) { + return moveRangePos(node, node.name.pos); + } + const lastModifier = canHaveModifiers(node) ? lastOrUndefined(node.modifiers) : void 0; + return lastModifier && !positionIsSynthesized(lastModifier.end) ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); +} +function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); +} +function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine( + getStartPositionOfRange( + range1, + sourceFile, + /*includeComments*/ + false + ), + getStartPositionOfRange( + range2, + sourceFile, + /*includeComments*/ + false + ), + sourceFile + ); +} +function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); +} +function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange( + range1, + sourceFile, + /*includeComments*/ + false + ), range2.end, sourceFile); +} +function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange( + range2, + sourceFile, + /*includeComments*/ + false + ), sourceFile); +} +function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) { + const range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments); + return getLinesBetweenPositions(sourceFile, range1.end, range2Start); +} +function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return getLinesBetweenPositions(sourceFile, pos1, pos2) === 0; +} +function getStartPositionOfRange(range, sourceFile, includeComments) { + return positionIsSynthesized(range.pos) ? -1 : skipTrivia( + sourceFile.text, + range.pos, + /*stopAfterLineBreak*/ + false, + includeComments + ); +} +function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { + const startPos = skipTrivia( + sourceFile.text, + pos, + /*stopAfterLineBreak*/ + false, + includeComments + ); + const prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return getLinesBetweenPositions(sourceFile, prevPos != null ? prevPos : stopPos, startPos); +} +function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { + const nextPos = skipTrivia( + sourceFile.text, + pos, + /*stopAfterLineBreak*/ + false, + includeComments + ); + return getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); +} +function getPreviousNonWhitespacePosition(pos, stopPos = 0, sourceFile) { + while (pos-- > stopPos) { + if (!isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } +} function closeFileWatcher(watcher) { watcher.close(); } @@ -11694,6 +12467,15 @@ function isTypeNodeKind(kind) { function isAccessExpression(node) { return node.kind === 208 /* PropertyAccessExpression */ || node.kind === 209 /* ElementAccessExpression */; } +function isBundleFileTextLike(section) { + switch (section.kind) { + case "text" /* Text */: + case "internal" /* Internal */: + return true; + default: + return false; + } +} function getLeftmostAccessExpression(expr) { while (isAccessExpression(expr)) { expr = expr.expression; @@ -12369,6 +13151,71 @@ function setParentRecursive(rootNode, incremental) { return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child); } } +function getContainingNodeArray(node) { + if (!node.parent) + return void 0; + switch (node.kind) { + case 165 /* TypeParameter */: + const { parent: parent2 } = node; + return parent2.kind === 192 /* InferType */ ? void 0 : parent2.typeParameters; + case 166 /* Parameter */: + return node.parent.parameters; + case 201 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 236 /* TemplateSpan */: + return node.parent.templateSpans; + case 167 /* Decorator */: { + const { parent: parent3 } = node; + return canHaveDecorators(parent3) ? parent3.modifiers : void 0; + } + case 294 /* HeritageClause */: + return node.parent.heritageClauses; + } + const { parent } = node; + if (isJSDocTag(node)) { + return isJSDocTypeLiteral(node.parent) ? void 0 : node.parent.tags; + } + switch (parent.kind) { + case 184 /* TypeLiteral */: + case 261 /* InterfaceDeclaration */: + return isTypeElement(node) ? parent.members : void 0; + case 189 /* UnionType */: + case 190 /* IntersectionType */: + return parent.types; + case 186 /* TupleType */: + case 206 /* ArrayLiteralExpression */: + case 357 /* CommaListExpression */: + case 272 /* NamedImports */: + case 276 /* NamedExports */: + return parent.elements; + case 207 /* ObjectLiteralExpression */: + case 289 /* JsxAttributes */: + return parent.properties; + case 210 /* CallExpression */: + case 211 /* NewExpression */: + return isTypeNode(node) ? parent.typeArguments : parent.expression === node ? void 0 : parent.arguments; + case 281 /* JsxElement */: + case 285 /* JsxFragment */: + return isJsxChild(node) ? parent.children : void 0; + case 283 /* JsxOpeningElement */: + case 282 /* JsxSelfClosingElement */: + return isTypeNode(node) ? parent.typeArguments : void 0; + case 238 /* Block */: + case 292 /* CaseClause */: + case 293 /* DefaultClause */: + case 265 /* ModuleBlock */: + return parent.statements; + case 266 /* CaseBlock */: + return parent.clauses; + case 260 /* ClassDeclaration */: + case 228 /* ClassExpression */: + return isClassElement(node) ? parent.members : void 0; + case 263 /* EnumDeclaration */: + return isEnumMember(node) ? parent.members : void 0; + case 308 /* SourceFile */: + return parent.statements; + } +} // src/compiler/factory/baseNodeFactory.ts function createBaseNodeFactory() { @@ -17452,6 +18299,22 @@ function getSyntheticTrailingComments(node) { var _a2; return (_a2 = node.emitNode) == null ? void 0 : _a2.trailingComments; } +function getConstantValue(node) { + var _a2; + return (_a2 = node.emitNode) == null ? void 0 : _a2.constantValue; +} +function getEmitHelpers(node) { + var _a2; + return (_a2 = node.emitNode) == null ? void 0 : _a2.helpers; +} +function getSnippetElement(node) { + var _a2; + return (_a2 = node.emitNode) == null ? void 0 : _a2.snippetElement; +} +function getTypeNode(node) { + var _a2; + return (_a2 = node.emitNode) == null ? void 0 : _a2.typeNode; +} function setIdentifierTypeArguments(node, typeArguments) { getOrCreateEmitNode(node).identifierTypeArguments = typeArguments; return node; @@ -17466,6 +18329,17 @@ function setIdentifierAutoGenerate(node, autoGenerate) { } // src/compiler/factory/emitHelpers.ts +function compareEmitHelpers(x, y) { + if (x === y) + return 0 /* EqualTo */; + if (x.priority === y.priority) + return 0 /* EqualTo */; + if (x.priority === void 0) + return 1 /* GreaterThan */; + if (y.priority === void 0) + return -1 /* LessThan */; + return compareValues(x.priority, y.priority); +} function helperString(input, ...args) { return (uniqueName) => { let result = ""; @@ -17749,6 +18623,9 @@ function isNonNullExpression(node) { function isMetaProperty(node) { return node.kind === 233 /* MetaProperty */; } +function isPartiallyEmittedExpression(node) { + return node.kind === 356 /* PartiallyEmittedExpression */; +} function isCommaListExpression(node) { return node.kind === 357 /* CommaListExpression */; } @@ -17761,6 +18638,9 @@ function isBlock(node) { function isVariableStatement(node) { return node.kind === 240 /* VariableStatement */; } +function isEmptyStatement(node) { + return node.kind === 239 /* EmptyStatement */; +} function isExpressionStatement(node) { return node.kind === 241 /* ExpressionStatement */; } @@ -17869,9 +18749,15 @@ function isShorthandPropertyAssignment(node) { function isEnumMember(node) { return node.kind === 302 /* EnumMember */; } +function isUnparsedPrepend(node) { + return node.kind === 304 /* UnparsedPrepend */; +} function isSourceFile(node) { return node.kind === 308 /* SourceFile */; } +function isUnparsedSource(node) { + return node.kind === 310 /* UnparsedSource */; +} function isJSDocTypeExpression(node) { return node.kind === 312 /* JSDocTypeExpression */; } @@ -17884,6 +18770,9 @@ function isJSDocFunctionType(node) { function isJSDoc(node) { return node.kind === 323 /* JSDoc */; } +function isJSDocTypeLiteral(node) { + return node.kind === 325 /* JSDocTypeLiteral */; +} function isJSDocPublicTag(node) { return node.kind === 336 /* JSDocPublicTag */; } @@ -17981,6 +18870,16 @@ function startOnNewLine(node) { true ); } +function getExternalHelpersModuleName(node) { + const parseNode = getOriginalNode(node, isSourceFile); + const emitNode = parseNode && parseNode.emitNode; + return emitNode && emitNode.externalHelpersModuleName; +} +function hasRecordedExternalHelpers(sourceFile) { + const parseNode = getOriginalNode(sourceFile, isSourceFile); + const emitNode = parseNode && parseNode.emitNode; + return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers); +} function getTargetOfBindingOrAssignmentElement(bindingElement) { if (isDeclarationBindingElement(bindingElement)) { return bindingElement.name; @@ -18225,6 +19124,25 @@ function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, return resultHolder.value; } } +function getNodeForGeneratedName(name) { + var _a2; + const autoGenerate = name.emitNode.autoGenerate; + if (autoGenerate.flags & 4 /* Node */) { + const autoGenerateId = autoGenerate.id; + let node = name; + let original = node.original; + while (original) { + node = original; + const autoGenerate2 = (_a2 = node.emitNode) == null ? void 0 : _a2.autoGenerate; + if (isMemberName(node) && (autoGenerate2 === void 0 || !!(autoGenerate2.flags & 4 /* Node */) && autoGenerate2.id !== autoGenerateId)) { + break; + } + original = node.original; + } + return node; + } + return name; +} function formatGeneratedNamePart(part, generateName) { return typeof part === "object" ? formatGeneratedName( /*privateName*/ @@ -18256,6 +19174,10 @@ function canHaveModifiers(node) { const kind = node.kind; return kind === 165 /* TypeParameter */ || kind === 166 /* Parameter */ || kind === 168 /* PropertySignature */ || kind === 169 /* PropertyDeclaration */ || kind === 170 /* MethodSignature */ || kind === 171 /* MethodDeclaration */ || kind === 173 /* Constructor */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 178 /* IndexSignature */ || kind === 182 /* ConstructorType */ || kind === 215 /* FunctionExpression */ || kind === 216 /* ArrowFunction */ || kind === 228 /* ClassExpression */ || kind === 240 /* VariableStatement */ || kind === 259 /* FunctionDeclaration */ || kind === 260 /* ClassDeclaration */ || kind === 261 /* InterfaceDeclaration */ || kind === 262 /* TypeAliasDeclaration */ || kind === 263 /* EnumDeclaration */ || kind === 264 /* ModuleDeclaration */ || kind === 268 /* ImportEqualsDeclaration */ || kind === 269 /* ImportDeclaration */ || kind === 274 /* ExportAssignment */ || kind === 275 /* ExportDeclaration */; } +function canHaveDecorators(node) { + const kind = node.kind; + return kind === 166 /* Parameter */ || kind === 169 /* PropertyDeclaration */ || kind === 171 /* MethodDeclaration */ || kind === 174 /* GetAccessor */ || kind === 175 /* SetAccessor */ || kind === 228 /* ClassExpression */ || kind === 260 /* ClassDeclaration */; +} // src/compiler/parser.ts var NodeConstructor; @@ -33840,6 +34762,24 @@ function extractSingleNode(nodes) { return singleOrUndefined(nodes); } +// src/compiler/sourcemap.ts +function isStringOrNull(x) { + return typeof x === "string" || x === null; +} +function isRawSourceMap(x) { + return x !== null && typeof x === "object" && x.version === 3 && typeof x.file === "string" && typeof x.mappings === "string" && isArray(x.sources) && every(x.sources, isString) && (x.sourceRoot === void 0 || x.sourceRoot === null || typeof x.sourceRoot === "string") && (x.sourcesContent === void 0 || x.sourcesContent === null || isArray(x.sourcesContent) && every(x.sourcesContent, isStringOrNull)) && (x.names === void 0 || x.names === null || isArray(x.names) && every(x.names, isString)); +} +function tryParseRawSourceMap(text) { + try { + const parsed = JSON.parse(text); + if (isRawSourceMap(parsed)) { + return parsed; + } + } catch (e) { + } + return void 0; +} + // src/compiler/transformers/jsx.ts var entities = new Map(Object.entries({ quot: 34, @@ -34098,8 +35038,54 @@ var entities = new Map(Object.entries({ })); // src/compiler/transformers/declarations.ts +function hasInternalAnnotation(range, currentSourceFile) { + const comment = currentSourceFile.text.substring(range.pos, range.end); + return stringContains(comment, "@internal"); +} +function isInternalDeclaration(node, currentSourceFile) { + const parseTreeNode = getParseTreeNode(node); + if (parseTreeNode && parseTreeNode.kind === 166 /* Parameter */) { + const paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); + const previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : void 0; + const text = currentSourceFile.text; + const commentRanges = previousSibling ? concatenate( + // to handle + // ... parameters, /** @internal */ + // public param: string + getTrailingCommentRanges(text, skipTrivia( + text, + previousSibling.end + 1, + /* stopAfterLineBreak */ + false, + /* stopAtComments */ + true + )), + getLeadingCommentRanges(text, node.pos) + ) : getTrailingCommentRanges(text, skipTrivia( + text, + node.pos, + /* stopAfterLineBreak */ + false, + /* stopAtComments */ + true + )); + return commentRanges && commentRanges.length && hasInternalAnnotation(last(commentRanges), currentSourceFile); + } + const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile); + return !!forEach(leadingCommentRanges, (range) => { + return hasInternalAnnotation(range, currentSourceFile); + }); +} var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +// src/compiler/transformer.ts +function noEmitSubstitution(_hint, node) { + return node; +} +function noEmitNotification(hint, node, callback) { + callback(hint, node); +} + // src/compiler/emitter.ts var brackets = createBracketsMap(); function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCanonicalFileName, checkSourceFilesBelongToPath) { @@ -34118,13 +35104,4674 @@ function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCa } return commonSourceDirectory; } -function createBracketsMap() { - const brackets2 = []; - brackets2[1024 /* Braces */] = ["{", "}"]; - brackets2[2048 /* Parenthesis */] = ["(", ")"]; - brackets2[4096 /* AngleBrackets */] = ["<", ">"]; - brackets2[8192 /* SquareBrackets */] = ["[", "]"]; - return brackets2; +var createPrinterWithDefaults = memoize(() => createPrinter({})); +var createPrinterWithRemoveComments = memoize(() => createPrinter({ removeComments: true })); +var createPrinterWithRemoveCommentsNeverAsciiEscape = memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); +var createPrinterWithRemoveCommentsOmitTrailingSemicolon = memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); +function createPrinter(printerOptions = {}, handlers = {}) { + const { + hasGlobalName, + onEmitNode = noEmitNotification, + isEmitNotificationEnabled, + substituteNode = noEmitSubstitution, + onBeforeEmitNode, + onAfterEmitNode, + onBeforeEmitNodeArray, + onAfterEmitNodeArray, + onBeforeEmitToken, + onAfterEmitToken + } = handlers; + const extendedDiagnostics = !!printerOptions.extendedDiagnostics; + const newLine = getNewLineCharacter(printerOptions); + const moduleKind = getEmitModuleKind(printerOptions); + const bundledHelpers = /* @__PURE__ */ new Map(); + let currentSourceFile; + let nodeIdToGeneratedName; + let nodeIdToGeneratedPrivateName; + let autoGeneratedIdToGeneratedName; + let generatedNames; + let formattedNameTempFlagsStack; + let formattedNameTempFlags; + let privateNameTempFlagsStack; + let privateNameTempFlags; + let tempFlagsStack; + let tempFlags; + let reservedNamesStack; + let reservedNames; + let reservedPrivateNamesStack; + let reservedPrivateNames; + let preserveSourceNewlines = printerOptions.preserveSourceNewlines; + let nextListElementPos; + let writer; + let ownWriter; + let write = writeBase; + let isOwnFileEmit; + const bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : void 0; + const relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : void 0; + const recordInternalSection = printerOptions.recordInternalSection; + let sourceFileTextPos = 0; + let sourceFileTextKind = "text" /* Text */; + let sourceMapsDisabled = true; + let sourceMapGenerator; + let sourceMapSource; + let sourceMapSourceIndex = -1; + let mostRecentlyAddedSourceMapSource; + let mostRecentlyAddedSourceMapSourceIndex = -1; + let containerPos = -1; + let containerEnd = -1; + let declarationListContainerEnd = -1; + let currentLineMap; + let detachedCommentsInfo; + let hasWrittenComment = false; + let commentsDisabled = !!printerOptions.removeComments; + let lastSubstitution; + let currentParenthesizerRule; + const { enter: enterComment, exit: exitComment } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); + const parenthesizer = factory.parenthesizer; + const typeArgumentParenthesizerRuleSelector = { + select: (index) => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : void 0 + }; + const emitBinaryExpression = createEmitBinaryExpression(); + reset(); + return { + // public API + printNode, + printList, + printFile, + printBundle, + // internal API + writeNode, + writeList, + writeFile: writeFile2, + writeBundle, + bundleFileInfo + }; + function printNode(hint, node, sourceFile) { + switch (hint) { + case 0 /* SourceFile */: + Debug.assert(isSourceFile(node), "Expected a SourceFile node."); + break; + case 2 /* IdentifierName */: + Debug.assert(isIdentifier(node), "Expected an Identifier node."); + break; + case 1 /* Expression */: + Debug.assert(isExpression(node), "Expected an Expression node."); + break; + } + switch (node.kind) { + case 308 /* SourceFile */: + return printFile(node); + case 309 /* Bundle */: + return printBundle(node); + case 310 /* UnparsedSource */: + return printUnparsedSource(node); + } + writeNode(hint, node, sourceFile, beginPrint()); + return endPrint(); + } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } + function printBundle(bundle) { + writeBundle( + bundle, + beginPrint(), + /*sourceMapEmitter*/ + void 0 + ); + return endPrint(); + } + function printFile(sourceFile) { + writeFile2( + sourceFile, + beginPrint(), + /*sourceMapEmitter*/ + void 0 + ); + return endPrint(); + } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } + function writeNode(hint, node, sourceFile, output) { + const previousWriter = writer; + setWriter( + output, + /*_sourceMapGenerator*/ + void 0 + ); + print(hint, node, sourceFile); + reset(); + writer = previousWriter; + } + function writeList(format, nodes, sourceFile, output) { + const previousWriter = writer; + setWriter( + output, + /*_sourceMapGenerator*/ + void 0 + ); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList( + /*parentNode*/ + void 0, + nodes, + format + ); + reset(); + writer = previousWriter; + } + function getTextPosWithWriteLine() { + return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos(); + } + function updateOrPushBundleFileTextLike(pos, end, kind) { + const last2 = lastOrUndefined(bundleFileInfo.sections); + if (last2 && last2.kind === kind) { + last2.end = end; + } else { + bundleFileInfo.sections.push({ pos, end, kind }); + } + } + function recordBundleFileInternalSectionStart(node) { + if (recordInternalSection && bundleFileInfo && currentSourceFile && (isDeclaration(node) || isVariableStatement(node)) && isInternalDeclaration(node, currentSourceFile) && sourceFileTextKind !== "internal" /* Internal */) { + const prevSourceFileTextKind = sourceFileTextKind; + recordBundleFileTextLikeSection(writer.getTextPos()); + sourceFileTextPos = getTextPosWithWriteLine(); + sourceFileTextKind = "internal" /* Internal */; + return prevSourceFileTextKind; + } + return void 0; + } + function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) { + if (prevSourceFileTextKind) { + recordBundleFileTextLikeSection(writer.getTextPos()); + sourceFileTextPos = getTextPosWithWriteLine(); + sourceFileTextKind = prevSourceFileTextKind; + } + } + function recordBundleFileTextLikeSection(end) { + if (sourceFileTextPos < end) { + updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind); + return true; + } + return false; + } + function writeBundle(bundle, output, sourceMapGenerator2) { + isOwnFileEmit = false; + const previousWriter = writer; + setWriter(output, sourceMapGenerator2); + emitShebangIfNeeded(bundle); + emitPrologueDirectivesIfNeeded(bundle); + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (const prepend of bundle.prepends) { + writeLine(); + const pos = writer.getTextPos(); + const savedSections = bundleFileInfo && bundleFileInfo.sections; + if (savedSections) + bundleFileInfo.sections = []; + print( + 4 /* Unspecified */, + prepend, + /*sourceFile*/ + void 0 + ); + if (bundleFileInfo) { + const newSections = bundleFileInfo.sections; + bundleFileInfo.sections = savedSections; + if (prepend.oldFileOfCurrentEmit) + bundleFileInfo.sections.push(...newSections); + else { + newSections.forEach((section) => Debug.assert(isBundleFileTextLike(section))); + bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "prepend" /* Prepend */, + data: relativeToBuildInfo(prepend.fileName), + texts: newSections + }); + } + } + } + sourceFileTextPos = getTextPosWithWriteLine(); + for (const sourceFile of bundle.sourceFiles) { + print(0 /* SourceFile */, sourceFile, sourceFile); + } + if (bundleFileInfo && bundle.sourceFiles.length) { + const end = writer.getTextPos(); + if (recordBundleFileTextLikeSection(end)) { + const prologues = getPrologueDirectivesFromBundledSourceFiles(bundle); + if (prologues) { + if (!bundleFileInfo.sources) + bundleFileInfo.sources = {}; + bundleFileInfo.sources.prologues = prologues; + } + const helpers = getHelpersFromBundledSourceFiles(bundle); + if (helpers) { + if (!bundleFileInfo.sources) + bundleFileInfo.sources = {}; + bundleFileInfo.sources.helpers = helpers; + } + } + } + reset(); + writer = previousWriter; + } + function writeUnparsedSource(unparsed, output) { + const previousWriter = writer; + setWriter( + output, + /*_sourceMapGenerator*/ + void 0 + ); + print( + 4 /* Unspecified */, + unparsed, + /*sourceFile*/ + void 0 + ); + reset(); + writer = previousWriter; + } + function writeFile2(sourceFile, output, sourceMapGenerator2) { + isOwnFileEmit = true; + const previousWriter = writer; + setWriter(output, sourceMapGenerator2); + emitShebangIfNeeded(sourceFile); + emitPrologueDirectivesIfNeeded(sourceFile); + print(0 /* SourceFile */, sourceFile, sourceFile); + reset(); + writer = previousWriter; + } + function beginPrint() { + return ownWriter || (ownWriter = createTextWriter(newLine)); + } + function endPrint() { + const text = ownWriter.getText(); + ownWriter.clear(); + return text; + } + function print(hint, node, sourceFile) { + if (sourceFile) { + setSourceFile(sourceFile); + } + pipelineEmit( + hint, + node, + /*parenthesizerRule*/ + void 0 + ); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + currentLineMap = void 0; + detachedCommentsInfo = void 0; + if (sourceFile) { + setSourceMapSource(sourceFile); + } + } + function setWriter(_writer, _sourceMapGenerator) { + if (_writer && printerOptions.omitTrailingSemicolon) { + _writer = getTrailingSemicolonDeferringWriter(_writer); + } + writer = _writer; + sourceMapGenerator = _sourceMapGenerator; + sourceMapsDisabled = !writer || !sourceMapGenerator; + } + function reset() { + nodeIdToGeneratedName = []; + nodeIdToGeneratedPrivateName = []; + autoGeneratedIdToGeneratedName = []; + generatedNames = /* @__PURE__ */ new Set(); + formattedNameTempFlagsStack = []; + formattedNameTempFlags = /* @__PURE__ */ new Map(); + privateNameTempFlagsStack = []; + privateNameTempFlags = TempFlags.Auto; + tempFlagsStack = []; + tempFlags = TempFlags.Auto; + reservedNamesStack = []; + reservedNames = void 0; + reservedPrivateNamesStack = []; + reservedPrivateNames = void 0; + currentSourceFile = void 0; + currentLineMap = void 0; + detachedCommentsInfo = void 0; + setWriter( + /*output*/ + void 0, + /*_sourceMapGenerator*/ + void 0 + ); + } + function getCurrentLineMap() { + return currentLineMap || (currentLineMap = getLineStarts(Debug.checkDefined(currentSourceFile))); + } + function emit(node, parenthesizerRule) { + if (node === void 0) + return; + const prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); + recordBundleFileInternalSectionEnd(prevSourceFileTextKind); + } + function emitIdentifierName(node) { + if (node === void 0) + return; + pipelineEmit( + 2 /* IdentifierName */, + node, + /*parenthesizerRule*/ + void 0 + ); + } + function emitExpression(node, parenthesizerRule) { + if (node === void 0) + return; + pipelineEmit(1 /* Expression */, node, parenthesizerRule); + } + function emitJsxAttributeValue(node) { + pipelineEmit(isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + } + function beforeEmitNode(node) { + if (preserveSourceNewlines && getInternalEmitFlags(node) & 4 /* IgnoreSourceNewlines */) { + preserveSourceNewlines = false; + } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; + const pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); + pipelinePhase(emitHint, node); + currentParenthesizerRule = void 0; + } + function shouldEmitComments(node) { + return !commentsDisabled && !isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && !isSourceFile(node) && !isInJsonFile(node) && !isUnparsedSource(node) && !isUnparsedPrepend(node); + } + function getPipelinePhase(phase, emitHint, node) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { + return pipelineEmitWithNotification; + } + case 1 /* Substitution */: + if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } + return pipelineEmitWithSubstitution; + } + case 2 /* Comments */: + if (shouldEmitComments(node)) { + return pipelineEmitWithComments; + } + case 3 /* SourceMaps */: + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; + } + case 4 /* Emit */: + return pipelineEmitWithHint; + default: + return Debug.assertNever(phase); + } + } + function getNextPipelinePhase(currentPhase, emitHint, node) { + return getPipelinePhase(currentPhase + 1, emitHint, node); + } + function pipelineEmitWithNotification(hint, node) { + const pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); + onEmitNode(hint, node, pipelinePhase); + } + function pipelineEmitWithHint(hint, node) { + onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + const savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode == null ? void 0 : onAfterEmitNode(node); + currentParenthesizerRule = void 0; + } + function pipelineEmitWithHintWorker(hint, node, allowSnippets = true) { + if (allowSnippets) { + const snippet = getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } + if (hint === 0 /* SourceFile */) + return emitSourceFile(cast(node, isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(cast(node, isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) + return emitLiteral( + cast(node, isStringLiteral), + /*jsxAttributeEscape*/ + true + ); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); + if (hint === 5 /* EmbeddedStatement */) { + Debug.assertNode(node, isEmptyStatement); + return emitEmptyStatement( + /*isEmbeddedStatement*/ + true + ); + } + if (hint === 4 /* Unspecified */) { + switch (node.kind) { + case 15 /* TemplateHead */: + case 16 /* TemplateMiddle */: + case 17 /* TemplateTail */: + return emitLiteral( + node, + /*jsxAttributeEscape*/ + false + ); + case 79 /* Identifier */: + return emitIdentifier(node); + case 80 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + case 163 /* QualifiedName */: + return emitQualifiedName(node); + case 164 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + case 165 /* TypeParameter */: + return emitTypeParameter(node); + case 166 /* Parameter */: + return emitParameter(node); + case 167 /* Decorator */: + return emitDecorator(node); + case 168 /* PropertySignature */: + return emitPropertySignature(node); + case 169 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 170 /* MethodSignature */: + return emitMethodSignature(node); + case 171 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 172 /* ClassStaticBlockDeclaration */: + return emitClassStaticBlockDeclaration(node); + case 173 /* Constructor */: + return emitConstructor(node); + case 174 /* GetAccessor */: + case 175 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 176 /* CallSignature */: + return emitCallSignature(node); + case 177 /* ConstructSignature */: + return emitConstructSignature(node); + case 178 /* IndexSignature */: + return emitIndexSignature(node); + case 179 /* TypePredicate */: + return emitTypePredicate(node); + case 180 /* TypeReference */: + return emitTypeReference(node); + case 181 /* FunctionType */: + return emitFunctionType(node); + case 182 /* ConstructorType */: + return emitConstructorType(node); + case 183 /* TypeQuery */: + return emitTypeQuery(node); + case 184 /* TypeLiteral */: + return emitTypeLiteral(node); + case 185 /* ArrayType */: + return emitArrayType(node); + case 186 /* TupleType */: + return emitTupleType(node); + case 187 /* OptionalType */: + return emitOptionalType(node); + case 189 /* UnionType */: + return emitUnionType(node); + case 190 /* IntersectionType */: + return emitIntersectionType(node); + case 191 /* ConditionalType */: + return emitConditionalType(node); + case 192 /* InferType */: + return emitInferType(node); + case 193 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 230 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 194 /* ThisType */: + return emitThisType(); + case 195 /* TypeOperator */: + return emitTypeOperator(node); + case 196 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 197 /* MappedType */: + return emitMappedType(node); + case 198 /* LiteralType */: + return emitLiteralType(node); + case 199 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 200 /* TemplateLiteralType */: + return emitTemplateType(node); + case 201 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 202 /* ImportType */: + return emitImportTypeNode(node); + case 203 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 204 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 205 /* BindingElement */: + return emitBindingElement(node); + case 236 /* TemplateSpan */: + return emitTemplateSpan(node); + case 237 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + case 238 /* Block */: + return emitBlock(node); + case 240 /* VariableStatement */: + return emitVariableStatement(node); + case 239 /* EmptyStatement */: + return emitEmptyStatement( + /*isEmbeddedStatement*/ + false + ); + case 241 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 242 /* IfStatement */: + return emitIfStatement(node); + case 243 /* DoStatement */: + return emitDoStatement(node); + case 244 /* WhileStatement */: + return emitWhileStatement(node); + case 245 /* ForStatement */: + return emitForStatement(node); + case 246 /* ForInStatement */: + return emitForInStatement(node); + case 247 /* ForOfStatement */: + return emitForOfStatement(node); + case 248 /* ContinueStatement */: + return emitContinueStatement(node); + case 249 /* BreakStatement */: + return emitBreakStatement(node); + case 250 /* ReturnStatement */: + return emitReturnStatement(node); + case 251 /* WithStatement */: + return emitWithStatement(node); + case 252 /* SwitchStatement */: + return emitSwitchStatement(node); + case 253 /* LabeledStatement */: + return emitLabeledStatement(node); + case 254 /* ThrowStatement */: + return emitThrowStatement(node); + case 255 /* TryStatement */: + return emitTryStatement(node); + case 256 /* DebuggerStatement */: + return emitDebuggerStatement(node); + case 257 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 258 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 259 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 260 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 261 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 262 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 263 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 264 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 265 /* ModuleBlock */: + return emitModuleBlock(node); + case 266 /* CaseBlock */: + return emitCaseBlock(node); + case 267 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 268 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 269 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 270 /* ImportClause */: + return emitImportClause(node); + case 271 /* NamespaceImport */: + return emitNamespaceImport(node); + case 277 /* NamespaceExport */: + return emitNamespaceExport(node); + case 272 /* NamedImports */: + return emitNamedImports(node); + case 273 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 274 /* ExportAssignment */: + return emitExportAssignment(node); + case 275 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 276 /* NamedExports */: + return emitNamedExports(node); + case 278 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 296 /* AssertClause */: + return emitAssertClause(node); + case 297 /* AssertEntry */: + return emitAssertEntry(node); + case 279 /* MissingDeclaration */: + return; + case 280 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + case 11 /* JsxText */: + return emitJsxText(node); + case 283 /* JsxOpeningElement */: + case 286 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 284 /* JsxClosingElement */: + case 287 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 288 /* JsxAttribute */: + return emitJsxAttribute(node); + case 289 /* JsxAttributes */: + return emitJsxAttributes(node); + case 290 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 291 /* JsxExpression */: + return emitJsxExpression(node); + case 292 /* CaseClause */: + return emitCaseClause(node); + case 293 /* DefaultClause */: + return emitDefaultClause(node); + case 294 /* HeritageClause */: + return emitHeritageClause(node); + case 295 /* CatchClause */: + return emitCatchClause(node); + case 299 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 300 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 301 /* SpreadAssignment */: + return emitSpreadAssignment(node); + case 302 /* EnumMember */: + return emitEnumMember(node); + case 303 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 310 /* UnparsedSource */: + case 304 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 305 /* UnparsedText */: + case 306 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 307 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + case 308 /* SourceFile */: + return emitSourceFile(node); + case 309 /* Bundle */: + return Debug.fail("Bundles should be printed using printBundle"); + case 311 /* InputFiles */: + return Debug.fail("InputFiles should not be printed"); + case 312 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 313 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 315 /* JSDocAllType */: + return writePunctuation("*"); + case 316 /* JSDocUnknownType */: + return writePunctuation("?"); + case 317 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 318 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 319 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 320 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 188 /* RestType */: + case 321 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 322 /* JSDocNamepathType */: + return; + case 323 /* JSDoc */: + return emitJSDoc(node); + case 325 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 326 /* JSDocSignature */: + return emitJSDocSignature(node); + case 330 /* JSDocTag */: + case 335 /* JSDocClassTag */: + case 340 /* JSDocOverrideTag */: + return emitJSDocSimpleTag(node); + case 331 /* JSDocAugmentsTag */: + case 332 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 333 /* JSDocAuthorTag */: + case 334 /* JSDocDeprecatedTag */: + return; + case 336 /* JSDocPublicTag */: + case 337 /* JSDocPrivateTag */: + case 338 /* JSDocProtectedTag */: + case 339 /* JSDocReadonlyTag */: + return; + case 341 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + case 342 /* JSDocOverloadTag */: + return emitJSDocOverloadTag(node); + case 344 /* JSDocParameterTag */: + case 351 /* JSDocPropertyTag */: + return emitJSDocPropertyLikeTag(node); + case 343 /* JSDocEnumTag */: + case 345 /* JSDocReturnTag */: + case 346 /* JSDocThisTag */: + case 347 /* JSDocTypeTag */: + case 352 /* JSDocThrowsTag */: + case 353 /* JSDocSatisfiesTag */: + return emitJSDocSimpleTypedTag(node); + case 348 /* JSDocTemplateTag */: + return emitJSDocTemplateTag(node); + case 349 /* JSDocTypedefTag */: + return emitJSDocTypedefTag(node); + case 350 /* JSDocSeeTag */: + return emitJSDocSeeTag(node); + case 355 /* NotEmittedStatement */: + case 359 /* EndOfDeclarationMarker */: + case 358 /* MergeDeclarationMarker */: + return; + } + if (isExpression(node)) { + hint = 1 /* Expression */; + if (substituteNode !== noEmitSubstitution) { + const substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } + } + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + return emitNumericOrBigIntLiteral(node); + case 10 /* StringLiteral */: + case 13 /* RegularExpressionLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return emitLiteral( + node, + /*jsxAttributeEscape*/ + false + ); + case 79 /* Identifier */: + return emitIdentifier(node); + case 80 /* PrivateIdentifier */: + return emitPrivateIdentifier(node); + case 206 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 207 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 208 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 209 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 210 /* CallExpression */: + return emitCallExpression(node); + case 211 /* NewExpression */: + return emitNewExpression(node); + case 212 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 213 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 214 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 215 /* FunctionExpression */: + return emitFunctionExpression(node); + case 216 /* ArrowFunction */: + return emitArrowFunction(node); + case 217 /* DeleteExpression */: + return emitDeleteExpression(node); + case 218 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 219 /* VoidExpression */: + return emitVoidExpression(node); + case 220 /* AwaitExpression */: + return emitAwaitExpression(node); + case 221 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 222 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 223 /* BinaryExpression */: + return emitBinaryExpression(node); + case 224 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 225 /* TemplateExpression */: + return emitTemplateExpression(node); + case 226 /* YieldExpression */: + return emitYieldExpression(node); + case 227 /* SpreadElement */: + return emitSpreadElement(node); + case 228 /* ClassExpression */: + return emitClassExpression(node); + case 229 /* OmittedExpression */: + return; + case 231 /* AsExpression */: + return emitAsExpression(node); + case 232 /* NonNullExpression */: + return emitNonNullExpression(node); + case 230 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 235 /* SatisfiesExpression */: + return emitSatisfiesExpression(node); + case 233 /* MetaProperty */: + return emitMetaProperty(node); + case 234 /* SyntheticExpression */: + return Debug.fail("SyntheticExpression should never be printed."); + case 279 /* MissingDeclaration */: + return; + case 281 /* JsxElement */: + return emitJsxElement(node); + case 282 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 285 /* JsxFragment */: + return emitJsxFragment(node); + case 354 /* SyntaxList */: + return Debug.fail("SyntaxList should not be printed"); + case 355 /* NotEmittedStatement */: + return; + case 356 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 357 /* CommaListExpression */: + return emitCommaList(node); + case 358 /* MergeDeclarationMarker */: + case 359 /* EndOfDeclarationMarker */: + return; + case 360 /* SyntheticReferenceExpression */: + return Debug.fail("SyntheticReferenceExpression should not be printed"); + } + } + if (isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + Debug.fail(`Unhandled SyntaxKind: ${Debug.formatSyntaxKind(node.kind)}.`); + } + function emitMappedTypeParameter(node) { + emit(node.name); + writeSpace(); + writeKeyword("in"); + writeSpace(); + emit(node.constraint); + } + function pipelineEmitWithSubstitution(hint, node) { + const pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); + Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = void 0; + pipelinePhase(hint, node); + } + function getHelpersFromBundledSourceFiles(bundle) { + let result; + if (moduleKind === 0 /* None */ || printerOptions.noEmitHelpers) { + return void 0; + } + const bundledHelpers2 = /* @__PURE__ */ new Map(); + for (const sourceFile of bundle.sourceFiles) { + const shouldSkip = getExternalHelpersModuleName(sourceFile) !== void 0; + const helpers = getSortedEmitHelpers(sourceFile); + if (!helpers) + continue; + for (const helper of helpers) { + if (!helper.scoped && !shouldSkip && !bundledHelpers2.get(helper.name)) { + bundledHelpers2.set(helper.name, true); + (result || (result = [])).push(helper.name); + } + } + } + return result; + } + function emitHelpers(node) { + let helpersEmitted = false; + const bundle = node.kind === 309 /* Bundle */ ? node : void 0; + if (bundle && moduleKind === 0 /* None */) { + return; + } + const numPrepends = bundle ? bundle.prepends.length : 0; + const numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1; + for (let i = 0; i < numNodes; i++) { + const currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node; + const sourceFile = isSourceFile(currentNode) ? currentNode : isUnparsedSource(currentNode) ? void 0 : currentSourceFile; + const shouldSkip = printerOptions.noEmitHelpers || !!sourceFile && hasRecordedExternalHelpers(sourceFile); + const shouldBundle = (isSourceFile(currentNode) || isUnparsedSource(currentNode)) && !isOwnFileEmit; + const helpers = isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode); + if (helpers) { + for (const helper of helpers) { + if (!helper.scoped) { + if (shouldSkip) + continue; + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } else if (bundle) { + continue; + } + const pos = getTextPosWithWriteLine(); + if (typeof helper.text === "string") { + writeLines(helper.text); + } else { + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); + } + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name }); + helpersEmitted = true; + } + } + } + return helpersEmitted; + } + function getSortedEmitHelpers(node) { + const helpers = getEmitHelpers(node); + return helpers && stableSort(helpers, compareEmitHelpers); + } + function emitNumericOrBigIntLiteral(node) { + emitLiteral( + node, + /*jsxAttributeEscape*/ + false + ); + } + function emitLiteral(node, jsxAttributeEscape) { + const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape); + if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind))) { + writeLiteral(text); + } else { + writeStringLiteral(text); + } + } + function emitUnparsedSourceOrPrepend(unparsed) { + for (const text of unparsed.texts) { + writeLine(); + emit(text); + } + } + function writeUnparsedNode(unparsed) { + writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end)); + } + function emitUnparsedTextLike(unparsed) { + const pos = getTextPosWithWriteLine(); + writeUnparsedNode(unparsed); + if (bundleFileInfo) { + updateOrPushBundleFileTextLike( + pos, + writer.getTextPos(), + unparsed.kind === 305 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */ + ); + } + } + function emitUnparsedSyntheticReference(unparsed) { + const pos = getTextPosWithWriteLine(); + writeUnparsedNode(unparsed); + if (bundleFileInfo) { + const section = clone(unparsed.section); + section.pos = pos; + section.end = writer.getTextPos(); + bundleFileInfo.sections.push(section); + } + } + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(hint, node, snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite(`\${${snippet.order}:`); + pipelineEmitWithHintWorker( + hint, + node, + /*allowSnippets*/ + false + ); + nonEscapingWrite(`}`); + } + function emitTabStop(hint, node, snippet) { + Debug.assert( + node.kind === 239 /* EmptyStatement */, + `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.` + ); + Debug.assert( + hint !== 5 /* EmbeddedStatement */, + `A tab stop cannot be attached to an embedded statement.` + ); + nonEscapingWrite(`$${snippet.order}`); + } + function emitIdentifier(node) { + const writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode2( + node, + /*includeTrivia*/ + false + ), node.symbol); + emitList(node, getIdentifierTypeArguments(node), 53776 /* TypeParameters */); + } + function emitPrivateIdentifier(node) { + write(getTextOfNode2( + node, + /*includeTrivia*/ + false + )); + } + function emitQualifiedName(node) { + emitEntityName(node.left); + writePunctuation("."); + emit(node.right); + } + function emitEntityName(node) { + if (node.kind === 79 /* Identifier */) { + emitExpression(node); + } else { + emit(node); + } + } + function emitComputedPropertyName(node) { + const savedPrivateNameTempFlags = privateNameTempFlags; + const savedReservedMemberNames = reservedPrivateNames; + popPrivateNameGenerationScope(); + writePunctuation("["); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); + writePunctuation("]"); + pushPrivateNameGenerationScope(savedPrivateNameTempFlags, savedReservedMemberNames); + } + function emitTypeParameter(node) { + emitModifierList(node, node.modifiers); + emit(node.name); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } + } + function emitParameter(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 320 /* JSDocFunctionType */ && !node.name) { + emit(node.type); + } else { + emitTypeAnnotation(node.type); + } + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitDecorator(decorator) { + writePunctuation("@"); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); + } + function emitPropertySignature(node) { + emitModifierList(node, node.modifiers); + emitNodeWithWriter(node.name, writeProperty); + emit(node.questionToken); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitPropertyDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emit(node.name); + emit(node.questionToken); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); + writeTrailingSemicolon(); + } + function emitMethodSignature(node) { + pushNameGenerationScope(node); + emitModifierList(node, node.modifiers); + emit(node.name); + emit(node.questionToken); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitMethodDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emit(node.asteriskToken); + emit(node.name); + emit(node.questionToken); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitClassStaticBlockDeclaration(node) { + writeKeyword("static"); + emitBlockFunctionBody(node.body); + } + function emitConstructor(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("constructor"); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitAccessorDeclaration(node) { + const pos = emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + const token = node.kind === 174 /* GetAccessor */ ? 137 /* GetKeyword */ : 151 /* SetKeyword */; + emitTokenWithComment(token, pos, writeKeyword, node); + writeSpace(); + emit(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitCallSignature(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitConstructSignature(node) { + pushNameGenerationScope(node); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + popNameGenerationScope(node); + } + function emitIndexSignature(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emitParametersForIndexSignature(node, node.parameters); + emitTypeAnnotation(node.type); + writeTrailingSemicolon(); + } + function emitTemplateTypeSpan(node) { + emit(node.type); + emit(node.literal); + } + function emitSemicolonClassElement() { + writeTrailingSemicolon(); + } + function emitTypePredicate(node) { + if (node.assertsModifier) { + emit(node.assertsModifier); + writeSpace(); + } + emit(node.parameterName); + if (node.type) { + writeSpace(); + writeKeyword("is"); + writeSpace(); + emit(node.type); + } + } + function emitTypeReference(node) { + emit(node.typeName); + emitTypeArguments(node, node.typeArguments); + } + function emitFunctionType(node) { + pushNameGenerationScope(node); + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitJSDocFunctionType(node) { + writeKeyword("function"); + emitParameters(node, node.parameters); + writePunctuation(":"); + emit(node.type); + } + function emitJSDocNullableType(node) { + writePunctuation("?"); + emit(node.type); + } + function emitJSDocNonNullableType(node) { + writePunctuation("!"); + emit(node.type); + } + function emitJSDocOptionalType(node) { + emit(node.type); + writePunctuation("="); + } + function emitConstructorType(node) { + pushNameGenerationScope(node); + emitModifierList(node, node.modifiers); + writeKeyword("new"); + writeSpace(); + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + writeSpace(); + writePunctuation("=>"); + writeSpace(); + emit(node.type); + popNameGenerationScope(node); + } + function emitTypeQuery(node) { + writeKeyword("typeof"); + writeSpace(); + emit(node.exprName); + emitTypeArguments(node, node.typeArguments); + } + function emitTypeLiteral(node) { + pushPrivateNameGenerationScope( + TempFlags.Auto, + /*newReservedMemberNames*/ + void 0 + ); + writePunctuation("{"); + const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); + writePunctuation("}"); + popPrivateNameGenerationScope(); + } + function emitArrayType(node) { + emit(node.elementType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType); + writePunctuation("["); + writePunctuation("]"); + } + function emitRestOrJSDocVariadicType(node) { + writePunctuation("..."); + emit(node.type); + } + function emitTupleType(node) { + emitTokenWithComment(22 /* OpenBracketToken */, node.pos, writePunctuation, node); + const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */; + emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */, parenthesizer.parenthesizeElementTypeOfTupleType); + emitTokenWithComment(23 /* CloseBracketToken */, node.elements.end, writePunctuation, node); + } + function emitNamedTupleMember(node) { + emit(node.dotDotDotToken); + emit(node.name); + emit(node.questionToken); + emitTokenWithComment(58 /* ColonToken */, node.name.end, writePunctuation, node); + writeSpace(); + emit(node.type); + } + function emitOptionalType(node) { + emit(node.type, parenthesizer.parenthesizeTypeOfOptionalType); + writePunctuation("?"); + } + function emitUnionType(node) { + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeConstituentTypeOfUnionType); + } + function emitIntersectionType(node) { + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeConstituentTypeOfIntersectionType); + } + function emitConditionalType(node) { + emit(node.checkType, parenthesizer.parenthesizeCheckTypeOfConditionalType); + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.extendsType, parenthesizer.parenthesizeExtendsTypeOfConditionalType); + writeSpace(); + writePunctuation("?"); + writeSpace(); + emit(node.trueType); + writeSpace(); + writePunctuation(":"); + writeSpace(); + emit(node.falseType); + } + function emitInferType(node) { + writeKeyword("infer"); + writeSpace(); + emit(node.typeParameter); + } + function emitParenthesizedType(node) { + writePunctuation("("); + emit(node.type); + writePunctuation(")"); + } + function emitThisType() { + writeKeyword("this"); + } + function emitTypeOperator(node) { + writeTokenText(node.operator, writeKeyword); + writeSpace(); + const parenthesizerRule = node.operator === 146 /* ReadonlyKeyword */ ? parenthesizer.parenthesizeOperandOfReadonlyTypeOperator : parenthesizer.parenthesizeOperandOfTypeOperator; + emit(node.type, parenthesizerRule); + } + function emitIndexedAccessType(node) { + emit(node.objectType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType); + writePunctuation("["); + emit(node.indexType); + writePunctuation("]"); + } + function emitMappedType(node) { + const emitFlags = getEmitFlags(node); + writePunctuation("{"); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } else { + writeLine(); + increaseIndent(); + } + if (node.readonlyToken) { + emit(node.readonlyToken); + if (node.readonlyToken.kind !== 146 /* ReadonlyKeyword */) { + writeKeyword("readonly"); + } + writeSpace(); + } + writePunctuation("["); + pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter); + if (node.nameType) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.nameType); + } + writePunctuation("]"); + if (node.questionToken) { + emit(node.questionToken); + if (node.questionToken.kind !== 57 /* QuestionToken */) { + writePunctuation("?"); + } + } + writePunctuation(":"); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + if (emitFlags & 1 /* SingleLine */) { + writeSpace(); + } else { + writeLine(); + decreaseIndent(); + } + emitList(node, node.members, 2 /* PreserveLines */); + writePunctuation("}"); + } + function emitLiteralType(node) { + emitExpression(node.literal); + } + function emitTemplateType(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + if (node.assertions) { + writePunctuation(","); + writeSpace(); + writePunctuation("{"); + writeSpace(); + writeKeyword("assert"); + writePunctuation(":"); + writeSpace(); + const elements = node.assertions.assertClause.elements; + emitList(node.assertions.assertClause, elements, 526226 /* ImportClauseEntries */); + writeSpace(); + writePunctuation("}"); + } + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } + function emitObjectBindingPattern(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */); + writePunctuation("}"); + } + function emitArrayBindingPattern(node) { + writePunctuation("["); + emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */); + writePunctuation("]"); + } + function emitBindingElement(node) { + emit(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } + emit(node.name); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitArrayLiteralExpression(node) { + const elements = node.elements; + const preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitObjectLiteralExpression(node) { + pushPrivateNameGenerationScope( + TempFlags.Auto, + /*newReservedMemberNames*/ + void 0 + ); + forEach(node.properties, generateMemberNames); + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + const preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; + const allowTrailingComma = currentSourceFile && currentSourceFile.languageVersion >= 1 /* ES5 */ && !isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); + } + popPrivateNameGenerationScope(); + } + function emitPropertyAccessExpression(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); + const linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); + const linesAfterDot = getLinesBetweenNodes(node, token, node.name); + writeLinesAndIndent( + linesBeforeDot, + /*writeSpaceIfNotIndenting*/ + false + ); + const shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); + if (shouldEmitDotDot) { + writePunctuation("."); + } + if (node.questionDotToken) { + emit(token); + } else { + emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node); + } + writeLinesAndIndent( + linesAfterDot, + /*writeSpaceIfNotIndenting*/ + false + ); + emit(node.name); + decreaseIndentIf(linesBeforeDot, linesAfterDot); + } + function mayNeedDotDotForPropertyAccess(expression) { + expression = skipPartiallyEmittedExpressions(expression); + if (isNumericLiteral(expression)) { + const text = getLiteralTextOfNode( + expression, + /*neverAsciiEscape*/ + true, + /*jsxAttributeEscape*/ + false + ); + return !expression.numericLiteralFlags && !stringContains(text, tokenToString(24 /* DotToken */)); + } else if (isAccessExpression(expression)) { + const constantValue = getConstantValue(expression); + return typeof constantValue === "number" && isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + function emitElementAccessExpression(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + emit(node.questionDotToken); + emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitExpression(node.argumentExpression); + emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); + } + function emitCallExpression(node) { + const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */; + if (indirectCall) { + writePunctuation("("); + writeLiteral("0"); + writePunctuation(","); + writeSpace(); + } + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + if (indirectCall) { + writePunctuation(")"); + } + emit(node.questionDotToken); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitNewExpression(node) { + emitTokenWithComment(103 /* NewKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); + emitTypeArguments(node, node.typeArguments); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitTaggedTemplateExpression(node) { + const indirectCall = getInternalEmitFlags(node) & 16 /* IndirectCall */; + if (indirectCall) { + writePunctuation("("); + writeLiteral("0"); + writePunctuation(","); + writeSpace(); + } + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); + if (indirectCall) { + writePunctuation(")"); + } + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emitExpression(node.template); + } + function emitTypeAssertionExpression(node) { + writePunctuation("<"); + emit(node.type); + writePunctuation(">"); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitParenthesizedExpression(node) { + const openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + const indented = writeLineSeparatorsAndIndentBefore(node.expression, node); + emitExpression( + node.expression, + /*parenthesizerRules*/ + void 0 + ); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); + emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); + } + function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); + emitFunctionDeclarationOrExpression(node); + } + function emitArrowFunction(node) { + emitModifierList(node, node.modifiers); + emitSignatureAndBody(node, emitArrowFunctionHead); + } + function emitArrowFunctionHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParametersForArrow(node, node.parameters); + emitTypeAnnotation(node.type); + writeSpace(); + emit(node.equalsGreaterThanToken); + } + function emitDeleteExpression(node) { + emitTokenWithComment(89 /* DeleteKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitTypeOfExpression(node) { + emitTokenWithComment(112 /* TypeOfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitVoidExpression(node) { + emitTokenWithComment(114 /* VoidKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitAwaitExpression(node) { + emitTokenWithComment(133 /* AwaitKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function emitPrefixUnaryExpression(node) { + writeTokenText(node.operator, writeOperator); + if (shouldEmitWhitespaceBeforeOperand(node)) { + writeSpace(); + } + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); + } + function shouldEmitWhitespaceBeforeOperand(node) { + const operand = node.operand; + return operand.kind === 221 /* PrefixUnaryExpression */ && (node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */) || node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)); + } + function emitPostfixUnaryExpression(node) { + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); + writeTokenText(node.operator, writeOperator); + } + function createEmitBinaryExpression() { + return createBinaryExpressionTrampoline( + onEnter, + onLeft, + onOperator, + onRight, + onExit, + /*foldState*/ + void 0 + ); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + const emitComments2 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + const emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node); + if (emitComments2) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); + } else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [void 0], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false] + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + const isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; + const linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + const linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 101 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition( + operatorToken.end, + /*prefixSpace*/ + true + ); + writeLinesAndIndent( + linesAfterOperator, + /*writeSpaceIfNotIndenting*/ + true + ); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + const linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + const linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + const savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + const savedContainerPos = state.containerPosStack[state.stackIndex]; + const savedContainerEnd = state.containerEndStack[state.stackIndex]; + const savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + const shouldEmitComments2 = state.shouldEmitCommentsStack[state.stackIndex]; + const shouldEmitSourceMaps2 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps2) + emitSourceMapsAfterNode(node); + if (shouldEmitComments2) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode == null ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + const parenthesizerRule = side === "left" ? parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); + let pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(cast(lastSubstitution, isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = void 0; + } + if (pipelinePhase === pipelineEmitWithComments || pipelinePhase === pipelineEmitWithSourceMaps || pipelinePhase === pipelineEmitWithHint) { + if (isBinaryExpression(next)) { + return next; + } + } + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); + } + } + function emitConditionalExpression(node) { + const linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken); + const linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); + const linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); + const linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); + writeLinesAndIndent( + linesBeforeQuestion, + /*writeSpaceIfNotIndenting*/ + true + ); + emit(node.questionToken); + writeLinesAndIndent( + linesAfterQuestion, + /*writeSpaceIfNotIndenting*/ + true + ); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); + decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); + writeLinesAndIndent( + linesBeforeColon, + /*writeSpaceIfNotIndenting*/ + true + ); + emit(node.colonToken); + writeLinesAndIndent( + linesAfterColon, + /*writeSpaceIfNotIndenting*/ + true + ); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); + decreaseIndentIf(linesBeforeColon, linesAfterColon); + } + function emitTemplateExpression(node) { + emit(node.head); + emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); + } + function emitYieldExpression(node) { + emitTokenWithComment(125 /* YieldKeyword */, node.pos, writeKeyword, node); + emit(node.asteriskToken); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma); + } + function emitSpreadElement(node) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitClassExpression(node) { + generateNameIfNeeded(node.name); + emitClassDeclarationOrExpression(node); + } + function emitExpressionWithTypeArguments(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + emitTypeArguments(node, node.typeArguments); + } + function emitAsExpression(node) { + emitExpression( + node.expression, + /*parenthesizerRules*/ + void 0 + ); + if (node.type) { + writeSpace(); + writeKeyword("as"); + writeSpace(); + emit(node.type); + } + } + function emitNonNullExpression(node) { + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); + writeOperator("!"); + } + function emitSatisfiesExpression(node) { + emitExpression( + node.expression, + /*parenthesizerRules*/ + void 0 + ); + if (node.type) { + writeSpace(); + writeKeyword("satisfies"); + writeSpace(); + emit(node.type); + } + } + function emitMetaProperty(node) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); + emit(node.name); + } + function emitTemplateSpan(node) { + emitExpression(node.expression); + emit(node.literal); + } + function emitBlock(node) { + emitBlockStatements( + node, + /*forceSingleLine*/ + !node.multiLine && isEmptyBlock(node) + ); + } + function emitBlockStatements(node, forceSingleLine) { + emitTokenWithComment( + 18 /* OpenBraceToken */, + node.pos, + writePunctuation, + /*contextNode*/ + node + ); + const format = forceSingleLine || getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); + emitTokenWithComment( + 19 /* CloseBraceToken */, + node.statements.end, + writePunctuation, + /*contextNode*/ + node, + /*indentLeading*/ + !!(format & 1 /* MultiLine */) + ); + } + function emitVariableStatement(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emit(node.declarationList); + writeTrailingSemicolon(); + } + function emitEmptyStatement(isEmbeddedStatement) { + if (isEmbeddedStatement) { + writePunctuation(";"); + } else { + writeTrailingSemicolon(); + } + } + function emitExpressionStatement(node) { + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); + if (!currentSourceFile || !isJsonSourceFile(currentSourceFile) || nodeIsSynthesized(node.expression)) { + writeTrailingSemicolon(); + } + } + function emitIfStatement(node) { + const openParenPos = emitTokenWithComment(99 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.thenStatement); + if (node.elseStatement) { + writeLineOrSpace(node, node.thenStatement, node.elseStatement); + emitTokenWithComment(91 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); + if (node.elseStatement.kind === 242 /* IfStatement */) { + writeSpace(); + emit(node.elseStatement); + } else { + emitEmbeddedStatement(node, node.elseStatement); + } + } + } + function emitWhileClause(node, startPos) { + const openParenPos = emitTokenWithComment(115 /* WhileKeyword */, startPos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + } + function emitDoStatement(node) { + emitTokenWithComment(90 /* DoKeyword */, node.pos, writeKeyword, node); + emitEmbeddedStatement(node, node.statement); + if (isBlock(node.statement) && !preserveSourceNewlines) { + writeSpace(); + } else { + writeLineOrSpace(node, node.statement, node.expression); + } + emitWhileClause(node, node.statement.end); + writeTrailingSemicolon(); + } + function emitWhileStatement(node) { + emitWhileClause(node, node.pos); + emitEmbeddedStatement(node, node.statement); + } + function emitForStatement(node) { + const openParenPos = emitTokenWithComment(97 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + let pos = emitTokenWithComment( + 20 /* OpenParenToken */, + openParenPos, + writePunctuation, + /*contextNode*/ + node + ); + emitForBinding(node.initializer); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.condition); + pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node); + emitExpressionWithLeadingSpace(node.incrementor); + emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForInStatement(node) { + const openParenPos = emitTokenWithComment(97 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(101 /* InKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForOfStatement(node) { + const openParenPos = emitTokenWithComment(97 /* ForKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitForBinding(node.initializer); + writeSpace(); + emitTokenWithComment(162 /* OfKeyword */, node.initializer.end, writeKeyword, node); + writeSpace(); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitForBinding(node) { + if (node !== void 0) { + if (node.kind === 258 /* VariableDeclarationList */) { + emit(node); + } else { + emitExpression(node); + } + } + } + function emitContinueStatement(node) { + emitTokenWithComment(86 /* ContinueKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitBreakStatement(node) { + emitTokenWithComment(81 /* BreakKeyword */, node.pos, writeKeyword, node); + emitWithLeadingSpace(node.label); + writeTrailingSemicolon(); + } + function emitTokenWithComment(token, pos, writer2, contextNode, indentLeading) { + const node = getParseTreeNode(contextNode); + const isSimilarNode = node && node.kind === contextNode.kind; + const startPos = pos; + if (isSimilarNode && currentSourceFile) { + pos = skipTrivia(currentSourceFile.text, pos); + } + if (isSimilarNode && contextNode.pos !== startPos) { + const needsIndent = indentLeading && currentSourceFile && !positionsAreOnSameLine(startPos, pos, currentSourceFile); + if (needsIndent) { + increaseIndent(); + } + emitLeadingCommentsOfPosition(startPos); + if (needsIndent) { + decreaseIndent(); + } + } + pos = writeTokenText(token, writer2, pos); + if (isSimilarNode && contextNode.end !== pos) { + const isJsxExprContext = contextNode.kind === 291 /* JsxExpression */; + emitTrailingCommentsOfPosition( + pos, + /*prefixSpace*/ + !isJsxExprContext, + /*forceNoNewline*/ + isJsxExprContext + ); + } + return pos; + } + function commentWillEmitNewLine(node) { + return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; + } + function willEmitLeadingNewLine(node) { + if (!currentSourceFile) + return false; + if (some(getLeadingCommentRanges(currentSourceFile.text, node.pos), commentWillEmitNewLine)) + return true; + if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) + return true; + if (isPartiallyEmittedExpression(node)) { + if (node.pos !== node.expression.pos) { + if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) + return true; + } + return willEmitLeadingNewLine(node.expression); + } + return false; + } + function parenthesizeExpressionForNoAsi(node) { + if (!commentsDisabled && isPartiallyEmittedExpression(node) && willEmitLeadingNewLine(node)) { + const parseNode = getParseTreeNode(node); + if (parseNode && isParenthesizedExpression(parseNode)) { + const parens = factory.createParenthesizedExpression(node.expression); + setOriginalNode(parens, node); + setTextRange(parens, parseNode); + return parens; + } + return factory.createParenthesizedExpression(node); + } + return node; + } + function parenthesizeExpressionForNoAsiAndDisallowedComma(node) { + return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node)); + } + function emitReturnStatement(node) { + emitTokenWithComment( + 105 /* ReturnKeyword */, + node.pos, + writeKeyword, + /*contextNode*/ + node + ); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); + writeTrailingSemicolon(); + } + function emitWithStatement(node) { + const openParenPos = emitTokenWithComment(116 /* WithKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + emitEmbeddedStatement(node, node.statement); + } + function emitSwitchStatement(node) { + const openParenPos = emitTokenWithComment(107 /* SwitchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emitExpression(node.expression); + emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); + writeSpace(); + emit(node.caseBlock); + } + function emitLabeledStatement(node) { + emit(node.label); + emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node); + writeSpace(); + emit(node.statement); + } + function emitThrowStatement(node) { + emitTokenWithComment(109 /* ThrowKeyword */, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); + writeTrailingSemicolon(); + } + function emitTryStatement(node) { + emitTokenWithComment(111 /* TryKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emit(node.tryBlock); + if (node.catchClause) { + writeLineOrSpace(node, node.tryBlock, node.catchClause); + emit(node.catchClause); + } + if (node.finallyBlock) { + writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock); + emitTokenWithComment(96 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node); + writeSpace(); + emit(node.finallyBlock); + } + } + function emitDebuggerStatement(node) { + writeToken(87 /* DebuggerKeyword */, node.pos, writeKeyword); + writeTrailingSemicolon(); + } + function emitVariableDeclaration(node) { + var _a2, _b, _c, _d, _e; + emit(node.name); + emit(node.exclamationToken); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer, (_e = (_d = (_a2 = node.type) == null ? void 0 : _a2.end) != null ? _d : (_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) != null ? _e : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitVariableDeclarationList(node) { + writeKeyword(isLet(node) ? "let" : isVarConst(node) ? "const" : "var"); + writeSpace(); + emitList(node, node.declarations, 528 /* VariableDeclarationList */); + } + function emitFunctionDeclaration(node) { + emitFunctionDeclarationOrExpression(node); + } + function emitFunctionDeclarationOrExpression(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("function"); + emit(node.asteriskToken); + writeSpace(); + emitIdentifierName(node.name); + emitSignatureAndBody(node, emitSignatureHead); + } + function emitSignatureAndBody(node, emitSignatureHead2) { + const body = node.body; + if (body) { + if (isBlock(body)) { + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + forEach(node.parameters, generateNames); + generateNames(node.body); + emitSignatureHead2(node); + emitBlockFunctionBody(body); + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } else { + emitSignatureHead2(node); + writeSpace(); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); + } + } else { + emitSignatureHead2(node); + writeTrailingSemicolon(); + } + } + function emitSignatureHead(node) { + emitTypeParameters(node, node.typeParameters); + emitParameters(node, node.parameters); + emitTypeAnnotation(node.type); + } + function shouldEmitBlockFunctionBodyOnSingleLine(body) { + if (getEmitFlags(body) & 1 /* SingleLine */) { + return true; + } + if (body.multiLine) { + return false; + } + if (!nodeIsSynthesized(body) && currentSourceFile && !rangeIsOnSingleLine(body, currentSourceFile)) { + return false; + } + if (getLeadingLineTerminatorCount(body, firstOrUndefined(body.statements), 2 /* PreserveLines */) || getClosingLineTerminatorCount(body, lastOrUndefined(body.statements), 2 /* PreserveLines */, body.statements)) { + return false; + } + let previousStatement; + for (const statement of body.statements) { + if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) { + return false; + } + previousStatement = statement; + } + return true; + } + function emitBlockFunctionBody(body) { + onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(body); + writeSpace(); + writePunctuation("{"); + increaseIndent(); + const emitBlockFunctionBody2 = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine : emitBlockFunctionBodyWorker; + emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody2); + decreaseIndent(); + writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode == null ? void 0 : onAfterEmitNode(body); + } + function emitBlockFunctionBodyOnSingleLine(body) { + emitBlockFunctionBodyWorker( + body, + /*emitBlockFunctionBodyOnSingleLine*/ + true + ); + } + function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine2) { + const statementOffset = emitPrologueDirectives(body.statements); + const pos = writer.getTextPos(); + emitHelpers(body); + if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine2) { + decreaseIndent(); + emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); + increaseIndent(); + } else { + emitList( + body, + body.statements, + 1 /* MultiLineFunctionBodyStatements */, + /*parenthesizerRule*/ + void 0, + statementOffset + ); + } + } + function emitClassDeclaration(node) { + emitClassDeclarationOrExpression(node); + } + function emitClassDeclarationOrExpression(node) { + pushPrivateNameGenerationScope( + TempFlags.Auto, + /*newReservedMemberNames*/ + void 0 + ); + forEach(node.members, generateMemberNames); + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + true + ); + emitTokenWithComment(84 /* ClassKeyword */, moveRangePastModifiers(node).pos, writeKeyword, node); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* ClassMembers */); + writePunctuation("}"); + if (indentedFlag) { + decreaseIndent(); + } + popPrivateNameGenerationScope(); + } + function emitInterfaceDeclaration(node) { + pushPrivateNameGenerationScope( + TempFlags.Auto, + /*newReservedMemberNames*/ + void 0 + ); + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("interface"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + emitList(node, node.heritageClauses, 512 /* HeritageClauses */); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 129 /* InterfaceMembers */); + writePunctuation("}"); + popPrivateNameGenerationScope(); + } + function emitTypeAliasDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("type"); + writeSpace(); + emit(node.name); + emitTypeParameters(node, node.typeParameters); + writeSpace(); + writePunctuation("="); + writeSpace(); + emit(node.type); + writeTrailingSemicolon(); + } + function emitEnumDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + writeKeyword("enum"); + writeSpace(); + emit(node.name); + writeSpace(); + writePunctuation("{"); + emitList(node, node.members, 145 /* EnumMembers */); + writePunctuation("}"); + } + function emitModuleDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + if (~node.flags & 1024 /* GlobalAugmentation */) { + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); + } + emit(node.name); + let body = node.body; + if (!body) + return writeTrailingSemicolon(); + while (body && isModuleDeclaration(body)) { + writePunctuation("."); + emit(body.name); + body = body.body; + } + writeSpace(); + emit(body); + } + function emitModuleBlock(node) { + pushNameGenerationScope(node); + forEach(node.statements, generateNames); + emitBlockStatements( + node, + /*forceSingleLine*/ + isEmptyBlock(node) + ); + popNameGenerationScope(node); + } + function emitCaseBlock(node) { + emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emitList(node, node.clauses, 129 /* CaseBlockClauses */); + emitTokenWithComment( + 19 /* CloseBraceToken */, + node.clauses.end, + writePunctuation, + node, + /*indentLeading*/ + true + ); + } + function emitImportEqualsDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emitTokenWithComment(100 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.isTypeOnly) { + emitTokenWithComment(154 /* TypeKeyword */, node.pos, writeKeyword, node); + writeSpace(); + } + emit(node.name); + writeSpace(); + emitTokenWithComment(63 /* EqualsToken */, node.name.end, writePunctuation, node); + writeSpace(); + emitModuleReference(node.moduleReference); + writeTrailingSemicolon(); + } + function emitModuleReference(node) { + if (node.kind === 79 /* Identifier */) { + emitExpression(node); + } else { + emit(node); + } + } + function emitImportDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + emitTokenWithComment(100 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); + writeSpace(); + if (node.importClause) { + emit(node.importClause); + writeSpace(); + emitTokenWithComment(158 /* FromKeyword */, node.importClause.end, writeKeyword, node); + writeSpace(); + } + emitExpression(node.moduleSpecifier); + if (node.assertClause) { + emitWithLeadingSpace(node.assertClause); + } + writeTrailingSemicolon(); + } + function emitImportClause(node) { + if (node.isTypeOnly) { + emitTokenWithComment(154 /* TypeKeyword */, node.pos, writeKeyword, node); + writeSpace(); + } + emit(node.name); + if (node.name && node.namedBindings) { + emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node); + writeSpace(); + } + emit(node.namedBindings); + } + function emitNamespaceImport(node) { + const asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(128 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedImports(node) { + emitNamedImportsOrExports(node); + } + function emitImportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitExportAssignment(node) { + const nextPos = emitTokenWithComment(93 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isExportEquals) { + emitTokenWithComment(63 /* EqualsToken */, nextPos, writeOperator, node); + } else { + emitTokenWithComment(88 /* DefaultKeyword */, nextPos, writeKeyword, node); + } + writeSpace(); + emitExpression(node.expression, node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(63 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault); + writeTrailingSemicolon(); + } + function emitExportDeclaration(node) { + emitDecoratorsAndModifiers( + node, + node.modifiers, + /*allowDecorators*/ + false + ); + let nextPos = emitTokenWithComment(93 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.isTypeOnly) { + nextPos = emitTokenWithComment(154 /* TypeKeyword */, nextPos, writeKeyword, node); + writeSpace(); + } + if (node.exportClause) { + emit(node.exportClause); + } else { + nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node); + } + if (node.moduleSpecifier) { + writeSpace(); + const fromPos = node.exportClause ? node.exportClause.end : nextPos; + emitTokenWithComment(158 /* FromKeyword */, fromPos, writeKeyword, node); + writeSpace(); + emitExpression(node.moduleSpecifier); + } + if (node.assertClause) { + emitWithLeadingSpace(node.assertClause); + } + writeTrailingSemicolon(); + } + function emitAssertClause(node) { + emitTokenWithComment(130 /* AssertKeyword */, node.pos, writeKeyword, node); + writeSpace(); + const elements = node.elements; + emitList(node, elements, 526226 /* ImportClauseEntries */); + } + function emitAssertEntry(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + const value = node.value; + if ((getEmitFlags(value) & 1024 /* NoLeadingComments */) === 0) { + const commentRange = getCommentRange(value); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emit(value); + } + function emitNamespaceExportDeclaration(node) { + let nextPos = emitTokenWithComment(93 /* ExportKeyword */, node.pos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(128 /* AsKeyword */, nextPos, writeKeyword, node); + writeSpace(); + nextPos = emitTokenWithComment(143 /* NamespaceKeyword */, nextPos, writeKeyword, node); + writeSpace(); + emit(node.name); + writeTrailingSemicolon(); + } + function emitNamespaceExport(node) { + const asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node); + writeSpace(); + emitTokenWithComment(128 /* AsKeyword */, asPos, writeKeyword, node); + writeSpace(); + emit(node.name); + } + function emitNamedExports(node) { + emitNamedImportsOrExports(node); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + } + function emitNamedImportsOrExports(node) { + writePunctuation("{"); + emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */); + writePunctuation("}"); + } + function emitImportOrExportSpecifier(node) { + if (node.isTypeOnly) { + writeKeyword("type"); + writeSpace(); + } + if (node.propertyName) { + emit(node.propertyName); + writeSpace(); + emitTokenWithComment(128 /* AsKeyword */, node.propertyName.end, writeKeyword, node); + writeSpace(); + } + emit(node.name); + } + function emitExternalModuleReference(node) { + writeKeyword("require"); + writePunctuation("("); + emitExpression(node.expression); + writePunctuation(")"); + } + function emitJsxElement(node) { + emit(node.openingElement); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingElement); + } + function emitJsxSelfClosingElement(node) { + writePunctuation("<"); + emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); + writeSpace(); + emit(node.attributes); + writePunctuation("/>"); + } + function emitJsxFragment(node) { + emit(node.openingFragment); + emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */); + emit(node.closingFragment); + } + function emitJsxOpeningElementOrFragment(node) { + writePunctuation("<"); + if (isJsxOpeningElement(node)) { + const indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); + emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); + if (node.attributes.properties && node.attributes.properties.length > 0) { + writeSpace(); + } + emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); + } + writePunctuation(">"); + } + function emitJsxText(node) { + writer.writeLiteral(node.text); + } + function emitJsxClosingElementOrFragment(node) { + writePunctuation(""); + } + function emitJsxAttributes(node) { + emitList(node, node.properties, 262656 /* JsxElementAttributes */); + } + function emitJsxAttribute(node) { + emit(node.name); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); + } + function emitJsxSpreadAttribute(node) { + writePunctuation("{..."); + emitExpression(node.expression); + writePunctuation("}"); + } + function hasTrailingCommentsAtPosition(pos) { + let result = false; + forEachTrailingCommentRange((currentSourceFile == null ? void 0 : currentSourceFile.text) || "", pos + 1, () => result = true); + return result; + } + function hasLeadingCommentsAtPosition(pos) { + let result = false; + forEachLeadingCommentRange((currentSourceFile == null ? void 0 : currentSourceFile.text) || "", pos + 1, () => result = true); + return result; + } + function hasCommentsAtPosition(pos) { + return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos); + } + function emitJsxExpression(node) { + var _a2; + if (node.expression || !commentsDisabled && !nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos)) { + const isMultiline = currentSourceFile && !nodeIsSynthesized(node) && getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== getLineAndCharacterOfPosition(currentSourceFile, node.end).line; + if (isMultiline) { + writer.increaseIndent(); + } + const end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node); + emit(node.dotDotDotToken); + emitExpression(node.expression); + emitTokenWithComment(19 /* CloseBraceToken */, ((_a2 = node.expression) == null ? void 0 : _a2.end) || end, writePunctuation, node); + if (isMultiline) { + writer.decreaseIndent(); + } + } + } + function emitJsxTagName(node) { + if (node.kind === 79 /* Identifier */) { + emitExpression(node); + } else { + emit(node); + } + } + function emitCaseClause(node) { + emitTokenWithComment(82 /* CaseKeyword */, node.pos, writeKeyword, node); + writeSpace(); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); + } + function emitDefaultClause(node) { + const pos = emitTokenWithComment(88 /* DefaultKeyword */, node.pos, writeKeyword, node); + emitCaseOrDefaultClauseRest(node, node.statements, pos); + } + function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { + const emitAsSingleStatement = statements.length === 1 && // treat synthesized nodes as located on the same line for emit purposes + (!currentSourceFile || nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + let format = 163969 /* CaseOrDefaultClauseStatements */; + if (emitAsSingleStatement) { + writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode); + writeSpace(); + format &= ~(1 /* MultiLine */ | 128 /* Indented */); + } else { + emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode); + } + emitList(parentNode, statements, format); + } + function emitHeritageClause(node) { + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); + emitList(node, node.types, 528 /* HeritageClauseTypes */); + } + function emitCatchClause(node) { + const openParenPos = emitTokenWithComment(83 /* CatchKeyword */, node.pos, writeKeyword, node); + writeSpace(); + if (node.variableDeclaration) { + emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); + emit(node.variableDeclaration); + emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node); + writeSpace(); + } + emit(node.block); + } + function emitPropertyAssignment(node) { + emit(node.name); + writePunctuation(":"); + writeSpace(); + const initializer = node.initializer; + if ((getEmitFlags(initializer) & 1024 /* NoLeadingComments */) === 0) { + const commentRange = getCommentRange(initializer); + emitTrailingCommentsOfPosition(commentRange.pos); + } + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitShorthandPropertyAssignment(node) { + emit(node.name); + if (node.objectAssignmentInitializer) { + writeSpace(); + writePunctuation("="); + writeSpace(); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + } + function emitSpreadAssignment(node) { + if (node.expression) { + emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + } + function emitEnumMember(node) { + emit(node.name); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + } + function emitJSDoc(node) { + write("/**"); + if (node.comment) { + const text = getTextOfJSDocComment(node.comment); + if (text) { + const lines = text.split(/\r\n?|\n/g); + for (const line of lines) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === 347 /* JSDocTypeTag */ && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } else { + emitList(node, node.tags, 33 /* JSDocComment */); + } + } + writeSpace(); + write("*/"); + } + function emitJSDocSimpleTypedTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + function emitJSDocSeeTag(tag) { + emitJSDocTagName(tag.tagName); + emit(tag.name); + emitJSDocComment(tag.comment); + } + function emitJSDocNameReference(node) { + writeSpace(); + writePunctuation("{"); + emit(node.name); + writePunctuation("}"); + } + function emitJSDocHeritageTag(tag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + function emitJSDocTemplateTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, 528 /* CommaListElements */); + emitJSDocComment(tag.comment); + } + function emitJSDocTypedefTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === 312 /* JSDocTypeExpression */) { + emitJSDocTypeExpression(tag.typeExpression); + } else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === 325 /* JSDocTypeLiteral */) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + function emitJSDocCallbackTag(tag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocOverloadTag(tag) { + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + function emitJSDocSimpleTag(tag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + function emitJSDocTypeLiteral(lit) { + emitList(lit, factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); + } + function emitJSDocSignature(sig) { + if (sig.typeParameters) { + emitList(sig, factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); + } + if (sig.parameters) { + emitList(sig, factory.createNodeArray(sig.parameters), 33 /* JSDocComment */); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + function emitJSDocPropertyLikeTag(param) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + function emitJSDocTagName(tagName) { + writePunctuation("@"); + emit(tagName); + } + function emitJSDocComment(comment) { + const text = getTextOfJSDocComment(comment); + if (text) { + writeSpace(); + write(text); + } + } + function emitJSDocTypeExpression(typeExpression) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + function emitSourceFile(node) { + writeLine(); + const statements = node.statements; + const shouldEmitDetachedComment = statements.length === 0 || !isPrologueDirective(statements[0]) || nodeIsSynthesized(statements[0]); + if (shouldEmitDetachedComment) { + emitBodyWithDetachedComments(node, statements, emitSourceFileWorker); + return; + } + emitSourceFileWorker(node); + } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); + for (const prepend of node.prepends) { + if (isUnparsedSource(prepend) && prepend.syntheticReferences) { + for (const ref of prepend.syntheticReferences) { + emit(ref); + writeLine(); + } + } + } + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs2) { + if (hasNoDefaultLib) { + const pos = writer.getTextPos(); + writeComment(`/// `); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ }); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + writeComment(`/// `); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (const dep of currentSourceFile.amdDependencies) { + if (dep.name) { + writeComment(`/// `); + } else { + writeComment(`/// `); + } + writeLine(); + } + } + for (const directive of files) { + const pos = writer.getTextPos(); + writeComment(`/// `); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); + writeLine(); + } + for (const directive of types) { + const pos = writer.getTextPos(); + const resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile == null ? void 0 : currentSourceFile.impliedNodeFormat) ? `resolution-mode="${directive.resolutionMode === 99 /* ESNext */ ? "import" : "require"}"` : ""; + writeComment(`/// `); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: !directive.resolutionMode ? "type" /* Type */ : directive.resolutionMode === 99 /* ESNext */ ? "type-import" /* TypeResolutionModeImport */ : "type-require" /* TypeResolutionModeRequire */, data: directive.fileName }); + writeLine(); + } + for (const directive of libs2) { + const pos = writer.getTextPos(); + writeComment(`/// `); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName }); + writeLine(); + } + } + function emitSourceFileWorker(node) { + const statements = node.statements; + pushNameGenerationScope(node); + forEach(node.statements, generateNames); + emitHelpers(node); + const index = findIndex(statements, (statement) => !isPrologueDirective(statement)); + emitTripleSlashDirectivesIfNeeded(node); + emitList( + node, + statements, + 1 /* MultiLine */, + /*parenthesizerRule*/ + void 0, + index === -1 ? statements.length : index + ); + popNameGenerationScope(node); + } + function emitPartiallyEmittedExpression(node) { + const emitFlags = getEmitFlags(node); + if (!(emitFlags & 1024 /* NoLeadingComments */) && node.pos !== node.expression.pos) { + emitTrailingCommentsOfPosition(node.expression.pos); + } + emitExpression(node.expression); + if (!(emitFlags & 2048 /* NoTrailingComments */) && node.end !== node.expression.end) { + emitLeadingCommentsOfPosition(node.expression.end); + } + } + function emitCommaList(node) { + emitExpressionList( + node, + node.elements, + 528 /* CommaListElements */, + /*parenthesizerRule*/ + void 0 + ); + } + function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) { + let needsToSetSourceFile = !!sourceFile; + for (let i = 0; i < statements.length; i++) { + const statement = statements[i]; + if (isPrologueDirective(statement)) { + const shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; + if (shouldEmitPrologueDirective) { + if (needsToSetSourceFile) { + needsToSetSourceFile = false; + setSourceFile(sourceFile); + } + writeLine(); + const pos = writer.getTextPos(); + emit(statement); + if (recordBundleFileSection && bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text }); + if (seenPrologueDirectives) { + seenPrologueDirectives.add(statement.expression.text); + } + } + } else { + return i; + } + } + return statements.length; + } + function emitUnparsedPrologues(prologues, seenPrologueDirectives) { + for (const prologue of prologues) { + if (!seenPrologueDirectives.has(prologue.data)) { + writeLine(); + const pos = writer.getTextPos(); + emit(prologue); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data }); + if (seenPrologueDirectives) { + seenPrologueDirectives.add(prologue.data); + } + } + } + } + function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { + if (isSourceFile(sourceFileOrBundle)) { + emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle); + } else { + const seenPrologueDirectives = /* @__PURE__ */ new Set(); + for (const prepend of sourceFileOrBundle.prepends) { + emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives); + } + for (const sourceFile of sourceFileOrBundle.sourceFiles) { + emitPrologueDirectives( + sourceFile.statements, + sourceFile, + seenPrologueDirectives, + /*recordBundleFileSection*/ + true + ); + } + setSourceFile(void 0); + } + } + function getPrologueDirectivesFromBundledSourceFiles(bundle) { + const seenPrologueDirectives = /* @__PURE__ */ new Set(); + let prologues; + for (let index = 0; index < bundle.sourceFiles.length; index++) { + const sourceFile = bundle.sourceFiles[index]; + let directives; + let end = 0; + for (const statement of sourceFile.statements) { + if (!isPrologueDirective(statement)) + break; + if (seenPrologueDirectives.has(statement.expression.text)) + continue; + seenPrologueDirectives.add(statement.expression.text); + (directives || (directives = [])).push({ + pos: statement.pos, + end: statement.end, + expression: { + pos: statement.expression.pos, + end: statement.expression.end, + text: statement.expression.text + } + }); + end = end < statement.end ? statement.end : end; + } + if (directives) + (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives }); + } + return prologues; + } + function emitShebangIfNeeded(sourceFileOrBundle) { + if (isSourceFile(sourceFileOrBundle) || isUnparsedSource(sourceFileOrBundle)) { + const shebang = getShebang(sourceFileOrBundle.text); + if (shebang) { + writeComment(shebang); + writeLine(); + return true; + } + } else { + for (const prepend of sourceFileOrBundle.prepends) { + Debug.assertNode(prepend, isUnparsedSource); + if (emitShebangIfNeeded(prepend)) { + return true; + } + } + for (const sourceFile of sourceFileOrBundle.sourceFiles) { + if (emitShebangIfNeeded(sourceFile)) { + return true; + } + } + } + } + function emitNodeWithWriter(node, writer2) { + if (!node) + return; + const savedWrite = write; + write = writer2; + emit(node); + write = savedWrite; + } + function emitDecoratorsAndModifiers(node, modifiers, allowDecorators) { + if (modifiers == null ? void 0 : modifiers.length) { + if (every(modifiers, isModifier)) { + return emitModifierList(node, modifiers); + } + if (every(modifiers, isDecorator)) { + if (allowDecorators) { + return emitDecoratorList(node, modifiers); + } + return node.pos; + } + onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(modifiers); + let lastMode; + let mode; + let start = 0; + let pos = 0; + let lastModifier; + while (start < modifiers.length) { + while (pos < modifiers.length) { + lastModifier = modifiers[pos]; + mode = isDecorator(lastModifier) ? "decorators" : "modifiers"; + if (lastMode === void 0) { + lastMode = mode; + } else if (mode !== lastMode) { + break; + } + pos++; + } + const textRange = { pos: -1, end: -1 }; + if (start === 0) + textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) + textRange.end = modifiers.end; + if (lastMode === "modifiers" || allowDecorators) { + emitNodeListItems( + emit, + node, + modifiers, + lastMode === "modifiers" ? 2359808 /* Modifiers */ : 2146305 /* Decorators */, + /*parenthesizerRule*/ + void 0, + start, + pos - start, + /*hasTrailingComma*/ + false, + textRange + ); + } + start = pos; + lastMode = mode; + pos++; + } + onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(modifiers); + if (lastModifier && !positionIsSynthesized(lastModifier.end)) { + return lastModifier.end; + } + } + return node.pos; + } + function emitModifierList(node, modifiers) { + emitList(node, modifiers, 2359808 /* Modifiers */); + const lastModifier = lastOrUndefined(modifiers); + return lastModifier && !positionIsSynthesized(lastModifier.end) ? lastModifier.end : node.pos; + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { + if (node) { + writeSpace(); + emitTokenWithComment(63 /* EqualsToken */, equalCommentStartPos, writeOperator, container); + writeSpace(); + emitExpression(node, parenthesizerRule); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit2) { + if (node) { + prefixWriter(prefix); + emit2(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { + if (node) { + writeSpace(); + emitExpression(node, parenthesizerRule); + } + } + function emitWithTrailingSpace(node) { + if (node) { + emit(node); + writeSpace(); + } + } + function emitEmbeddedStatement(parent, node) { + if (isBlock(node) || getEmitFlags(parent) & 1 /* SingleLine */) { + writeSpace(); + emit(node); + } else { + writeLine(); + increaseIndent(); + if (isEmptyStatement(node)) { + pipelineEmit(5 /* EmbeddedStatement */, node); + } else { + emit(node); + } + decreaseIndent(); + } + } + function emitDecoratorList(parentNode, decorators) { + emitList(parentNode, decorators, 2146305 /* Decorators */); + const lastDecorator = lastOrUndefined(decorators); + return lastDecorator && !positionIsSynthesized(lastDecorator.end) ? lastDecorator.end : parentNode.pos; + } + function emitTypeArguments(parentNode, typeArguments) { + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, typeArgumentParenthesizerRuleSelector); + } + function emitTypeParameters(parentNode, typeParameters) { + if (isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + } + function emitParameters(parentNode, parameters) { + emitList(parentNode, parameters, 2576 /* Parameters */); + } + function canEmitSimpleArrowHead(parentNode, parameters) { + const parameter = singleOrUndefined(parameters); + return parameter && parameter.pos === parentNode.pos && isArrowFunction(parentNode) && !parentNode.type && !some(parentNode.modifiers) && !some(parentNode.typeParameters) && !some(parameter.modifiers) && !parameter.dotDotDotToken && !parameter.questionToken && !parameter.type && !parameter.initializer && isIdentifier(parameter.name); + } + function emitParametersForArrow(parentNode, parameters) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { + emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */); + } else { + emitParameters(parentNode, parameters); + } + } + function emitParametersForIndexSignature(parentNode, parameters) { + emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); + } + function writeDelimiter(format) { + switch (format & 60 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList( + emit, + parentNode, + children, + format | (parentNode && getEmitFlags(parentNode) & 2 /* MultiLine */ ? 65536 /* PreferNewLine */ : 0), + parenthesizerRule, + start, + count + ); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit2, parentNode, children, format, parenthesizerRule, start = 0, count = children ? children.length - start : 0) { + const isUndefined = children === void 0; + if (isUndefined && format & 16384 /* OptionalIfUndefined */) { + return; + } + const isEmpty = children === void 0 || start >= children.length || count === 0; + if (isEmpty && format & 32768 /* OptionalIfEmpty */) { + onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children); + onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(children); + return; + } + if (format & 15360 /* BracketsMask */) { + writePunctuation(getOpeningBracket(format)); + if (isEmpty && children) { + emitTrailingCommentsOfPosition( + children.pos, + /*prefixSpace*/ + true + ); + } + } + onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children); + if (isEmpty) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile)))) { + writeLine(); + } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { + writeSpace(); + } + } else { + emitNodeListItems(emit2, parentNode, children, format, parenthesizerRule, start, count, children.hasTrailingComma, children); + } + onAfterEmitNodeArray == null ? void 0 : onAfterEmitNodeArray(children); + if (format & 15360 /* BracketsMask */) { + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); + } + writePunctuation(getClosingBracket(format)); + } + } + function emitNodeListItems(emit2, parentNode, children, format, parenthesizerRule, start, count, hasTrailingComma, childrenTextRange) { + const mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; + let shouldEmitInterveningComments = mayEmitInterveningComments; + const leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children[start], format); + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); + shouldEmitInterveningComments = false; + } else if (format & 256 /* SpaceBetweenBraces */) { + writeSpace(); + } + if (format & 128 /* Indented */) { + increaseIndent(); + } + const emitListItem = getEmitListItem(emit2, parenthesizerRule); + let previousSibling; + let previousSourceFileTextKind; + let shouldDecreaseIndentAfterEmit = false; + for (let i = 0; i < count; i++) { + const child = children[start + i]; + if (format & 32 /* AsteriskDelimited */) { + writeLine(); + writeDelimiter(format); + } else if (previousSibling) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { + const previousSiblingEmitFlags = getEmitFlags(previousSibling); + if (!(previousSiblingEmitFlags & 2048 /* NoTrailingComments */)) { + emitLeadingCommentsOfPosition(previousSibling.end); + } + } + writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + const separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { + if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { + increaseIndent(); + shouldDecreaseIndentAfterEmit = true; + } + writeLine(separatingLineTerminatorCount); + shouldEmitInterveningComments = false; + } else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { + writeSpace(); + } + } + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); + if (shouldEmitInterveningComments) { + const commentRange = getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); + } else { + shouldEmitInterveningComments = mayEmitInterveningComments; + } + nextListElementPos = child.pos; + emitListItem(child, emit2, parenthesizerRule, i); + if (shouldDecreaseIndentAfterEmit) { + decreaseIndent(); + shouldDecreaseIndentAfterEmit = false; + } + previousSibling = child; + } + const emitFlags = previousSibling ? getEmitFlags(previousSibling) : 0; + const skipTrailingComments = commentsDisabled || !!(emitFlags & 2048 /* NoTrailingComments */); + const emitTrailingComma = hasTrailingComma && format & 64 /* AllowTrailingComma */ && format & 16 /* CommaDelimited */; + if (emitTrailingComma) { + if (previousSibling && !skipTrailingComments) { + emitTokenWithComment(27 /* CommaToken */, previousSibling.end, writePunctuation, previousSibling); + } else { + writePunctuation(","); + } + } + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && format & 60 /* DelimitersMask */ && !skipTrailingComments) { + emitLeadingCommentsOfPosition(emitTrailingComma && (childrenTextRange == null ? void 0 : childrenTextRange.end) ? childrenTextRange.end : previousSibling.end); + } + if (format & 128 /* Indented */) { + decreaseIndent(); + } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); + const closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children[start + count - 1], format, childrenTextRange); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); + } else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { + writeSpace(); + } + } + function writeLiteral(s) { + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + writer.writeStringLiteral(s); + } + function writeBase(s) { + writer.write(s); + } + function writeSymbol(s, sym) { + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + writer.writePunctuation(s); + } + function writeTrailingSemicolon() { + writer.writeTrailingSemicolon(";"); + } + function writeKeyword(s) { + writer.writeKeyword(s); + } + function writeOperator(s) { + writer.writeOperator(s); + } + function writeParameter(s) { + writer.writeParameter(s); + } + function writeComment(s) { + writer.writeComment(s); + } + function writeSpace() { + writer.writeSpace(" "); + } + function writeProperty(s) { + writer.writeProperty(s); + } + function nonEscapingWrite(s) { + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } else { + writer.write(s); + } + } + function writeLine(count = 1) { + for (let i = 0; i < count; i++) { + writer.writeLine(i > 0); + } + } + function increaseIndent() { + writer.increaseIndent(); + } + function decreaseIndent() { + writer.decreaseIndent(); + } + function writeToken(token, pos, writer2, contextNode) { + return !sourceMapsDisabled ? emitTokenWithSourceMap(contextNode, token, writer2, pos, writeTokenText) : writeTokenText(token, writer2, pos); + } + function writeTokenNode(node, writer2) { + if (onBeforeEmitToken) { + onBeforeEmitToken(node); + } + writer2(tokenToString(node.kind)); + if (onAfterEmitToken) { + onAfterEmitToken(node); + } + } + function writeTokenText(token, writer2, pos) { + const tokenString = tokenToString(token); + writer2(tokenString); + return pos < 0 ? pos : pos + tokenString.length; + } + function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) { + if (getEmitFlags(parentNode) & 1 /* SingleLine */) { + writeSpace(); + } else if (preserveSourceNewlines) { + const lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode); + if (lines) { + writeLine(lines); + } else { + writeSpace(); + } + } else { + writeLine(); + } + } + function writeLines(text) { + const lines = text.split(/\r\n?|\n/g); + const indentation = guessIndentation(lines); + for (const lineText of lines) { + const line = indentation ? lineText.slice(indentation) : lineText; + if (line.length) { + writeLine(); + write(line); + } + } + } + function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) { + if (lineCount) { + increaseIndent(); + writeLine(lineCount); + } else if (writeSpaceIfNotIndenting) { + writeSpace(); + } + } + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function getLeadingLineTerminatorCount(parentNode, firstChild, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { + if (format & 65536 /* PreferNewLine */) { + return 1; + } + if (firstChild === void 0) { + return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + } + if (firstChild.pos === nextListElementPos) { + return 0; + } + if (firstChild.kind === 11 /* JsxText */) { + return 0; + } + if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode))) { + if (preserveSourceNewlines) { + return getEffectiveLines( + (includeComments) => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter( + firstChild.pos, + parentNode.pos, + currentSourceFile, + includeComments + ) + ); + } + return rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; + } + if (synthesizedNodeStartsOnNewLine(firstChild, format)) { + return 1; + } + } + return format & 1 /* MultiLine */ ? 1 : 0; + } + function getSeparatingLineTerminatorCount(previousNode, nextNode, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { + if (previousNode === void 0 || nextNode === void 0) { + return 0; + } + if (nextNode.kind === 11 /* JsxText */) { + return 0; + } else if (currentSourceFile && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) { + if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines( + (includeComments) => getLinesBetweenRangeEndAndRangeStart( + previousNode, + nextNode, + currentSourceFile, + includeComments + ) + ); + } else if (!preserveSourceNewlines && originalNodesHaveSameParent(previousNode, nextNode)) { + return rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; + } + return format & 65536 /* PreferNewLine */ ? 1 : 0; + } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { + return 1; + } + } else if (getStartsOnNewLine(nextNode)) { + return 1; + } + return format & 1 /* MultiLine */ ? 1 : 0; + } + function getClosingLineTerminatorCount(parentNode, lastChild, format, childrenTextRange) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { + if (format & 65536 /* PreferNewLine */) { + return 1; + } + if (lastChild === void 0) { + return !parentNode || currentSourceFile && rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + } + if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (preserveSourceNewlines) { + const end = childrenTextRange && !positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; + return getEffectiveLines( + (includeComments) => getLinesBetweenPositionAndNextNonWhitespaceCharacter( + end, + parentNode.end, + currentSourceFile, + includeComments + ) + ); + } + return rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; + } + if (synthesizedNodeStartsOnNewLine(lastChild, format)) { + return 1; + } + } + if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) { + return 1; + } + return 0; + } + function getEffectiveLines(getLineDifference) { + Debug.assert(!!preserveSourceNewlines); + const lines = getLineDifference( + /*includeComments*/ + true + ); + if (lines === 0) { + return getLineDifference( + /*includeComments*/ + false + ); + } + return lines; + } + function writeLineSeparatorsAndIndentBefore(node, parent) { + const leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, node, 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent( + leadingNewlines, + /*writeSpaceIfNotIndenting*/ + false + ); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + const trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount( + parent, + node, + 0 /* None */, + /*childrenTextRange*/ + void 0 + ); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } + function synthesizedNodeStartsOnNewLine(node, format) { + if (nodeIsSynthesized(node)) { + const startsOnNewLine = getStartsOnNewLine(node); + if (startsOnNewLine === void 0) { + return (format & 65536 /* PreferNewLine */) !== 0; + } + return startsOnNewLine; + } + return (format & 65536 /* PreferNewLine */) !== 0; + } + function getLinesBetweenNodes(parent, node1, node2) { + if (getEmitFlags(parent) & 262144 /* NoIndentation */) { + return 0; + } + parent = skipSynthesizedParentheses(parent); + node1 = skipSynthesizedParentheses(node1); + node2 = skipSynthesizedParentheses(node2); + if (getStartsOnNewLine(node2)) { + return 1; + } + if (currentSourceFile && !nodeIsSynthesized(parent) && !nodeIsSynthesized(node1) && !nodeIsSynthesized(node2)) { + if (preserveSourceNewlines) { + return getEffectiveLines( + (includeComments) => getLinesBetweenRangeEndAndRangeStart( + node1, + node2, + currentSourceFile, + includeComments + ) + ); + } + return rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1; + } + return 0; + } + function isEmptyBlock(block) { + return block.statements.length === 0 && (!currentSourceFile || rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile)); + } + function skipSynthesizedParentheses(node) { + while (node.kind === 214 /* ParenthesizedExpression */ && nodeIsSynthesized(node)) { + node = node.expression; + } + return node; + } + function getTextOfNode2(node, includeTrivia) { + if (isGeneratedIdentifier(node) || isGeneratedPrivateIdentifier(node)) { + return generateName(node); + } + if (isStringLiteral(node) && node.textSourceNode) { + return getTextOfNode2(node.textSourceNode, includeTrivia); + } + const sourceFile = currentSourceFile; + const canUseSourceFile = !!sourceFile && !!node.parent && !nodeIsSynthesized(node); + if (isMemberName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return idText(node); + } + } else { + Debug.assertNode(node, isLiteralExpression); + if (!canUseSourceFile) { + return node.text; + } + } + return getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia); + } + function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { + if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) { + const textSourceNode = node.textSourceNode; + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { + const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + } else { + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); + } + } + const flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0) | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0) | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0) | (printerOptions.target && printerOptions.target === 99 /* ESNext */ ? 8 /* AllowNumericSeparator */ : 0); + return getLiteralText(node, currentSourceFile, flags); + } + function pushNameGenerationScope(node) { + if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { + return; + } + tempFlagsStack.push(tempFlags); + tempFlags = TempFlags.Auto; + formattedNameTempFlagsStack.push(formattedNameTempFlags); + formattedNameTempFlags = void 0; + reservedNamesStack.push(reservedNames); + } + function popNameGenerationScope(node) { + if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { + return; + } + tempFlags = tempFlagsStack.pop(); + formattedNameTempFlags = formattedNameTempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === lastOrUndefined(reservedNamesStack)) { + reservedNames = /* @__PURE__ */ new Set(); + } + reservedNames.add(name); + } + function pushPrivateNameGenerationScope(newPrivateNameTempFlags, newReservedMemberNames) { + privateNameTempFlagsStack.push(privateNameTempFlags); + privateNameTempFlags = newPrivateNameTempFlags; + reservedPrivateNamesStack.push(reservedNames); + reservedPrivateNames = newReservedMemberNames; + } + function popPrivateNameGenerationScope() { + privateNameTempFlags = privateNameTempFlagsStack.pop(); + reservedPrivateNames = reservedPrivateNamesStack.pop(); + } + function reservePrivateNameInNestedScopes(name) { + if (!reservedPrivateNames || reservedPrivateNames === lastOrUndefined(reservedPrivateNamesStack)) { + reservedPrivateNames = /* @__PURE__ */ new Set(); + } + reservedPrivateNames.add(name); + } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 238 /* Block */: + forEach(node.statements, generateNames); + break; + case 253 /* LabeledStatement */: + case 251 /* WithStatement */: + case 243 /* DoStatement */: + case 244 /* WhileStatement */: + generateNames(node.statement); + break; + case 242 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 245 /* ForStatement */: + case 247 /* ForOfStatement */: + case 246 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 252 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 266 /* CaseBlock */: + forEach(node.clauses, generateNames); + break; + case 292 /* CaseClause */: + case 293 /* DefaultClause */: + forEach(node.statements, generateNames); + break; + case 255 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 295 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 240 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 258 /* VariableDeclarationList */: + forEach(node.declarations, generateNames); + break; + case 257 /* VariableDeclaration */: + case 166 /* Parameter */: + case 205 /* BindingElement */: + case 260 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 259 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { + forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 203 /* ObjectBindingPattern */: + case 204 /* ArrayBindingPattern */: + forEach(node.elements, generateNames); + break; + case 269 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 270 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 271 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 277 /* NamespaceExport */: + generateNameIfNeeded(node.name); + break; + case 272 /* NamedImports */: + forEach(node.elements, generateNames); + break; + case 273 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 299 /* PropertyAssignment */: + case 300 /* ShorthandPropertyAssignment */: + case 169 /* PropertyDeclaration */: + case 171 /* MethodDeclaration */: + case 174 /* GetAccessor */: + case 175 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (isGeneratedIdentifier(name) || isGeneratedPrivateIdentifier(name)) { + generateName(name); + } else if (isBindingPattern(name)) { + generateNames(name); + } + } + } + function generateName(name) { + const autoGenerate = name.emitNode.autoGenerate; + if ((autoGenerate.flags & 7 /* KindMask */) === 4 /* Node */) { + return generateNameCached(getNodeForGeneratedName(name), isPrivateIdentifier(name), autoGenerate.flags, autoGenerate.prefix, autoGenerate.suffix); + } else { + const autoGenerateId = autoGenerate.id; + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); + } + } + function generateNameCached(node, privateName, flags, prefix, suffix) { + const nodeId = getNodeId(node); + const cache = privateName ? nodeIdToGeneratedPrivateName : nodeIdToGeneratedName; + return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags != null ? flags : 0 /* None */, formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix))); + } + function isUniqueName(name, privateName) { + return isFileLevelUniqueName2(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); + } + function isReservedName(name, privateName) { + return privateName ? !!(reservedPrivateNames == null ? void 0 : reservedPrivateNames.has(name)) : !!(reservedNames == null ? void 0 : reservedNames.has(name)); + } + function isFileLevelUniqueName2(name, _isPrivate) { + return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } + function isUniqueLocalName(name, container) { + for (let node = container; node && isNodeDescendantOf(node, container); node = node.nextContainer) { + if (canHaveLocals(node) && node.locals) { + const local = node.locals.get(escapeLeadingUnderscores(name)); + if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + return false; + } + } + } + return true; + } + function getTempFlags(formattedNameKey) { + var _a2; + switch (formattedNameKey) { + case "": + return tempFlags; + case "#": + return privateNameTempFlags; + default: + return (_a2 = formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) != null ? _a2 : TempFlags.Auto; + } + } + function setTempFlags(formattedNameKey, flags) { + switch (formattedNameKey) { + case "": + tempFlags = flags; + break; + case "#": + privateNameTempFlags = flags; + break; + default: + formattedNameTempFlags != null ? formattedNameTempFlags : formattedNameTempFlags = /* @__PURE__ */ new Map(); + formattedNameTempFlags.set(formattedNameKey, flags); + break; + } + } + function makeTempVariableName(flags, reservedInNestedScopes, privateName, prefix, suffix) { + if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* hash */) { + prefix = prefix.slice(1); + } + const key = formatGeneratedName(privateName, prefix, "", suffix); + let tempFlags2 = getTempFlags(key); + if (flags && !(tempFlags2 & flags)) { + const name = flags === TempFlags._i ? "_i" : "_n"; + const fullName = formatGeneratedName(privateName, prefix, name, suffix); + if (isUniqueName(fullName, privateName)) { + tempFlags2 |= flags; + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (reservedInNestedScopes) { + reserveNameInNestedScopes(fullName); + } + setTempFlags(key, tempFlags2); + return fullName; + } + } + while (true) { + const count = tempFlags2 & TempFlags.CountMask; + tempFlags2++; + if (count !== 8 && count !== 13) { + const name = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + const fullName = formatGeneratedName(privateName, prefix, name, suffix); + if (isUniqueName(fullName, privateName)) { + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (reservedInNestedScopes) { + reserveNameInNestedScopes(fullName); + } + setTempFlags(key, tempFlags2); + return fullName; + } + } + } + } + function makeUniqueName(baseName, checkFn = isUniqueName, optimistic, scoped, privateName, prefix, suffix) { + if (baseName.length > 0 && baseName.charCodeAt(0) === 35 /* hash */) { + baseName = baseName.slice(1); + } + if (prefix.length > 0 && prefix.charCodeAt(0) === 35 /* hash */) { + prefix = prefix.slice(1); + } + if (optimistic) { + const fullName = formatGeneratedName(privateName, prefix, baseName, suffix); + if (checkFn(fullName, privateName)) { + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (scoped) { + reserveNameInNestedScopes(fullName); + } else { + generatedNames.add(fullName); + } + return fullName; + } + } + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + let i = 1; + while (true) { + const fullName = formatGeneratedName(privateName, prefix, baseName + i, suffix); + if (checkFn(fullName, privateName)) { + if (privateName) { + reservePrivateNameInNestedScopes(fullName); + } else if (scoped) { + reserveNameInNestedScopes(fullName); + } else { + generatedNames.add(fullName); + } + return fullName; + } + i++; + } + } + function makeFileLevelOptimisticUniqueName(name) { + return makeUniqueName( + name, + isFileLevelUniqueName2, + /*optimistic*/ + true, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForModuleOrEnum(node) { + const name = getTextOfNode2(node.name); + return isUniqueLocalName(name, tryCast(node, canHaveLocals)) ? name : makeUniqueName( + name, + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForImportOrExportDeclaration(node) { + const expr = getExternalModuleName(node); + const baseName = isStringLiteral(expr) ? makeIdentifierFromModuleName(expr.text) : "module"; + return makeUniqueName( + baseName, + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForExportDefault() { + return makeUniqueName( + "default", + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForClassExpression() { + return makeUniqueName( + "class", + isUniqueName, + /*optimistic*/ + false, + /*scoped*/ + false, + /*privateName*/ + false, + /*prefix*/ + "", + /*suffix*/ + "" + ); + } + function generateNameForMethodOrAccessor(node, privateName, prefix, suffix) { + if (isIdentifier(node.name)) { + return generateNameCached(node.name, privateName); + } + return makeTempVariableName( + TempFlags.Auto, + /*reservedInNestedScopes*/ + false, + privateName, + prefix, + suffix + ); + } + function generateNameForNode(node, privateName, flags, prefix, suffix) { + switch (node.kind) { + case 79 /* Identifier */: + case 80 /* PrivateIdentifier */: + return makeUniqueName( + getTextOfNode2(node), + isUniqueName, + !!(flags & 16 /* Optimistic */), + !!(flags & 8 /* ReservedInNestedScopes */), + privateName, + prefix, + suffix + ); + case 264 /* ModuleDeclaration */: + case 263 /* EnumDeclaration */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForModuleOrEnum(node); + case 269 /* ImportDeclaration */: + case 275 /* ExportDeclaration */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForImportOrExportDeclaration(node); + case 259 /* FunctionDeclaration */: + case 260 /* ClassDeclaration */: { + Debug.assert(!prefix && !suffix && !privateName); + const name = node.name; + if (name && !isGeneratedIdentifier(name)) { + return generateNameForNode( + name, + /*privateName*/ + false, + flags, + prefix, + suffix + ); + } + return generateNameForExportDefault(); + } + case 274 /* ExportAssignment */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForExportDefault(); + case 228 /* ClassExpression */: + Debug.assert(!prefix && !suffix && !privateName); + return generateNameForClassExpression(); + case 171 /* MethodDeclaration */: + case 174 /* GetAccessor */: + case 175 /* SetAccessor */: + return generateNameForMethodOrAccessor(node, privateName, prefix, suffix); + case 164 /* ComputedPropertyName */: + return makeTempVariableName( + TempFlags.Auto, + /*reserveInNestedScopes*/ + true, + privateName, + prefix, + suffix + ); + default: + return makeTempVariableName( + TempFlags.Auto, + /*reserveInNestedScopes*/ + false, + privateName, + prefix, + suffix + ); + } + } + function makeName(name) { + const autoGenerate = name.emitNode.autoGenerate; + const prefix = formatGeneratedNamePart(autoGenerate.prefix, generateName); + const suffix = formatGeneratedNamePart(autoGenerate.suffix); + switch (autoGenerate.flags & 7 /* KindMask */) { + case 1 /* Auto */: + return makeTempVariableName(TempFlags.Auto, !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), isPrivateIdentifier(name), prefix, suffix); + case 2 /* Loop */: + Debug.assertNode(name, isIdentifier); + return makeTempVariableName( + TempFlags._i, + !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), + /*privateName*/ + false, + prefix, + suffix + ); + case 3 /* Unique */: + return makeUniqueName( + idText(name), + autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueName2 : isUniqueName, + !!(autoGenerate.flags & 16 /* Optimistic */), + !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), + isPrivateIdentifier(name), + prefix, + suffix + ); + } + return Debug.fail(`Unsupported GeneratedIdentifierKind: ${Debug.formatEnum( + autoGenerate.flags & 7 /* KindMask */, + GeneratedIdentifierFlags, + /*isFlags*/ + true + )}.`); + } + function pipelineEmitWithComments(hint, node) { + const pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + const savedContainerPos = containerPos; + const savedContainerEnd = containerEnd; + const savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + const emitFlags = getEmitFlags(node); + const commentRange = getCommentRange(node); + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 4096 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + const emitFlags = getEmitFlags(node); + const commentRange = getCommentRange(node); + if (emitFlags & 4096 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + const typeNode = getTypeNode(node); + if (typeNode) { + emitTrailingCommentsOfNode(node, emitFlags, typeNode.pos, typeNode.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { + enterComment(); + hasWrittenComment = false; + const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; + const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + if ((pos > 0 || end > 0) && pos !== end) { + if (!skipLeadingComments) { + emitLeadingComments( + pos, + /*isEmittedNode*/ + node.kind !== 355 /* NotEmittedStatement */ + ); + } + if (!skipLeadingComments || pos >= 0 && (emitFlags & 1024 /* NoLeadingComments */) !== 0) { + containerPos = pos; + } + if (!skipTrailingComments || end >= 0 && (emitFlags & 2048 /* NoTrailingComments */) !== 0) { + containerEnd = end; + if (node.kind === 258 /* VariableDeclarationList */) { + declarationListContainerEnd = end; + } + } + } + forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); + exitComment(); + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + enterComment(); + const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; + forEach(getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); + if ((pos > 0 || end > 0) && pos !== end) { + containerPos = savedContainerPos; + containerEnd = savedContainerEnd; + declarationListContainerEnd = savedDeclarationListContainerEnd; + if (!skipTrailingComments && node.kind !== 355 /* NotEmittedStatement */) { + emitTrailingComments(end); + } + } + exitComment(); + } + function emitLeadingSynthesizedComment(comment) { + if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } else { + writer.writeSpace(" "); + } + } + function emitTrailingSynthesizedComment(comment) { + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + writeSynthesizedComment(comment); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + } + function writeSynthesizedComment(comment) { + const text = formatSynthesizedComment(comment); + const lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? computeLineStarts(text) : void 0; + writeCommentRange(text, lineMap, writer, 0, text.length, newLine); + } + function formatSynthesizedComment(comment) { + return comment.kind === 3 /* MultiLineCommentTrivia */ ? `/*${comment.text}*/` : `//${comment.text}`; + } + function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { + enterComment(); + const { pos, end } = detachedRange; + const emitFlags = getEmitFlags(node); + const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0; + const skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0; + if (!skipLeadingComments) { + emitDetachedCommentsAndUpdateCommentsInfo(detachedRange); + } + exitComment(); + if (emitFlags & 4096 /* NoNestedComments */ && !commentsDisabled) { + commentsDisabled = true; + emitCallback(node); + commentsDisabled = false; + } else { + emitCallback(node); + } + enterComment(); + if (!skipTrailingComments) { + emitLeadingComments( + detachedRange.end, + /*isEmittedNode*/ + true + ); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } + } + exitComment(); + } + function originalNodesHaveSameParent(nodeA, nodeB) { + nodeA = getOriginalNode(nodeA); + return nodeA.parent && nodeA.parent === getOriginalNode(nodeB).parent; + } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = getOriginalNode(previousNode); + nextNode = getOriginalNode(nextNode); + const parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + const parentNodeArray = getContainingNodeArray(previousNode); + const prevNodeIndex = parentNodeArray == null ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== void 0 && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } + function emitLeadingComments(pos, isEmittedNode) { + hasWrittenComment = false; + if (isEmittedNode) { + if (pos === 0 && (currentSourceFile == null ? void 0 : currentSourceFile.isDeclarationFile)) { + forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment); + } else { + forEachLeadingCommentToEmit(pos, emitLeadingComment); + } + } else if (pos === 0) { + forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment); + } + } + function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!isTripleSlashComment(commentPos, commentEnd)) { + emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); + } + } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return isJSDocLikeText(text, pos) || isPinnedComment(text, pos); + } + return true; + } + function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!hasWrittenComment) { + emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); + hasWrittenComment = true; + } + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } else if (kind === 3 /* MultiLineCommentTrivia */) { + writer.writeSpace(" "); + } + } + function emitLeadingCommentsOfPosition(pos) { + if (commentsDisabled || pos === -1) { + return; + } + emitLeadingComments( + pos, + /*isEmittedNode*/ + true + ); + } + function emitTrailingComments(pos) { + forEachTrailingCommentToEmit(pos, emitTrailingComment); + } + function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) + return; + if (!writer.isAtStartOfLine()) { + writer.writeSpace(" "); + } + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } + } + function emitTrailingCommentsOfPosition(pos, prefixSpace, forceNoNewline) { + if (commentsDisabled) { + return; + } + enterComment(); + forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : forceNoNewline ? emitTrailingCommentOfPositionNoNewline : emitTrailingCommentOfPosition); + exitComment(); + } + function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) { + if (!currentSourceFile) + return; + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (kind === 2 /* SingleLineCommentTrivia */) { + writer.writeLine(); + } + } + function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!currentSourceFile) + return; + emitPos(commentPos); + writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); + emitPos(commentEnd); + if (hasTrailingNewLine) { + writer.writeLine(); + } else { + writer.writeSpace(" "); + } + } + function forEachLeadingCommentToEmit(pos, cb) { + if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) { + if (hasDetachedComments(pos)) { + forEachLeadingCommentWithoutDetachedComments(cb); + } else { + forEachLeadingCommentRange( + currentSourceFile.text, + pos, + cb, + /*state*/ + pos + ); + } + } + } + function forEachTrailingCommentToEmit(end, cb) { + if (currentSourceFile && (containerEnd === -1 || end !== containerEnd && end !== declarationListContainerEnd)) { + forEachTrailingCommentRange(currentSourceFile.text, end, cb); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== void 0 && last(detachedCommentsInfo).nodePos === pos; + } + function forEachLeadingCommentWithoutDetachedComments(cb) { + if (!currentSourceFile) + return; + const pos = last(detachedCommentsInfo).detachedCommentEndPos; + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } else { + detachedCommentsInfo = void 0; + } + forEachLeadingCommentRange( + currentSourceFile.text, + pos, + cb, + /*state*/ + pos + ); + } + function emitDetachedCommentsAndUpdateCommentsInfo(range) { + const currentDetachedCommentInfo = currentSourceFile && emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + function emitComment(text, lineMap, writer2, commentPos, commentEnd, newLine2) { + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) + return; + emitPos(commentPos); + writeCommentRange(text, lineMap, writer2, commentPos, commentEnd, newLine2); + emitPos(commentEnd); + } + function isTripleSlashComment(commentPos, commentEnd) { + return !!currentSourceFile && isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); + } + function getParsedSourceMap(node) { + if (node.parsedSourceMap === void 0 && node.sourceMapText !== void 0) { + node.parsedSourceMap = tryParseRawSourceMap(node.sourceMapText) || false; + } + return node.parsedSourceMap || void 0; + } + function pipelineEmitWithSourceMaps(hint, node) { + const pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + const emitFlags = getEmitFlags(node); + const sourceMapRange = getSourceMapRange(node); + if (isUnparsedNode(node)) { + Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); + const parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap( + writer.getLine(), + writer.getColumn(), + parsed, + node.parent.sourceMapPath, + node.parent.getLineAndCharacterOfPosition(node.pos), + node.parent.getLineAndCharacterOfPosition(node.end) + ); + } + } else { + const source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 355 /* NotEmittedStatement */ && (emitFlags & 32 /* NoLeadingSourceMap */) === 0 && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); + } + if (emitFlags & 128 /* NoNestedSourceMaps */) { + sourceMapsDisabled = true; + } + } + } + function emitSourceMapsAfterNode(node) { + const emitFlags = getEmitFlags(node); + const sourceMapRange = getSourceMapRange(node); + if (!isUnparsedNode(node)) { + if (emitFlags & 128 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; + } + if (node.kind !== 355 /* NotEmittedStatement */ && (emitFlags & 64 /* NoTrailingSourceMap */) === 0 && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); + } + } + } + function skipSourceTrivia(source, pos) { + return source.skipTrivia ? source.skipTrivia(pos) : skipTrivia(source.text, pos); + } + function emitPos(pos) { + if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { + return; + } + const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos); + sourceMapGenerator.addMapping( + writer.getLine(), + writer.getColumn(), + sourceMapSourceIndex, + sourceLine, + sourceCharacter, + /*nameIndex*/ + void 0 + ); + } + function emitSourcePos(source, pos) { + if (source !== sourceMapSource) { + const savedSourceMapSource = sourceMapSource; + const savedSourceMapSourceIndex = sourceMapSourceIndex; + setSourceMapSource(source); + emitPos(pos); + resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex); + } else { + emitPos(pos); + } + } + function emitTokenWithSourceMap(node, token, writer2, tokenPos, emitCallback) { + if (sourceMapsDisabled || node && isInJsonFile(node)) { + return emitCallback(token, writer2, tokenPos); + } + const emitNode = node && node.emitNode; + const emitFlags = emitNode && emitNode.flags || 0 /* None */; + const range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + const source = range && range.source || sourceMapSource; + tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos); + if ((emitFlags & 256 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + tokenPos = emitCallback(token, writer2, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 512 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitSourcePos(source, tokenPos); + } + return tokenPos; + } + function setSourceMapSource(source) { + if (sourceMapsDisabled) { + return; + } + sourceMapSource = source; + if (source === mostRecentlyAddedSourceMapSource) { + sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex; + return; + } + if (isJsonSourceMapSource(source)) { + return; + } + sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName); + if (printerOptions.inlineSources) { + sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text); + } + mostRecentlyAddedSourceMapSource = source; + mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex; + } + function resetSourceMapSource(source, sourceIndex) { + sourceMapSource = source; + sourceMapSourceIndex = sourceIndex; + } + function isJsonSourceMapSource(sourceFile) { + return fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } +} +function createBracketsMap() { + const brackets2 = []; + brackets2[1024 /* Braces */] = ["{", "}"]; + brackets2[2048 /* Parenthesis */] = ["(", ")"]; + brackets2[4096 /* AngleBrackets */] = ["<", ">"]; + brackets2[8192 /* SquareBrackets */] = ["[", "]"]; + return brackets2; +} +function getOpeningBracket(format) { + return brackets[format & 15360 /* BracketsMask */][0]; +} +function getClosingBracket(format) { + return brackets[format & 15360 /* BracketsMask */][1]; +} +var TempFlags = /* @__PURE__ */ ((TempFlags2) => { + TempFlags2[TempFlags2["Auto"] = 0] = "Auto"; + TempFlags2[TempFlags2["CountMask"] = 268435455] = "CountMask"; + TempFlags2[TempFlags2["_i"] = 268435456] = "_i"; + return TempFlags2; +})(TempFlags || {}); +function emitListItemNoParenthesizer(node, emit, _parenthesizerRule, _index) { + emit(node); +} +function emitListItemWithParenthesizerRuleSelector(node, emit, parenthesizerRuleSelector, index) { + emit(node, parenthesizerRuleSelector.select(index)); +} +function emitListItemWithParenthesizerRule(node, emit, parenthesizerRule, _index) { + emit(node, parenthesizerRule); +} +function getEmitListItem(emit, parenthesizerRule) { + return emit.length === 1 ? emitListItemNoParenthesizer : typeof parenthesizerRule === "object" ? emitListItemWithParenthesizerRuleSelector : emitListItemWithParenthesizerRule; } // src/compiler/watchUtilities.ts