xo 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,14 @@
1
- import ts from 'typescript';
2
1
  /**
3
- This function checks if the files are matched by the tsconfig include, exclude, and it returns the unmatched files.
2
+ This function checks if the files are matched by the tsconfig include/exclude, and returns the unmatched files.
4
3
 
5
- If no tsconfig is found, it will create an in-memory TypeScript Program for type-aware linting.
4
+ All unincluded files are routed through a generated tsconfig (`parserOptions.project`) so that autofix works correctly across multiple ESLint passes. The in-memory Program approach is intentionally not used here because `@typescript-eslint/typescript-estree` always returns the AST built from the original file text when using `parserOptions.programs`, ignoring the updated `code` ESLint passes on subsequent fix passes, which causes file corruption.
6
5
 
7
6
  @param options - The options for handling the tsconfig.
8
7
  @param options.files - The TypeScript files to check against the tsconfig.
9
8
  @param options.cwd - The current working directory.
10
- @param options.cacheLocation - The cache directory used to detect virtual/stdin files.
11
- @returns The unmatched files and an in-memory TypeScript Program.
9
+ @returns The unincluded files.
12
10
  */
13
- export declare function handleTsconfig({ files, cwd, cacheLocation }: {
11
+ export declare function handleTsconfig({ files, cwd }: {
14
12
  files: string[];
15
13
  cwd: string;
16
- cacheLocation?: string;
17
- }): {
18
- existingFiles: string[];
19
- virtualFiles: string[];
20
- program: ts.Program | undefined;
21
- };
14
+ }): string[];
@@ -1,9 +1,7 @@
1
1
  import path from 'node:path';
2
- import fs from 'node:fs';
3
2
  import { createRequire } from 'node:module';
4
3
  import ts from 'typescript';
5
4
  import { getTsconfig, createFilesMatcher } from 'get-tsconfig';
6
- import { tsconfigDefaults } from './constants.js';
7
5
  let hasWarnedAboutTypeScriptVersion = false;
8
6
  /**
9
7
  Warns once if the project's own TypeScript is an older major than the version XO bundles. Mixing TypeScript versions in one process can crash type-aware linting (notably under pnpm), because the TypeFlags enum was renumbered in TypeScript 6.
@@ -29,65 +27,17 @@ const warnOnOutdatedProjectTypeScript = (cwd) => {
29
27
  hasWarnedAboutTypeScriptVersion = true;
30
28
  console.warn(`XO bundles TypeScript ${ts.version}, but your project has TypeScript ${projectVersion}. Mixing TypeScript versions in one process can crash type-aware linting (notably with pnpm). Upgrade your project's \`typescript\` to ${bundledMajor} or later, or pin it (for example, a pnpm \`overrides\` entry).`);
31
29
  };
32
- const createInMemoryProgram = (files, cwd) => {
33
- if (files.length === 0) {
34
- return undefined;
35
- }
36
- try {
37
- const compilerOptions = getFallbackCompilerOptions(cwd);
38
- const program = ts.createProgram(files, { ...compilerOptions });
39
- Object.defineProperty(program, 'toJSON', {
40
- value: () => ({
41
- __type: 'TypeScriptProgram',
42
- files: files.map(file => path.relative(cwd, file)),
43
- }),
44
- configurable: true,
45
- });
46
- return program;
47
- }
48
- catch (error) {
49
- console.warn('XO: Failed to create TypeScript Program for type-aware linting. Continuing without type information for unincluded files.', error instanceof Error ? error.message : String(error));
50
- return undefined;
51
- }
52
- };
53
- const fallbackCompilerOptionsCache = new Map();
54
- const getFallbackCompilerOptions = (cwd) => {
55
- const cacheKey = path.resolve(cwd);
56
- const cached = fallbackCompilerOptionsCache.get(cacheKey);
57
- if (cached) {
58
- return cached;
59
- }
60
- const compilerOptionsResult = ts.convertCompilerOptionsFromJson(tsconfigDefaults.compilerOptions ?? {}, cacheKey);
61
- if (compilerOptionsResult.errors.length > 0) {
62
- throw new Error('XO: Invalid default TypeScript compiler options');
63
- }
64
- const compilerOptions = {
65
- ...compilerOptionsResult.options,
66
- // Anchor module and `@types` resolution to the project directory. Without `configFilePath`, an option-only program resolves these from `process.cwd()`, which differs from `cwd` for programmatic callers. The file need not exist; only its directory is used.
67
- configFilePath: path.join(cacheKey, 'tsconfig.json'),
68
- esModuleInterop: true,
69
- resolveJsonModule: true,
70
- allowJs: true,
71
- skipLibCheck: true,
72
- skipDefaultLibCheck: true,
73
- // TypeScript 6 only auto-includes `@types/*` packages when `types` contains `'*'`. Without this, files outside the tsconfig resolve imports to `any` and type-aware rules misfire.
74
- types: ['*'],
75
- };
76
- fallbackCompilerOptionsCache.set(cacheKey, compilerOptions);
77
- return compilerOptions;
78
- };
79
30
  /**
80
- This function checks if the files are matched by the tsconfig include, exclude, and it returns the unmatched files.
31
+ This function checks if the files are matched by the tsconfig include/exclude, and returns the unmatched files.
81
32
 
82
- If no tsconfig is found, it will create an in-memory TypeScript Program for type-aware linting.
33
+ All unincluded files are routed through a generated tsconfig (`parserOptions.project`) so that autofix works correctly across multiple ESLint passes. The in-memory Program approach is intentionally not used here because `@typescript-eslint/typescript-estree` always returns the AST built from the original file text when using `parserOptions.programs`, ignoring the updated `code` ESLint passes on subsequent fix passes, which causes file corruption.
83
34
 
84
35
  @param options - The options for handling the tsconfig.
85
36
  @param options.files - The TypeScript files to check against the tsconfig.
86
37
  @param options.cwd - The current working directory.
87
- @param options.cacheLocation - The cache directory used to detect virtual/stdin files.
88
- @returns The unmatched files and an in-memory TypeScript Program.
38
+ @returns The unincluded files.
89
39
  */
