Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/oxide-candidates-with-positions-errors.md
Original file line number Diff line number Diff line change
@@ -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
68 changes: 41 additions & 27 deletions crates/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,27 @@ pub struct SourceEntry {
pub negated: bool,
}

impl From<ChangedContent> 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<ChangedContent> for tailwindcss_oxide::ChangedContent {
type Error = napi::Error;

fn try_from(changed_content: ChangedContent) -> napi::Result<Self> {
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))
}
}

Expand Down Expand Up @@ -134,38 +144,42 @@ impl Scanner {
}

#[napi]
pub fn scan_files(&mut self, input: Vec<ChangedContent>) -> Vec<String> {
self
.scanner
.scan_content(input.into_iter().map(Into::into).collect())
pub fn scan_files(&mut self, input: Vec<ChangedContent>) -> napi::Result<Vec<String>> {
let input = input
.into_iter()
.map(TryInto::try_into)
.collect::<napi::Result<Vec<_>>>()?;

Ok(self.scanner.scan_content(input))
}

#[napi]
pub fn get_candidates_with_positions(
&mut self,
input: ChangedContent,
) -> Vec<CandidateWithPosition> {
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<Vec<CandidateWithPosition>> {
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)]
Expand Down
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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, '<div class="flex underline"></div>')

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: '<div class="flex">', extension: 'html' },
{ extension: 'html' },
]),
).toThrow('Either `content` or `file` must be provided')
})