Skip to content

⬅️ Back to Table of Contents

📄 createParseSettings

📊 Analysis Summary

Metric Count
🔧 Functions 6
📦 Imports 18
📊 Variables & Constants 3

📚 Table of Contents

🛠️ File Location:

📂 packages/typescript-estree/src/parseSettings/createParseSettings.ts

📦 Imports

Name Source
CreateProjectServiceSettings @typescript-eslint/project-service
ProjectServiceAndMetadata @typescript-eslint/project-service
ProjectServiceOptions @typescript-eslint/types
createProjectService @typescript-eslint/project-service
debug debug
path node:path
TSESTreeOptions ../parser-options
MutableParseSettings ./index
ensureAbsolutePath ../create-program/shared
validateDefaultProjectForFilesGlob ../create-program/validateDefaultProjectForFilesGlob
isSourceFile ../source-files
getInferredTSConfigRootDir ./candidateTSConfigRootDirs
DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS ./ExpiringCache
ExpiringCache ./ExpiringCache
getProjectConfigFiles ./getProjectConfigFiles
inferSingleRun ./inferSingleRun
resolveProjectList ./resolveProjectList
handleUnsupportedTSVersion ./warnAboutTSVersion

Variables & Constants

Name Type Kind Value Exported
TSCONFIG_MATCH_CACHE ExpiringCache<string, string> \| null let/var *not shown*
TSSERVER_PROJECT_SERVICE ProjectServiceAndMetadata \| null let/var null
JSDocParsingMode { readonly ParseAll: any; readonly Pa... const { ParseAll: ts.JSDocParsingMode?.ParseAll, ParseForTypeErrors: ts.JSDocParsin...

Functions

createParseSettings(code: string | ts.SourceFile, tsestreeOptions: Partial<TSESTreeOptions>): MutableParseSettings

Parameters:

  • code string | ts.SourceFile
  • tsestreeOptions Partial<TSESTreeOptions>

Returns: MutableParseSettings

Calls:

  • enforceCodeString
  • inferSingleRun (from ./inferSingleRun)
  • complex_call_2252
  • getInferredTSConfigRootDir (from ./candidateTSConfigRootDirs)
  • path.resolve
  • JSON.stringify
  • path.isAbsolute
  • /^[a-zA-Z]:/.test
  • ensureAbsolutePath (from ../create-program/shared)
  • getFileName
  • path.extname(filePath).toLowerCase
  • complex_call_4347
  • Array.isArray
  • tsestreeOptions.extraFileExtensions.every
  • populateProjectService
  • parseSettings.debugLevel.has
  • namespaces.push
  • debug.enabled
  • debug.enable
  • namespaces.join
  • log
  • resolveProjectList (from ./resolveProjectList)
  • getProjectConfigFiles (from ./getProjectConfigFiles)
  • handleUnsupportedTSVersion (from ./warnAboutTSVersion)

Internal Comments:

// Ensure it's fully absolute with a drive letter if windows
// Deal with any funny business around trailing path separators (a/b/) or relative path segments (/a/b/../c)
// Since we already know it's absolute, we can safely use path.resolve here.
// TODO: Eventually, parse settings will be validated more thoroughly.
// https://github.com/typescript-eslint/typescript-eslint/issues/6403
// debug doesn't support multiple `enable` calls, so have to do it all at once
// make sure we don't turn off the eslint debug if it was enabled via --debug (x3)
// https://github.com/eslint/eslint/blob/9dfc8501fb1956c90dc11e6377b4cb38a6bea65d/bin/eslint.js#L25 (x4)
// Providing a program or project service overrides project resolution
// No type-aware linting which means that cross-file (or even same-file) JSDoc is useless
// So in this specific case we default to 'none' if no value was provided

Code
export function createParseSettings(
  code: string | ts.SourceFile,
  tsestreeOptions: Partial<TSESTreeOptions> = {},
): MutableParseSettings {
  const codeFullText = enforceCodeString(code);
  const singleRun = inferSingleRun(tsestreeOptions);

  const tsconfigRootDir = (() => {
    if (tsestreeOptions.tsconfigRootDir == null) {
      const inferredTsconfigRootDir = getInferredTSConfigRootDir();
      if (path.resolve(inferredTsconfigRootDir) !== inferredTsconfigRootDir) {
        throw new Error(
          `inferred tsconfigRootDir should be a resolved absolute path, but received: ${JSON.stringify(
            inferredTsconfigRootDir,
          )}. This is a bug in typescript-eslint! Please report it to us at https://github.com/typescript-eslint/typescript-eslint/issues/new/choose.`,
        );
      }
      return inferredTsconfigRootDir;
    }

    if (typeof tsestreeOptions.tsconfigRootDir === 'string') {
      const userProvidedTsconfigRootDir = tsestreeOptions.tsconfigRootDir;
      if (
        !path.isAbsolute(userProvidedTsconfigRootDir) ||
        // Ensure it's fully absolute with a drive letter if windows
        (process.platform === 'win32' &&
          !/^[a-zA-Z]:/.test(userProvidedTsconfigRootDir))
      ) {
        throw new Error(
          `parserOptions.tsconfigRootDir must be an absolute path, but received: ${JSON.stringify(
            userProvidedTsconfigRootDir,
          )}. This is a bug in your configuration; please supply an absolute path.`,
        );
      }
      // Deal with any funny business around trailing path separators (a/b/) or relative path segments (/a/b/../c)
      // Since we already know it's absolute, we can safely use path.resolve here.
      return path.resolve(userProvidedTsconfigRootDir);
    }

    throw new Error(
      `If provided, parserOptions.tsconfigRootDir must be a string, but received a value of type "${typeof tsestreeOptions.tsconfigRootDir}"`,
    );
  })();

  const passedLoggerFn = typeof tsestreeOptions.loggerFn === 'function';
  const filePath = ensureAbsolutePath(
    typeof tsestreeOptions.filePath === 'string' &&
      tsestreeOptions.filePath !== '<input>'
      ? tsestreeOptions.filePath
      : getFileName(tsestreeOptions.jsx),
    tsconfigRootDir,
  );
  const extension = path.extname(filePath).toLowerCase() as ts.Extension;
  const jsDocParsingMode = ((): ts.JSDocParsingMode => {
    switch (tsestreeOptions.jsDocParsingMode) {
      case 'all':
        return JSDocParsingMode.ParseAll;

      case 'none':
        return JSDocParsingMode.ParseNone;

      case 'type-info':
        return JSDocParsingMode.ParseForTypeInfo;

      default:
        return JSDocParsingMode.ParseAll;
    }
  })();

  const parseSettings: MutableParseSettings = {
    loc: tsestreeOptions.loc === true,
    range: tsestreeOptions.range === true,
    allowInvalidAST: tsestreeOptions.allowInvalidAST === true,
    code,
    codeFullText,
    comment: tsestreeOptions.comment === true,
    comments: [],
    debugLevel:
      tsestreeOptions.debugLevel === true
        ? new Set(['typescript-eslint'])
        : Array.isArray(tsestreeOptions.debugLevel)
          ? new Set(tsestreeOptions.debugLevel)
          : new Set(),
    errorOnTypeScriptSyntacticAndSemanticIssues: false,
    errorOnUnknownASTType: tsestreeOptions.errorOnUnknownASTType === true,
    extraFileExtensions:
      Array.isArray(tsestreeOptions.extraFileExtensions) &&
      tsestreeOptions.extraFileExtensions.every(ext => typeof ext === 'string')
        ? tsestreeOptions.extraFileExtensions
        : [],
    filePath,
    jsDocParsingMode,
    jsx: tsestreeOptions.jsx === true,
    log:
      typeof tsestreeOptions.loggerFn === 'function'
        ? tsestreeOptions.loggerFn
        : tsestreeOptions.loggerFn === false
          ? (): void => {} // eslint-disable-line @typescript-eslint/no-empty-function
          : console.log, // eslint-disable-line no-console
    preserveNodeMaps: tsestreeOptions.preserveNodeMaps !== false,
    programs: Array.isArray(tsestreeOptions.programs)
      ? tsestreeOptions.programs
      : null,
    projects: new Map(),
    projectService:
      tsestreeOptions.projectService ||
      (tsestreeOptions.project &&
        tsestreeOptions.projectService !== false &&
        process.env.TYPESCRIPT_ESLINT_PROJECT_SERVICE === 'true')
        ? populateProjectService(tsestreeOptions.projectService, {
            jsDocParsingMode,
            tsconfigRootDir,
          })
        : undefined,
    setExternalModuleIndicator:
      tsestreeOptions.sourceType === 'module' ||
      (tsestreeOptions.sourceType == null && extension === ts.Extension.Mjs) ||
      (tsestreeOptions.sourceType == null && extension === ts.Extension.Mts)
        ? (file): void => {
            file.externalModuleIndicator = true;
          }
        : undefined,
    singleRun,
    suppressDeprecatedPropertyWarnings:
      tsestreeOptions.suppressDeprecatedPropertyWarnings ??
      process.env.NODE_ENV !== 'test',
    tokens: tsestreeOptions.tokens === true ? [] : null,
    tsconfigMatchCache: (TSCONFIG_MATCH_CACHE ??= new ExpiringCache(
      singleRun
        ? 'Infinity'
        : (tsestreeOptions.cacheLifetime?.glob ??
            DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS),
    )),
    tsconfigRootDir,
  };

  // TODO: Eventually, parse settings will be validated more thoroughly.
  // https://github.com/typescript-eslint/typescript-eslint/issues/6403
  if (
    parseSettings.projectService &&
    tsestreeOptions.project &&
    process.env.TYPESCRIPT_ESLINT_IGNORE_PROJECT_AND_PROJECT_SERVICE_ERROR !==
      'true'
  ) {
    throw new Error(
      'Enabling "project" does nothing when "projectService" is enabled. You can remove the "project" setting.',
    );
  }

  // debug doesn't support multiple `enable` calls, so have to do it all at once
  if (parseSettings.debugLevel.size > 0) {
    const namespaces = [];
    if (parseSettings.debugLevel.has('typescript-eslint')) {
      namespaces.push('typescript-eslint:*');
    }
    if (
      parseSettings.debugLevel.has('eslint') ||
      // make sure we don't turn off the eslint debug if it was enabled via --debug
      debug.enabled('eslint:*,-eslint:code-path')
    ) {
      // https://github.com/eslint/eslint/blob/9dfc8501fb1956c90dc11e6377b4cb38a6bea65d/bin/eslint.js#L25
      namespaces.push('eslint:*,-eslint:code-path');
    }
    debug.enable(namespaces.join(','));
  }

  if (Array.isArray(tsestreeOptions.programs)) {
    if (!tsestreeOptions.programs.length) {
      throw new Error(
        `You have set parserOptions.programs to an empty array. This will cause all files to not be found in existing programs. Either provide one or more existing TypeScript Program instances in the array, or remove the parserOptions.programs setting.`,
      );
    }
    log(
      'parserOptions.programs was provided, so parserOptions.project will be ignored.',
    );
  }

  // Providing a program or project service overrides project resolution
  if (!parseSettings.programs && !parseSettings.projectService) {
    parseSettings.projects = resolveProjectList({
      cacheLifetime: tsestreeOptions.cacheLifetime,
      project: getProjectConfigFiles(parseSettings, tsestreeOptions.project),
      projectFolderIgnoreList: tsestreeOptions.projectFolderIgnoreList,
      singleRun: parseSettings.singleRun,
      tsconfigRootDir,
    });
  }

  // No type-aware linting which means that cross-file (or even same-file) JSDoc is useless
  // So in this specific case we default to 'none' if no value was provided
  if (
    tsestreeOptions.jsDocParsingMode == null &&
    parseSettings.projects.size === 0 &&
    parseSettings.programs == null &&
    parseSettings.projectService == null
  ) {
    parseSettings.jsDocParsingMode = JSDocParsingMode.ParseNone;
  }

  handleUnsupportedTSVersion(
    parseSettings,
    tsestreeOptions.onUnsupportedTypeScriptVersion ?? 'warn',
    passedLoggerFn,
  );

  return parseSettings;
}

clearTSConfigMatchCache(): void

Returns: void

Calls:

  • TSCONFIG_MATCH_CACHE?.clear
Code
export function clearTSConfigMatchCache(): void {
  TSCONFIG_MATCH_CACHE?.clear();
}

clearTSServerProjectService(): void

Returns: void

Code
export function clearTSServerProjectService(): void {
  TSSERVER_PROJECT_SERVICE = null;
}

enforceCodeString(code: unknown): string

Ensures source code is a string.

Raw JSDoc
/**
 * Ensures source code is a string.
 */

Calls:

  • isSourceFile (from ../source-files)
  • code.getFullText
  • String
Code
function enforceCodeString(code: unknown): string {
  return isSourceFile(code)
    ? code.getFullText(code)
    : typeof code === 'string'
      ? code
      : String(code);
}

getFileName(jsx: boolean): string

Compute the filename based on the parser options.

Even if jsx option is set in typescript compiler, filename still has to contain .tsx file extension.

Raw JSDoc
/**
 * Compute the filename based on the parser options.
 *
 * Even if jsx option is set in typescript compiler, filename still has to
 * contain .tsx file extension.
 */
Code
function getFileName(jsx?: boolean): string {
  return jsx ? 'estree.tsx' : 'estree.ts';
}

populateProjectService(optionsRaw: ProjectServiceOptions | true | undefined, settings: CreateProjectServiceSettings): any

Parameters:

  • optionsRaw ProjectServiceOptions | true | undefined
  • settings CreateProjectServiceSettings

Returns: any

Calls:

  • validateDefaultProjectForFilesGlob (from ../create-program/validateDefaultProjectForFilesGlob)
  • createProjectService (from @typescript-eslint/project-service)
Code
function populateProjectService(
  optionsRaw: ProjectServiceOptions | true | undefined,
  settings: CreateProjectServiceSettings,
) {
  const options = typeof optionsRaw === 'object' ? optionsRaw : {};

  validateDefaultProjectForFilesGlob(options.allowDefaultProject);

  TSSERVER_PROJECT_SERVICE ??= createProjectService({
    options,
    ...settings,
  });

  return TSSERVER_PROJECT_SERVICE;
}

Generated by Syntax Scribe