90
- export function handleTsconfig({ files, cwd, cacheLocation }) {
40
+ export function handleTsconfig({ files, cwd }) {
91
41
  warnOnOutdatedProjectTypeScript(cwd);
92
42
  const unincludedFiles = [];
93
43
  const filesMatcherCache = new Map();
@@ -108,39 +58,6 @@ export function handleTsconfig({ files, cwd, cacheLocation }) {
108
58
  }
109
59
  unincludedFiles.push(filePath);
110
60
  }
111
- if (unincludedFiles.length === 0) {
112
- return { existingFiles: [], virtualFiles: [], program: undefined };
113
- }
114
- // Separate real files from virtual/cache files
115
- // Virtual files include: stdin files (in cache dir), non-existent files
116
- // TypeScript will surface opaque diagnostics for missing files; pre-filter so we only pay the program cost for real files.
117
- const existingFiles = [];
118
- const virtualFiles = [];
119
- for (const file of unincludedFiles) {
120
- // Files that don't exist are always virtual
121
- if (!fs.existsSync(file)) {
122
- virtualFiles.push(file);
123
- continue;
124
- }
125
- // Check if file is in cache directory (like stdin files)
126
- // These need tsconfig treatment even though they exist on disk
127
- if (cacheLocation !== undefined) {
128
- const absolutePath = path.resolve(file);
129
- const cacheRoot = path.resolve(cacheLocation);
130
- const relativeToCache = path.relative(cacheRoot, absolutePath);
131
- // File is inside cache if relative path doesn't escape (no '..')
132
- const isInCache = !relativeToCache.startsWith('..') && !path.isAbsolute(relativeToCache);
133
- if (isInCache) {
134
- virtualFiles.push(file);
135
- continue;
136
- }
137
- }
138
- existingFiles.push(file);
139
- }
140
- return {
141
- existingFiles,
142
- virtualFiles,
143
- program: createInMemoryProgram(existingFiles, cwd),
144
- };
61
+ return unincludedFiles;
145
62
  }
146
63
  //# sourceMappingURL=handle-ts-files.js.map
