diff --git a/.changelog/oxide-candidates-with-positions-errors.md b/.changelog/oxide-candidates-with-positions-errors.md new file mode 100644 index 000000000000..d6a495b30e04 --- /dev/null +++ b/.changelog/oxide-candidates-with-positions-errors.md @@ -0,0 +1,3 @@ +### Fixed + +- Throw an error instead of crashing the process when `Scanner#scanFiles` or `Scanner#getCandidatesWithPositions` from `@tailwindcss/oxide` gets invalid input diff --git a/crates/node/src/lib.rs b/crates/node/src/lib.rs index 97ba28f6c056..963c16ca91a9 100644 --- a/crates/node/src/lib.rs +++ b/crates/node/src/lib.rs @@ -48,17 +48,27 @@ pub struct SourceEntry { pub negated: bool, } -impl From for tailwindcss_oxide::ChangedContent { - fn from(changed_content: ChangedContent) -> Self { +const MISSING_CONTENT_AND_FILE: &str = "Either `content` or `file` must be provided"; + +impl TryFrom for tailwindcss_oxide::ChangedContent { + type Error = napi::Error; + + fn try_from(changed_content: ChangedContent) -> napi::Result { if let Some(file) = changed_content.file { - return tailwindcss_oxide::ChangedContent::File(file.into(), changed_content.extension); + return Ok(tailwindcss_oxide::ChangedContent::File( + file.into(), + changed_content.extension, + )); } if let Some(contents) = changed_content.content { - return tailwindcss_oxide::ChangedContent::Content(contents, changed_content.extension); + return Ok(tailwindcss_oxide::ChangedContent::Content( + contents, + changed_content.extension, + )); } - unreachable!() + Err(napi::Error::from_reason(MISSING_CONTENT_AND_FILE)) } } @@ -134,38 +144,42 @@ impl Scanner { } #[napi] - pub fn scan_files(&mut self, input: Vec) -> Vec { - self - .scanner - .scan_content(input.into_iter().map(Into::into).collect()) + pub fn scan_files(&mut self, input: Vec) -> napi::Result> { + let input = input + .into_iter() + .map(TryInto::try_into) + .collect::>>()?; + + Ok(self.scanner.scan_content(input)) } #[napi] pub fn get_candidates_with_positions( &mut self, input: ChangedContent, - ) -> Vec { - let content = input.content.unwrap_or_else(|| { - std::fs::read_to_string(input.file.unwrap()).expect("Failed to read file") - }); - - let input = ChangedContent { - file: None, - content: Some(content.clone()), - extension: input.extension, + ) -> napi::Result> { + let content = match (input.content, input.file) { + (Some(content), _) => content, + (None, Some(file)) => std::fs::read_to_string(&file) + .map_err(|err| napi::Error::from_reason(format!("Failed to read file `{file}`: {err}")))?, + (None, None) => return Err(napi::Error::from_reason(MISSING_CONTENT_AND_FILE)), }; + let input = tailwindcss_oxide::ChangedContent::Content(content.clone(), input.extension); + let mut utf16_idx = IndexConverter::new(&content[..]); - self - .scanner - .get_candidates_with_positions(input.into()) - .into_iter() - .map(|(candidate, position)| CandidateWithPosition { - candidate, - position: utf16_idx.get(position), - }) - .collect() + Ok( + self + .scanner + .get_candidates_with_positions(input) + .into_iter() + .map(|(candidate, position)| CandidateWithPosition { + candidate, + position: utf16_idx.get(position), + }) + .collect(), + ) } #[napi(getter)] diff --git a/packages/@tailwindcss-upgrade/src/codemods/template/candidates.test.ts b/packages/@tailwindcss-upgrade/src/codemods/template/candidates.test.ts index 2e4d150aa55a..d838630652f8 100644 --- a/packages/@tailwindcss-upgrade/src/codemods/template/candidates.test.ts +++ b/packages/@tailwindcss-upgrade/src/codemods/template/candidates.test.ts @@ -1,4 +1,8 @@ import { __unstable__loadDesignSystem } from '@tailwindcss/node' +import { Scanner } from '@tailwindcss/oxide' +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' import { expect, test } from 'vitest' import { spliceChangesIntoString } from '../../utils/splice-changes-into-string' import { extractRawCandidates } from './candidates' @@ -82,3 +86,49 @@ test('replaces the right positions for a candidate', async () => { " `) }) + +test('reads the content from `file` when no `content` is given', async () => { + let dir = await fs.mkdtemp(path.join(os.tmpdir(), 'tailwindcss-oxide-')) + try { + let file = path.join(dir, 'index.html') + await fs.writeFile(file, '
') + + let scanner = new Scanner({}) + expect(scanner.getCandidatesWithPositions({ file, extension: 'html' })).toEqual( + expect.arrayContaining([ + { candidate: 'flex', position: 12 }, + { candidate: 'underline', position: 17 }, + ]), + ) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) + +test('throws when the `file` cannot be read', () => { + let scanner = new Scanner({}) + let file = path.join(__dirname, 'does-not-exist.html') + + expect(() => scanner.getCandidatesWithPositions({ file, extension: 'html' })).toThrow( + `Failed to read file \`${file}\``, + ) +}) + +test('throws when neither `content` nor `file` is given', () => { + let scanner = new Scanner({}) + + expect(() => scanner.getCandidatesWithPositions({ extension: 'html' })).toThrow( + 'Either `content` or `file` must be provided', + ) +}) + +test('`scanFiles` throws when an entry has neither `content` nor `file`', () => { + let scanner = new Scanner({}) + + expect(() => + scanner.scanFiles([ + { content: '
', extension: 'html' }, + { extension: 'html' }, + ]), + ).toThrow('Either `content` or `file` must be provided') +})