 2 /* Auto */;
    }
  }
  /** @internal */
  getIncompleteCompletionsCache() {
    return this.incompleteCompletionsCache || (this.incompleteCompletionsCache = createIncompleteCompletionsCache());
  }
};
/** Makes a filename safe to insert in a RegExp */
_ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g;
var ProjectService3 = _ProjectService;
function createIncompleteCompletionsCache() {
  let info;
  return {
    get() {
      return info;
    },
    set(newInfo) {
      info = newInfo;
    },
    clear() {
      info = void 0;
    }
  };
}
function isConfigFile(config) {
  return config.kind !== void 0;
}
function printProjectWithoutFileNames(project) {
  project.print(
    /*writeProjectFileNames*/
    false,
    /*writeFileExplaination*/
    false,
    /*writeFileVersionAndText*/
    false
  );
}

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

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

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

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

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

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

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

// src/server/typingInstallerAdapter.ts
var _TypingsInstallerAdapter = class _TypingsInstallerAdapter {
  constructor(telemetryEnabled, logger, host, globalTypingsCacheLocation, event, maxActiveRequestCount) {
    this.telemetryEnabled = telemetryEnabled;
    this.logger = logger;
    this.host = host;
    this.globalTypingsCacheLocation = globalTypingsCacheLocation;
    this.event = event;
    this.maxActiveRequestCount = maxActiveRequestCount;
    this.activeRequestCount = 0;
    this.requestQueue = createQueue();
    this.requestMap = /* @__PURE__ */ new Map();
    // Maps project name to newest requestQueue entry for that project
    /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */
    this.requestedRegistry = false;
    this.packageInstallId = 0;
  }
  isKnownTypesPackageName(name) {
    var _a;
    const validationResult = ts_JsTyping_exports.validatePackageName(name);
    if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) {
      return false;
    }
    if (!this.requestedRegistry) {
      this.requestedRegistry = true;
      this.installer.send({ kind: "typesRegistry" });
    }
    return !!((_a = this.typesRegistryCache) == null ? void 0 : _a.has(name));
  }
  installPackage(options) {
    this.packageInstallId++;
    const request = { kind: "installPackage", ...options, id: this.packageInstallId };
    const promise = new Promise((resolve, reject) => {
      (this.packageInstalledPromise ?? (this.packageInstalledPromise = /* @__PURE__ */ new Map())).set(this.packageInstallId, { resolve, reject });
    });
    this.installer.send(request);
    return promise;
  }
  attach(projectService) {
    this.projectService = projectService;
    this.installer = this.createInstallerProcess();
  }
  onProjectClosed(p) {
    this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" });
  }
  enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports) {
    const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
    if (this.logger.hasLevel(3 /* verbose */)) {
      this.logger.info(`TIAdapter:: Scheduling throttled operation:${stringifyIndented(request)}`);
    }
    if (this.activeRequestCount < this.maxActiveRequestCount) {
      this.scheduleRequest(request);
    } else {
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`TIAdapter:: Deferring request for: ${request.projectName}`);
      }
      this.requestQueue.enqueue(request);
      this.requestMap.set(request.projectName, request);
    }
  }
  handleMessage(response) {
    var _a, _b;
    if (this.logger.hasLevel(3 /* verbose */)) {
      this.logger.info(`TIAdapter:: Received response:${stringifyIndented(response)}`);
    }
    switch (response.kind) {
      case EventTypesRegistry:
        this.typesRegistryCache = new Map(Object.entries(response.typesRegistry));
        break;
      case ActionPackageInstalled: {
        const promise = (_a = this.packageInstalledPromise) == null ? void 0 : _a.get(response.id);
        Debug.assertIsDefined(promise, "Should find the promise for package install");
        (_b = this.packageInstalledPromise) == null ? void 0 : _b.delete(response.id);
        if (response.success) {
          promise.resolve({ successMessage: response.message });
        } else {
          promise.reject(response.message);
        }
        this.projectService.updateTypingsForProject(response);
        this.event(response, "setTypings");
        break;
      }
      case EventInitializationFailed: {
        const body = {
          message: response.message
        };
        const eventName = "typesInstallerInitializationFailed";
        this.event(body, eventName);
        break;
      }
      case EventBeginInstallTypes: {
        const body = {
          eventId: response.eventId,
          packages: response.packagesToInstall
        };
        const eventName = "beginInstallTypes";
        this.event(body, eventName);
        break;
      }
      case EventEndInstallTypes: {
        if (this.telemetryEnabled) {
          const body2 = {
            telemetryEventName: "typingsInstalled",
            payload: {
              installedPackages: response.packagesToInstall.join(","),
              installSuccess: response.installSuccess,
              typingsInstallerVersion: response.typingsInstallerVersion
            }
          };
          const eventName2 = "telemetry";
          this.event(body2, eventName2);
        }
        const body = {
          eventId: response.eventId,
          packages: response.packagesToInstall,
          success: response.installSuccess
        };
        const eventName = "endInstallTypes";
        this.event(body, eventName);
        break;
      }
      case ActionInvalidate: {
        this.projectService.updateTypingsForProject(response);
        break;
      }
      case ActionSet: {
        if (this.activeRequestCount > 0) {
          this.activeRequestCount--;
        } else {
          Debug.fail("TIAdapter:: Received too many responses");
        }
        while (!this.requestQueue.isEmpty()) {
          const queuedRequest = this.requestQueue.dequeue();
          if (this.requestMap.get(queuedRequest.projectName) === queuedRequest) {
            this.requestMap.delete(queuedRequest.projectName);
            this.scheduleRequest(queuedRequest);
            break;
          }
          if (this.logger.hasLevel(3 /* verbose */)) {
            this.logger.info(`TIAdapter:: Skipping defunct request for: ${queuedRequest.projectName}`);
          }
        }
        this.projectService.updateTypingsForProject(response);
        this.event(response, "setTypings");
        break;
      }
      case ActionWatchTypingLocations:
        this.projectService.watchTypingLocations(response);
        break;
      default:
        assertType(response);
    }
  }
  scheduleRequest(request) {
    if (this.logger.hasLevel(3 /* verbose */)) {
      this.logger.info(`TIAdapter:: Scheduling request for: ${request.projectName}`);
    }
    this.activeRequestCount++;
    this.host.setTimeout(
      () => {
        if (this.logger.hasLevel(3 /* verbose */)) {
          this.logger.info(`TIAdapter:: Sending request:${stringifyIndented(request)}`);
        }
        this.installer.send(request);
      },
      _TypingsInstallerAdapter.requestDelayMillis,
      `${request.projectName}::${request.kind}`
    );
  }
};
// This number is essentially arbitrary.  Processing more than one typings request
// at a time makes sense, but having too many in the pipe results in a hang
// (see https://github.com/nodejs/node/issues/7657).
// It would be preferable to base our limit on the amount of space left in the
// buffer, but we have yet to find a way to retrieve that value.
_TypingsInstallerAdapter.requestDelayMillis = 100;
var TypingsInstallerAdapter = _TypingsInstallerAdapter;

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

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

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

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