package/dist/lib/xo.d.ts CHANGED
@@ -23,13 +23,11 @@ export declare class Xo {
23
23
  private prepareEslintConfig;
24
24
  private discoverFiles;
25
25
  /**
26
- Add virtual files to the config with a tsconfig approach.
27
- */
28
- private addVirtualFilesToConfig;
29
- /**
30
- Add existing files to the config with an in-memory TypeScript Program.
26
+ Add unincluded files to the config with a generated tsconfig approach. Passing an empty array removes the generated config entry.
27
+
28
+ This uses `parserOptions.project` rather than an in-memory `parserOptions.programs`. A pre-built program's AST is built once from the original file text and is never updated between ESLint's multiple `--fix` passes, so stale offsets corrupt the output. A file-based project is re-read on each pass, so autofix stays correct.
31
29
  */
32
- private addExistingFilesToConfig;
30
+ private addUnincludedFilesToConfig;
33
31
  private processReport;
34
32
  private getReportStatistics;
35
33
  /**
@@ -46,7 +44,7 @@ export declare class Xo {
46
44
  */
47
45
  ensureCacheDirectory(): Promise<void>;
48
46
  /**
49
- Checks every TS file to ensure its included in the tsconfig and any that are not included are added to an in-memory TypeScript Program for type aware linting.
47
+ Checks every TS file to ensure it is included in the tsconfig. Any that are not included are routed through a generated tsconfig (`tsconfig.generated.json`) so that autofix works correctly across multiple ESLint passes.
50
48
 
51
49
  @param files - The TypeScript files being linted.
52
50
  */
package/dist/lib/xo.js CHANGED
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import syncFs from 'node:fs';
4
4
  import fs from 'node:fs/promises';
5
5
  import process from 'node:process';
6
+ import { createHash } from 'node:crypto';
6
7
  import { ESLint } from 'eslint';
7
8
  import findCacheDirectory from 'find-cache-directory';
8
9
  import { globby, isDynamicPattern } from 'globby';
@@ -39,6 +40,17 @@ const createIgnoredLintResult = (filePath) => ({
39
40
  });
40
41
  const normalizeGlobPath = (filePath) => filePath.split(path.sep).join('/');
41
42
  const pathMatchesPattern = (filePath, pattern) => micromatch.isMatch(normalizeGlobPath(filePath), normalizeGlobPath(pattern), { dot: true });
43
+ const isPathInside = (parentPath, childPath) => {
44
+ const relativePath = path.relative(parentPath, childPath);
45
+ return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
46
+ };
47
+ const getGeneratedTsconfigPath = (directory, files) => {
48
+ const hash = createHash('sha256')
49
+ .update(JSON.stringify(files.toSorted((first, second) => first.localeCompare(second))))
50
+ .digest('hex')
51
+ .slice(0, 16);
52
+ return path.join(directory, `tsconfig.generated.${hash}.json`);
53
+ };
42
54
  const isIgnoredByPatterns = (filePath, patterns) => {
43
55
  let isIgnored = false;
44
56
  for (const pattern of patterns) {
@@ -233,6 +245,14 @@ export class Xo {
233
245
  */
234
246
  #cacheLocation;
235
247
  /**
248
+ Directory for generated tsconfigs for unincluded TypeScript files.
249
+ */
250
+ #generatedTsconfigDirectory;
251
+ /**
252
+ File path to the currently active generated tsconfig.
253
+ */
254
+ #currentGeneratedTsconfigPath;
255
+ /**
236
256
  XO config derived from both the base config and the resolved flat config.
237
257
  */
238
258
  #xoConfig;
@@ -258,17 +278,6 @@ export class Xo {
258
278
  We use this to also add negative glob patterns in case a user overrides the parserOptions in their XO config.
259
279
  */
260
280
  #tsFilesIgnoresGlob = [];
261
- /**
262
- Store per-file configs separately from base config to prevent unbounded array growth.
263
- Key: file path, Value: config for that file.
264
- This prevents memory bloat in long-running processes (e.g., language servers).
265
- */
266
- #fileConfigs = new Map();
267
- /**
268
- Track virtual/stdin files that share a single tsconfig.stdin.json.
269
- These are handled differently from regular files.
270
- */
271
- #virtualFiles = new Set();
272
281
  constructor(_linterOptions, _baseXoConfig = {}) {
273
282
  this.#linterOptions = _linterOptions;
274
283
  this.#baseXoConfig = _baseXoConfig;
@@ -284,6 +293,9 @@ export class Xo {
284
293
  }
285
294
  const backupCacheLocation = path.join(os.tmpdir(), cacheDirName);
286
295
  this.#cacheLocation = findCacheDirectory({ name: cacheDirName, cwd: this.#linterOptions.cwd }) ?? backupCacheLocation;
296
+ this.#generatedTsconfigDirectory = isPathInside(this.#linterOptions.cwd, this.#cacheLocation)
297
+ ? this.#cacheLocation
298
+ : path.join(this.#linterOptions.cwd, 'node_modules', '.cache', cacheDirName);
287
299
  }
288
300
  /**
289
301
  Initializes the ESLint flat config on the XO instance.
@@ -320,100 +332,74 @@ export class Xo {
320
332
  };
321
333
  }
322
334
  /**
323
- Add virtual files to the config with a tsconfig approach.
335
+ Add unincluded files to the config with a generated tsconfig approach. Passing an empty array removes the generated config entry.
336
+
337
+ This uses `parserOptions.project` rather than an in-memory `parserOptions.programs`. A pre-built program's AST is built once from the original file text and is never updated between ESLint's multiple `--fix` passes, so stale offsets corrupt the output. A file-based project is re-read on each pass, so autofix stays correct.
324
338
  */
325
- async addVirtualFilesToConfig(files) {
339
+ async addUnincludedFilesToConfig(files) {
326
340
  if (!this.#xoConfig) {
327
341
  return;
328
342
  }
329
343
  try {
330
- const nextVirtualFiles = new Set(files);
331
- const tsconfigPath = path.join(this.#cacheLocation, 'tsconfig.stdin.json');
332
- const configIndex = this.#xoConfig.findIndex(configItem => {
333
- const { languageOptions } = configItem;
334
- const parserOptions = languageOptions?.['parserOptions'];
335
- return parserOptions?.project === tsconfigPath;
336
- });
337
- if (nextVirtualFiles.size > 0) {
338
- const filesArray = [...nextVirtualFiles];
339
- const relativeFiles = filesArray.map(file => path.relative(this.#linterOptions.cwd, file));
340
- const tsconfigContent = {
341
- compilerOptions: {
342
- ...tsconfigDefaults.compilerOptions,
343
- module: 'ESNext',
344
- moduleResolution: 'NodeNext',
345
- esModuleInterop: true,
346
- skipLibCheck: true,
347
- // TypeScript 6 only auto-includes `@types/*` packages when `types` contains `'*'`. Without this, virtual/stdin files resolve imports to `any` and type-aware rules misfire.
348
- types: ['*'],
349
- },
350
- files: filesArray,
351
- };
352
- await fs.writeFile(tsconfigPath, JSON.stringify(tsconfigContent, null, 2));
353
- if (configIndex === -1) {
354
- const parserOptions = {
355
- projectService: false,
356
- project: tsconfigPath,
357
- tsconfigRootDir: this.#linterOptions.cwd,
358
- };
359
- this.#xoConfig.push({
360
- files: relativeFiles,
361
- languageOptions: {
362
- parser: typescriptParser,
363
- parserOptions,
364
- },
365
- });
366
- }
367
- else {
368
- const existingConfig = this.#xoConfig[configIndex];
369
- this.#xoConfig[configIndex] = {
370
- ...existingConfig,
371
- files: relativeFiles,
372
- };
344
+ const previousTsconfigPath = this.#currentGeneratedTsconfigPath;
345
+ const configIndex = previousTsconfigPath === undefined
346
+ ? -1
347
+ : this.#xoConfig.findIndex(configItem => {
348
+ const { languageOptions } = configItem;
349
+ const parserOptions = languageOptions?.['parserOptions'];
350
+ return parserOptions?.project === previousTsconfigPath;
351
+ });
352
+ if (files.length === 0) {
353
+ if (configIndex !== -1) {
354
+ this.#xoConfig.splice(configIndex, 1);
373
355
  }
374
- this.#virtualFiles.clear();
375
- for (const file of nextVirtualFiles) {
376
- this.#virtualFiles.add(file);
356
+ if (previousTsconfigPath !== undefined) {
357
+ this.#currentGeneratedTsconfigPath = undefined;
377
358
  }
378
359
  return;
379
360
  }
380
- if (configIndex >= 0) {
381
- this.#xoConfig.splice(configIndex, 1);
361
+ const tsconfigPath = getGeneratedTsconfigPath(this.#generatedTsconfigDirectory, files);
362
+ // The generated tsconfig references files by absolute path; the ESLint config matches them by path relative to `cwd`.
363
+ const relativeFiles = files.map(file => path.relative(this.#linterOptions.cwd, file));
364
+ const tsconfigContent = {
365
+ compilerOptions: {
366
+ ...tsconfigDefaults.compilerOptions,
367
+ module: 'ESNext',
368
+ moduleResolution: 'NodeNext',
369
+ esModuleInterop: true,
370
+ resolveJsonModule: true,
371
+ skipLibCheck: true,
372
+ // JS files are routed here too (type-aware rules apply to JS). Without `allowJs`, TypeScript does not load them as source files, so the parser reports "file not found in project".
373
+ allowJs: true,
374
+ // TypeScript 6 only auto-includes `@types/*` packages when `types` contains `'*'`. Without this, unincluded files resolve imports to `any` and type-aware rules misfire.
375
+ types: ['*'],
376
+ },
377
+ files,
378
+ };
379
+ await fs.mkdir(path.dirname(tsconfigPath), { recursive: true });
380
+ await fs.writeFile(tsconfigPath, JSON.stringify(tsconfigContent, null, 2));
381
+ this.#currentGeneratedTsconfigPath = tsconfigPath;
382
+ const parserOptions = {
383
+ projectService: false,
384
+ project: tsconfigPath,
385
+ tsconfigRootDir: this.#linterOptions.cwd,
386
+ };
387
+ const generatedConfig = {
388
+ files: relativeFiles,
389
+ languageOptions: {
390
+ parser: typescriptParser,
391
+ parserOptions,
392
+ },
393
+ };
394
+ if (configIndex === -1) {
395
+ this.#xoConfig.push(generatedConfig);
396
+ }
397
+ else {
398
+ this.#xoConfig[configIndex] = generatedConfig;
382
399
  }
383
- this.#virtualFiles.clear();
384
- await fs.rm(tsconfigPath, { force: true });
385
400
  }
386
401
  catch (error) {
387
- console.warn('XO: Failed to create tsconfig for virtual files. Type-aware linting will be disabled for these files.', error instanceof Error ? error.message : String(error));
388
- }
389
- }
390
- /**
391
- Add existing files to the config with an in-memory TypeScript Program.
392
- */
393
- addExistingFilesToConfig(files, program) {
394
- if (!this.#xoConfig || files.length === 0) {
395
- return;
396
- }
397
- const parserOptions = {
398
- project: false,
399
- projectService: false,
400
- };
401
- if (program) {
402
- parserOptions.programs = [program];
403
- }
404
- const config = {
405
- files: files.map(file => path.relative(this.#linterOptions.cwd, file)),
406
- languageOptions: {
407
- parser: typescriptParser,
408
- parserOptions,
409
- },
410
- };
411
- // IMPORTANT: All files intentionally share the same config object reference for memory efficiency.
412
- // This prevents unbounded memory growth in long-running processes (e.g., language servers).
413
- // The config is immutable after creation, so sharing is safe.
414
- // Deduplication happens in setEslintConfig() via Set to avoid duplicate configs in the final array.
415
- for (const file of files) {
416
- this.#fileConfigs.set(file, config);
402
+ console.warn('XO: Failed to create tsconfig for unincluded files. Type-aware linting will be disabled for these files.', error instanceof Error ? error.message : String(error));
417
403
  }
418
404
  }
419
405
  processReport(report, { rulesMeta = {} } = {}) {
@@ -492,14 +478,11 @@ export class Xo {
492
478
  if (!this.#xoConfig) {
493
479
  throw new Error('"Xo.setEslintConfig" failed');
494
480
  }
495
- // Combine base config with per-file configs from Map
496
- // Deduplicate configs since multiple files can share the same config object
497
481
  const [baseConfig = {}, ...resolvedConfigs] = this.#xoConfig;
498
482
  const { ignores, ...configWithoutCliIgnores } = baseConfig;
499
483
  const expandedResolvedConfigs = resolvedConfigs.map(config => expandGlobalIgnoreConfigForEslint(config));
500
- const uniqueFileConfigs = [...new Set(this.#fileConfigs.values())];
501
484
  const cliIgnoreConfig = cliIgnores.length > 0 ? [{ ignores: expandIgnoreNegationsForEslint(cliIgnores) }] : [];
502
- const allConfigs = [configWithoutCliIgnores, ...expandedResolvedConfigs, ...cliIgnoreConfig, ...uniqueFileConfigs];
485
+ const allConfigs = [configWithoutCliIgnores, ...expandedResolvedConfigs, ...cliIgnoreConfig];
503
486
  // Always regenerate to support instance reuse with new files
504
487
  this.#eslintConfig = xoToEslintConfig(allConfigs);
505
488
  if (stripDefaultIgnores) {
@@ -527,33 +510,24 @@ export class Xo {
527
510
  }
528
511
  }
529
512
  /**
530
- Checks every TS file to ensure its included in the tsconfig and any that are not included are added to an in-memory TypeScript Program for type aware linting.
513
+ Checks every TS file to ensure it is included in the tsconfig. Any that are not included are routed through a generated tsconfig (`tsconfig.generated.json`) so that autofix works correctly across multiple ESLint passes.
531
514
 
532
515
  @param files - The TypeScript files being linted.
533
516
  */
534
517
  async handleUnincludedTsFiles(files) {
535
- if (!this.#linterOptions.ts || !files || files.length === 0) {
518
+ if (!this.#linterOptions.ts) {
536
519
  return;
537
520
  }
538
- // Get ALL TypeScript files being linted (both new and previously handled)
539
- const allTsFiles = matchFilesForTsConfig(this.#linterOptions.cwd, files, this.#tsFilesGlob, this.#tsFilesIgnoresGlob);
540
- if (allTsFiles.length === 0) {
541
- this.#fileConfigs.clear();
542
- if (this.#virtualFiles.size > 0) {
543
- await this.addVirtualFilesToConfig([]);
544
- }
521
+ if (!files || files.length === 0) {
522
+ await this.addUnincludedFilesToConfig([]);
545
523
  return;
546
524
  }
547
- const { program, existingFiles, virtualFiles } = handleTsconfig({
548
- files: allTsFiles,
549
- cwd: this.#linterOptions.cwd,
550
- cacheLocation: this.#cacheLocation,
551
- });
552
- this.#fileConfigs.clear();
553
- if (existingFiles.length > 0) {
554
- this.addExistingFilesToConfig(existingFiles, program);
555
- }
556
- await this.addVirtualFilesToConfig(virtualFiles);
525
+ // Get ALL TypeScript files being linted
526
+ const allTsFiles = matchFilesForTsConfig(this.#linterOptions.cwd, files, this.#tsFilesGlob, this.#tsFilesIgnoresGlob);
527
+ const unincludedFiles = allTsFiles.length === 0
528
+ ? []
529
+ : handleTsconfig({ files: allTsFiles, cwd: this.#linterOptions.cwd });
530
+ await this.addUnincludedFilesToConfig(unincludedFiles);
557
531
  }
558
532
  /**
559
533
  Initializes the ESLint instance on the XO instance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xo",
3
- "version": "3.0.1",
3
+ "version": "3.0.2",
4
4
  "description": "JavaScript/TypeScript linter (ESLint wrapper) with great defaults",
5
5
  "license": "MIT",
6
6
  "repository": "xojs/xo",