oxlint-contract.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import { spawnSync } from 'node:child_process'
  2. import { randomUUID } from 'node:crypto'
  3. import { existsSync } from 'node:fs'
  4. import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
  5. import { basename, dirname, join, relative } from 'node:path'
  6. import { fileURLToPath } from 'node:url'
  7. import { flattenDiagnosticMessageText, parseConfigFileTextToJson } from 'typescript'
  8. import { describe, expect, it } from 'vitest'
  9. const repositoryRoot = fileURLToPath(new URL('..', import.meta.url))
  10. const oxlintCli = fileURLToPath(new URL('../node_modules/oxlint/bin/oxlint', import.meta.url))
  11. const tsxCli = fileURLToPath(new URL('../node_modules/tsx/dist/cli.mjs', import.meta.url))
  12. function isRecord(value: unknown): value is Record<string, unknown> {
  13. return typeof value === 'object' && value !== null && !Array.isArray(value)
  14. }
  15. function isUnknownArray(value: unknown): value is unknown[] {
  16. return Array.isArray(value)
  17. }
  18. function runRepositoryOxlint(args: readonly string[], env: NodeJS.ProcessEnv = {}) {
  19. return spawnSync(process.execPath, [tsxCli, 'scripts/run-oxlint.ts', ...args], {
  20. cwd: repositoryRoot,
  21. encoding: 'utf8',
  22. env: { ...process.env, NO_COLOR: '1', ...env },
  23. })
  24. }
  25. function runOxlint(args: readonly string[], env: NodeJS.ProcessEnv = {}) {
  26. return spawnSync(process.execPath, [oxlintCli, ...args], {
  27. cwd: repositoryRoot,
  28. encoding: 'utf8',
  29. env: { ...process.env, NO_COLOR: '1', ...env },
  30. })
  31. }
  32. function normalizedOutput(result: ReturnType<typeof runOxlint>): string {
  33. return `${result.stdout}${result.stderr}`.replaceAll('\\', '/')
  34. }
  35. /** @returns A transient filename excluded from concurrent repository-wide glob discovery. */
  36. function hiddenProbeName(prefix: string, suffix: string, extension = '.ts'): string {
  37. return `.${prefix}-${suffix}${extension}`
  38. }
  39. /**
  40. * Publish a complete probe so concurrent repository scans never read a partial write.
  41. * @param path - Final probe path that the owning project must discover.
  42. * @param source - Complete TypeScript source to publish.
  43. */
  44. async function publishProbe(path: string, source: string): Promise<void> {
  45. const staging = join(dirname(path), `.${basename(path)}.staging`)
  46. try {
  47. await writeFile(staging, source)
  48. await rename(staging, path)
  49. } finally {
  50. await rm(staging, { force: true })
  51. }
  52. }
  53. async function writeContractConfig(suffix: string): Promise<string> {
  54. const path = join(repositoryRoot, `.oxlintrc.contract-${suffix}.json`)
  55. await writeFile(path, JSON.stringify({ extends: ['./.oxlintrc.json'], ignorePatterns: [] }))
  56. return path
  57. }
  58. describe('Oxlint executable contract', () => {
  59. it('discovers the owning TypeScript project for every file class', async () => {
  60. const suffix = randomUUID()
  61. const configPath = await writeContractConfig(suffix)
  62. const probes = [
  63. ['host package source', 'packages/fs/fs-observation-policy/src', 'packages/fs/fs-observation-policy/tsconfig.json'],
  64. ['host package test', 'packages/fs/fs-observation-policy/tests', 'tsconfig.host.json'],
  65. ['client package source', 'packages/client/ui-primitives/src', 'packages/client/ui-primitives/tsconfig.json'],
  66. // A test under packages/client states its face in the filename, so the
  67. // probe carries the Client suffix to reach the Client aggregate.
  68. ['client package test', 'packages/client/ui-trajectory/tests', 'tsconfig.client.json', '.client.ts'],
  69. ['example', 'examples/headless-agent/tests', 'tsconfig.host.json'],
  70. ['website', 'website', 'tsconfig.host.json'],
  71. ] as const
  72. const source = `/** Produce a settled promise for type-aware linting. */
  73. export function probePromise(): Promise<void> {
  74. return Promise.resolve()
  75. }
  76. probePromise()
  77. `
  78. try {
  79. const paths: Array<readonly [label: string, path: string, tsconfig: string]> = []
  80. for (const [label, parent, tsconfig, extension = '.ts'] of probes) {
  81. const path = join(repositoryRoot, parent, `oxlint-contract-${suffix}${extension}`)
  82. await publishProbe(path, source)
  83. paths.push([label, relative(repositoryRoot, path), tsconfig])
  84. }
  85. const clientScript = 'scripts/client-bundle-purity.spec.ts'
  86. const result = runOxlint([
  87. '--config',
  88. relative(repositoryRoot, configPath),
  89. '--format',
  90. 'unix',
  91. ...paths.map(([, path]) => path),
  92. clientScript,
  93. ], { OXC_LOG: 'debug' })
  94. const output = normalizedOutput(result)
  95. expect(result.error).toBeUndefined()
  96. expect(result.status, output).toBe(1)
  97. for (const [label, path, tsconfig] of paths) {
  98. expect(output, label).toContain(`${path.replaceAll('\\', '/')}:6:1: Promises must be awaited`)
  99. expect(output, `${label} project`).toContain(
  100. `Got tsconfig for file ${join(repositoryRoot, path).replaceAll('\\', '/')}: ${join(repositoryRoot, tsconfig).replaceAll('\\', '/')}`,
  101. )
  102. }
  103. expect(output.match(/typescript\(no-floating-promises\)/g)).toHaveLength(probes.length)
  104. expect(output, 'client aggregate script project').toContain(
  105. `Got tsconfig for file ${join(repositoryRoot, clientScript).replaceAll('\\', '/')}: ${join(repositoryRoot, 'tsconfig.client.json').replaceAll('\\', '/')}`,
  106. )
  107. expect(output).not.toContain('Unmatched file:')
  108. } finally {
  109. await Promise.all([
  110. ...probes.map(([, parent, , extension = '.ts']) =>
  111. rm(join(repositoryRoot, parent, `oxlint-contract-${suffix}${extension}`), { force: true })),
  112. rm(configPath, { force: true }),
  113. ])
  114. }
  115. }, 20_000)
  116. it('runs JavaScript compatibility and nursery rules', async () => {
  117. const suffix = randomUUID()
  118. const configPath = await writeContractConfig(suffix)
  119. const path = join(repositoryRoot, 'scripts', hiddenProbeName('oxlint-contract', suffix))
  120. const source = `export function firstProbe(): number {
  121. const first = 1
  122. const second = 2
  123. return first + second
  124. }
  125. export function secondProbe(): number {
  126. const first = 1
  127. const second = 2
  128. return first + second
  129. }
  130. export function hasValue(value: string): boolean {
  131. return value !== undefined
  132. }
  133. export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
  134. `
  135. try {
  136. await writeFile(path, source)
  137. const result = runOxlint([
  138. '--config',
  139. relative(repositoryRoot, configPath),
  140. '--format',
  141. 'unix',
  142. relative(repositoryRoot, path),
  143. ])
  144. const output = normalizedOutput(result)
  145. expect(result.error).toBeUndefined()
  146. expect(result.status, output).toBe(1)
  147. expect(output).toContain('@stylistic(max-len)')
  148. expect(output).toContain('sonarjs(no-identical-functions)')
  149. expect(output).toContain('typescript(no-unnecessary-condition)')
  150. } finally {
  151. await Promise.all([
  152. rm(path, { force: true }),
  153. rm(configPath, { force: true }),
  154. ])
  155. }
  156. }, 20_000)
  157. it('keeps the complete stylistic contract in Oxlint', async () => {
  158. const oxlintPath = join(repositoryRoot, '.oxlintrc.json')
  159. const result = parseConfigFileTextToJson(oxlintPath, await readFile(oxlintPath, 'utf8'))
  160. if (result.error !== undefined) {
  161. throw new Error(flattenDiagnosticMessageText(result.error.messageText, '\n'))
  162. }
  163. const parsed = result.config as unknown
  164. if (!isRecord(parsed) || !isUnknownArray(parsed.overrides)) {
  165. throw new Error('.oxlintrc.json must contain an overrides array')
  166. }
  167. expect(parsed.ignorePatterns).toEqual(expect.arrayContaining([
  168. 'packages/typert/generator/tests/fixtures/type-model/**',
  169. ]))
  170. const stylisticOverride = parsed.overrides.find((value: unknown) =>
  171. isRecord(value) && isRecord(value.rules) && '@stylistic/max-len' in value.rules)
  172. if (!isRecord(stylisticOverride) || !isRecord(stylisticOverride.rules)) {
  173. throw new Error('.oxlintrc.json must contain the @stylistic validator override')
  174. }
  175. expect(stylisticOverride.rules).toMatchObject({
  176. '@stylistic/indent': ['error', 2],
  177. '@stylistic/semi': ['error', 'never'],
  178. '@stylistic/quotes': ['error', 'single', { avoidEscape: true }],
  179. '@stylistic/comma-dangle': ['error', 'always-multiline'],
  180. '@stylistic/eol-last': ['error', 'always'],
  181. '@stylistic/no-trailing-spaces': 'error',
  182. '@stylistic/object-curly-spacing': ['error', 'always'],
  183. '@stylistic/arrow-parens': ['error', 'as-needed', { requireForBlockBody: true }],
  184. '@stylistic/member-delimiter-style': ['error', {
  185. multiline: { delimiter: 'none' },
  186. singleline: { delimiter: 'semi', requireLast: false },
  187. }],
  188. '@stylistic/max-len': ['error', { code: 140, ignoreUrls: true, ignoreStrings: true, ignoreTemplateLiterals: true }],
  189. })
  190. const typeGraphOverride = parsed.overrides.find((value: unknown) =>
  191. isRecord(value)
  192. && isUnknownArray(value.files)
  193. && value.files.includes('packages/typert/generator/tests/fixtures/type-model/packages/host/src/models.ts'))
  194. expect(typeGraphOverride).toMatchObject({
  195. rules: { '@stylistic/quotes': 'off' },
  196. })
  197. })
  198. it('checks preserved TypeGraph syntax without type-aware analysis', () => {
  199. const result = runOxlint([
  200. '--config',
  201. '.oxlintrc.staged.json',
  202. 'packages/typert/generator/tests/fixtures/type-model',
  203. ])
  204. expect(result.error).toBeUndefined()
  205. expect(result.status, normalizedOutput(result)).toBe(0)
  206. })
  207. it('keeps repository lint workflows Oxlint-only', async () => {
  208. const packageJson = JSON.parse(await readFile(join(repositoryRoot, 'package.json'), 'utf8')) as unknown
  209. if (!isRecord(packageJson) || !isRecord(packageJson.scripts) || !isRecord(packageJson.devDependencies)) {
  210. throw new Error('package.json must contain scripts and devDependencies objects')
  211. }
  212. expect(packageJson.scripts['lint:contracts-ready']).toBe('tsx scripts/run-oxlint.ts .')
  213. expect(packageJson.scripts['lint:fix:contracts-ready']).toBe(
  214. 'tsx scripts/run-oxlint.ts --config .oxlintrc.staged.json packages/typert/generator/tests/fixtures/type-model --fix && tsx scripts/run-oxlint.ts . --fix',
  215. )
  216. expect(packageJson.devDependencies).not.toHaveProperty('eslint')
  217. expect(packageJson.devDependencies).not.toHaveProperty('@typescript-eslint/parser')
  218. expect(existsSync(join(repositoryRoot, 'eslint.format.config.mjs'))).toBe(false)
  219. const lefthook = await readFile(join(repositoryRoot, 'lefthook.yml'), 'utf8')
  220. expect(lefthook).toContain('scripts/run-oxlint.ts --config .oxlintrc.staged.json --fix')
  221. expect(lefthook).not.toContain('node_modules/.bin/eslint')
  222. expect(lefthook).not.toContain('eslint.format.config.mjs')
  223. })
  224. it('reports an unused suppression', async () => {
  225. const suffix = randomUUID()
  226. const configPath = await writeContractConfig(suffix)
  227. const path = join(repositoryRoot, 'scripts', hiddenProbeName('oxlint-contract', suffix))
  228. try {
  229. await writeFile(path, '// oxlint-disable-next-line no-console\nexport const value = 1\n')
  230. const result = runOxlint([
  231. '--config',
  232. relative(repositoryRoot, configPath),
  233. '--format',
  234. 'unix',
  235. relative(repositoryRoot, path),
  236. ])
  237. const output = normalizedOutput(result)
  238. expect(result.error).toBeUndefined()
  239. expect(result.status, output).toBe(0)
  240. expect(output).toContain('Unused oxlint-disable directive')
  241. } finally {
  242. await Promise.all([
  243. rm(path, { force: true }),
  244. rm(configPath, { force: true }),
  245. ])
  246. }
  247. }, 20_000)
  248. it('accepts an ignored-only staged selection', () => {
  249. const result = runOxlint([
  250. '--fix',
  251. '--no-error-on-unmatched-pattern',
  252. 'scripts/install-lefthook.mjs',
  253. ])
  254. expect(result.error).toBeUndefined()
  255. expect(result.status, normalizedOutput(result)).toBe(0)
  256. })
  257. it('keeps staged validation project-free while preserving source rules', async () => {
  258. const configPath = join(repositoryRoot, '.oxlintrc.staged.json')
  259. const result = parseConfigFileTextToJson(configPath, await readFile(configPath, 'utf8'))
  260. if (result.error !== undefined) {
  261. throw new Error(flattenDiagnosticMessageText(result.error.messageText, '\n'))
  262. }
  263. const stagedConfig = result.config as unknown
  264. if (!isRecord(stagedConfig)) throw new Error('.oxlintrc.staged.json must contain a config object')
  265. expect(stagedConfig).toMatchObject({
  266. extends: ['./.oxlintrc.json'],
  267. options: { typeAware: false },
  268. })
  269. expect(stagedConfig.ignorePatterns).not.toContain('packages/typert/generator/tests/fixtures/type-model/**')
  270. const suffix = randomUUID()
  271. const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix))
  272. try {
  273. await writeFile(path, 'export const value={answer:1};\n')
  274. const lint = runOxlint([
  275. '--config',
  276. relative(repositoryRoot, configPath),
  277. '--format',
  278. 'unix',
  279. relative(repositoryRoot, path),
  280. ])
  281. const output = normalizedOutput(lint)
  282. expect(lint.error).toBeUndefined()
  283. expect(lint.status, output).toBe(1)
  284. expect(output).toContain('@stylistic')
  285. expect(output).not.toContain('typescript(')
  286. } finally {
  287. await rm(path, { force: true })
  288. }
  289. })
  290. it('preserves successful fix output channels', async () => {
  291. const suffix = randomUUID()
  292. const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix))
  293. try {
  294. await writeFile(path, '// oxlint-disable-next-line no-console\nexport const value = 1\n')
  295. const result = runRepositoryOxlint([
  296. '--config',
  297. '.oxlintrc.staged.json',
  298. '--format',
  299. 'unix',
  300. '--fix',
  301. relative(repositoryRoot, path),
  302. ])
  303. expect(result.error).toBeUndefined()
  304. expect(result.status, normalizedOutput(result)).toBe(0)
  305. expect(result.stdout).toContain('Unused oxlint-disable directive')
  306. expect(result.stderr).toBe('')
  307. } finally {
  308. await rm(path, { force: true })
  309. }
  310. })
  311. it('prints only the final diagnostics when a fix retry still fails', async () => {
  312. const suffix = randomUUID()
  313. const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix))
  314. try {
  315. await writeFile(path, `export const longProbe = ${'1 + '.repeat(80)}1\n`)
  316. const result = runRepositoryOxlint([
  317. '--config',
  318. '.oxlintrc.staged.json',
  319. '--format',
  320. 'unix',
  321. '--fix',
  322. relative(repositoryRoot, path),
  323. ])
  324. const output = normalizedOutput(result)
  325. expect(result.error).toBeUndefined()
  326. expect(result.status, output).toBe(1)
  327. expect(output.match(/@stylistic\(max-len\)/g)).toHaveLength(1)
  328. } finally {
  329. await rm(path, { force: true })
  330. }
  331. })
  332. it.each(['--fix', '--fix-suggestions', '--fix-dangerously'])(
  333. 'converges overlapping staged stylistic fixes through Oxlint under %s',
  334. async (fixFlag) => {
  335. const suffix = randomUUID()
  336. const directory = join(repositoryRoot, 'scripts', `.oxlint-contract-${suffix}`)
  337. const path = join(directory, 'fix.ts')
  338. try {
  339. await mkdir(directory, { recursive: true })
  340. await writeFile(path, 'const value={answer:1}; \nconsole.log(value)\n')
  341. const relativePath = relative(repositoryRoot, path)
  342. const lintResult = runRepositoryOxlint(['--config', '.oxlintrc.staged.json', fixFlag, relativePath])
  343. expect(lintResult.error).toBeUndefined()
  344. expect(lintResult.status, normalizedOutput(lintResult)).toBe(0)
  345. expect(normalizedOutput(lintResult)).not.toContain('@stylistic')
  346. await expect(readFile(path, 'utf8')).resolves.toBe('const value={ answer:1 }\nconsole.log(value)\n')
  347. } finally {
  348. await rm(directory, { recursive: true, force: true })
  349. }
  350. },
  351. 20_000,
  352. )
  353. })