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
23 changes: 23 additions & 0 deletions src/core/classDetector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ export interface ClassRange {
range: vscode.Range
}

const warnedInvalidSupportedFunctionPatterns = new Set<string>()

function warnInvalidSupportedFunctionPattern(pattern: string, error: unknown) {
if (warnedInvalidSupportedFunctionPatterns.has(pattern)) {
return
}

warnedInvalidSupportedFunctionPatterns.add(pattern)

const suffix = error instanceof Error && error.message ? `: ${error.message}` : ""
vscode.window.showWarningMessage(
`Tailwind Stash: invalid supportedFunctions regex "${pattern}" was ignored${suffix}`,
)
}

/**
* Detects Tailwind class strings in a document, including those wrapped
* in utility functions like cn(), clsx(), cva(), twMerge(), etc.
Expand Down Expand Up @@ -53,6 +68,14 @@ export function detectClassRanges(
// Strip ^/$ anchors — they don't work inside a group in a larger regex.
// Use \b boundaries instead for correct matching.
const cleaned = regexMatch[1].replace(/^\^/, "").replace(/\$$/, "")
try {
// Validate the pattern compiles; the constructor throws SyntaxError on invalid syntax.
// oxlint-disable-next-line no-new -- constructed only to validate; result intentionally unused
new RegExp(cleaned)
} catch (error) {
warnInvalidSupportedFunctionPattern(fn, error)
continue
}
regexPatterns.push(`\\b${cleaned}`)
} else {
literalNames.push(escapeRegex(fn))
Expand Down
1 change: 1 addition & 0 deletions test/__mocks__/vscode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ export const window = {
onDidChangeVisibleTextEditors: makeEventEmitter("onDidChangeVisibleTextEditors"),
showInformationMessage(_msg: string) {},
showTextDocument() {},
showWarningMessage(_msg: string) {},
visibleTextEditors: [] as unknown[],
}

Expand Down
38 changes: 36 additions & 2 deletions test/core/classDetector.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest"
import { afterEach, describe, expect, it, vi } from "vitest"

import { createMockDocument } from "../__mocks__/vscode"
import { createMockDocument, window } from "../__mocks__/vscode"
import { detectClassRanges } from "../../src/core/classDetector"

const defaultFunctions = [
Expand All @@ -14,6 +14,10 @@ const defaultFunctions = [
"classnames",
]

afterEach(() => {
vi.restoreAllMocks()
})

function detect(text: string, opts?: { functions?: string[]; minClasses?: number }) {
const doc = createMockDocument(text)
return detectClassRanges(doc, opts?.functions ?? defaultFunctions, opts?.minClasses ?? 4)
Expand Down Expand Up @@ -432,6 +436,36 @@ describe("empty and invalid function patterns", () => {
expect(results[0].element).toBe("div")
})

it("warns once and keeps valid detections when a regex pattern is invalid", () => {
const warningSpy = vi.spyOn(window, "showWarningMessage")
const text = `
const a = cn("flex items-center p-4 rounded");
const b = getButtonClasses("grid gap-4 p-6 bg-white");
<div class="text-sm font-bold mt-2 mx-auto"></div>
`

const results = detect(text, {
functions: ["cn", "/[invalid(/", "/^get.*Classes$/"],
})

expect(results).toHaveLength(3)
expect(warningSpy).toHaveBeenCalledTimes(1)
expect(warningSpy.mock.calls[0]?.[0]).toContain("/[invalid(/")
})

it("does not repeat the warning for the same invalid regex pattern", () => {
const warningSpy = vi.spyOn(window, "showWarningMessage")

detect('<div class="flex items-center p-4 rounded">', {
functions: ["/[still-invalid(/"],
})
detect('<div class="flex items-center p-4 rounded">', {
functions: ["/[still-invalid(/"],
})

expect(warningSpy).toHaveBeenCalledTimes(1)
})

it("returns results gracefully when regex pattern is invalid", () => {
const results = detect('<div class="flex items-center p-4 rounded">', {
functions: ["/[invalid(/"],
Expand Down