Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🚦 feat: Lint Disabled Dims That Compose No Disabled Recipe (#16907)
Marco Berettaadb04422bf7a
diff --git a/.github/workflows/static-checks.yml b/.github/workflows/static-checks.ymlindex b46cc86c16..98d6f1c5e2 100644--- a/.github/workflows/static-checks.yml+++ b/.github/workflows/static-checks.yml@@ -65,6 +65,7 @@ jobs:- '!**.md'eslint_config:- 'eslint.config.mjs'+ - 'scripts/eslint/**'- '.github/workflows/static-checks.yml'# The recorded design-rule backlog is data the lint reads, not code it# lints, so a diff that only edits it matches no source file. Its own@@ -83,6 +84,9 @@ jobs:- 'packages/client/tsdown.config.mjs'- 'packages/client/tsconfig.json'- 'eslint.config.mjs'+ # The local design rules: a change to what one reports changes+ # every count it owns.+ - 'scripts/eslint/**'# The plugin is a dependency: a bump changes what the rules# classify and a removal takes them with it, and neither touches a# source file.@@ -307,6 +311,7 @@ jobs:run: |node_modules/.bin/eslint --config eslint.config.mjs \api/server/index.js client/src/main.jsx packages/api/src/index.ts+ node --test scripts/eslint/design.test.mjs- name: Validate the design-rule suppressions baselineid: suppressions@@ -781,6 +786,7 @@ jobs:filters: |eslint_config:- 'eslint.config.mjs'+ - 'scripts/eslint/**'- '.github/workflows/static-checks.yml'- name: Set up Node.js 24.16.0diff --git a/e2e/specs/mock/scenarios/design-rule-enforcement.spec.ts b/e2e/specs/mock/scenarios/design-rule-enforcement.spec.tsindex b436c85b69..bc4f39eeb7 100644--- a/e2e/specs/mock/scenarios/design-rule-enforcement.spec.ts+++ b/e2e/specs/mock/scenarios/design-rule-enforcement.spec.ts@@ -131,6 +131,7 @@ test.describe('design-system rules', () => {'shadcn/no-inline-styles': 2,'shadcn/require-static-classes': 2,'shadcn/no-unknown-classes': 2,+ 'design/disabled-recipe': 2,};const library: Record<string, number> = {...caller,@@ -146,8 +147,13 @@ test.describe('design-system rules', () => {['packages/client/src', library],] as const) {for (const directory of sourceDirectories(root)) {+ /** Tests assert class strings rather than style a control, so the disabled-recipe rule+ * is off under a `__tests__` directory; every other rule still holds there. */+ const profile = /(?:^|\/)__tests__(?:\/|$)/.test(directory)+ ? { ...expected, 'design/disabled-recipe': 0 }+ : expected;for (const extension of ['ts', 'tsx', 'js', 'jsx']) {- probes[`${directory}/__coverage_probe__.${extension}`] = expected;+ probes[`${directory}/__coverage_probe__.${extension}`] = profile;}}}@@ -157,8 +163,10 @@ test.describe('design-system rules', () => {expect(Object.keys(probes).length, 'the roots hold no source directories').toBeGreaterThan(50);const resolved = designRuleSeverities(Object.keys(probes));+ const canonical = (severities: Record<string, number> = {}): string =>+ JSON.stringify(Object.entries(severities).sort(([a], [b]) => a.localeCompare(b)));const outside = Object.entries(probes)- .filter(([path, expected]) => JSON.stringify(resolved[path]) !== JSON.stringify(expected))+ .filter(([path, expected]) => canonical(resolved[path]) !== canonical(expected)).map(([path]) => `${path}: ${JSON.stringify(resolved[path])}`);expect(outside, 'a path the design rules no longer police as expected').toEqual([]);});diff --git a/e2e/specs/mock/scenarios/disabled-recipe.spec.ts b/e2e/specs/mock/scenarios/disabled-recipe.spec.tsnew file mode 100644index 0000000000..0932560e91--- /dev/null+++ b/e2e/specs/mock/scenarios/disabled-recipe.spec.ts@@ -0,0 +1,64 @@+import { join, resolve } from 'node:path';+import { rmSync, writeFileSync } from 'node:fs';+import { expect, test } from '@playwright/test';+import type { LintMessage } from './lint.helpers';+import { inOneProject, repoRoot, run } from './lint.helpers';++/**+ * A theme with `disabledStyle: fill` paints a disabled control through the shared recipes; a+ * class list that fades it with its own `opacity-*` keeps fading it under that theme. The+ * configured lint run is what a contributor meets, so the scenario runs it over a probe file.+ */++const ESLINT = resolve(repoRoot, 'node_modules/.bin/eslint');+const RULE = 'design/disabled-recipe';++test.describe('the disabled-recipe design rule', () => {+ test('a disabled dim without a shared recipe fails the design lint @scenario:a-disabled-dim-without-a-shared-recipe-fails-the-design-lint', () => {+ inOneProject();+ test.setTimeout(180_000);++ const probe = 'client/src/__disabled_recipe_probe__.tsx';+ const probePath = join(repoRoot, probe);+ const header = "import { cn, Button, disabledFillClasses } from '@librechat/client';\n";+ const lint = (body: string): LintMessage[] => {+ writeFileSync(probePath, `${header}${body}`);+ const result = run(ESLINT, ['--format', 'json', '--no-warn-ignored', '--', probe]);+ const [report] = JSON.parse(result.stdout) as { messages: LintMessage[] }[];+ return report.messages.filter((message) => message.ruleId === RULE);+ };++ try {+ const faded = lint(+ 'export const A = ({ disabled }: { disabled: boolean }) => (\n' ++ " <input disabled={disabled} className={cn('px-2 disabled:opacity-50', disabled && 'cursor-not-allowed')} />\n" ++ ');\n',+ );+ expect(faded.map((message) => message.message).join('\n')).toContain(+ '`disabled:opacity-50` dims a disabled control without a disabled recipe',+ );++ const chosen = lint(+ "export const A = ({ disabled }: { disabled: boolean }) => <span className={cn(disabled ? 'opacity-50' : '')} />;\n",+ );+ expect(chosen, 'a dim a disabled condition chooses').toHaveLength(1);++ const otherBranch = lint(+ "export const A = ({ disabled }: { disabled: boolean }) => <span className={cn(disabled ? 'opacity-50' : disabledFillClasses)} />;\n",+ );+ expect(otherBranch, 'a recipe only on the branch the dim is not on').toHaveLength(1);++ const composed = lint(+ "export const A = () => <input className={cn('px-2 disabled:opacity-50', disabledFillClasses)} />;\n",+ );+ expect(composed, 'a dim composed with the recipe').toEqual([]);++ const primitive = lint(+ 'export const A = () => <Button className="disabled:opacity-80">Go</Button>;\n',+ );+ expect(primitive, 'a dim on a primitive that composes the recipe').toEqual([]);+ } finally {+ rmSync(probePath, { force: true });+ }+ });+});diff --git a/e2e/specs/mock/scenarios/lint.helpers.ts b/e2e/specs/mock/scenarios/lint.helpers.tsindex 5115b17ec2..ffce5ed5ba 100644--- a/e2e/specs/mock/scenarios/lint.helpers.ts+++ b/e2e/specs/mock/scenarios/lint.helpers.ts@@ -120,9 +120,12 @@ export function lintFile(relativePath: string): LintMessage[] {);}+/** The design rules: `@shadcn/lint`'s and the local `design` plugin's. */+const isDesignRule = (ruleId: string): boolean => /^(?:shadcn|design)\//.test(ruleId);+/** Only the design-system rules; the probes carry no other interesting output. */export function designMessages(messages: LintMessage[]): LintMessage[] {- return messages.filter((message) => message.ruleId?.startsWith('shadcn/'));+ return messages.filter((message) => message.ruleId != null && isDesignRule(message.ruleId));}export const messagesFor = (messages: LintMessage[], ruleId: string): string[] =>@@ -149,7 +152,7 @@ export function designRuleSeverities(paths: string[]): Record<string, Record<strconst config = await eslint.calculateConfigForFile(path);const severities = {};for (const [rule, setting] of Object.entries(config.rules ?? {})) {- if (rule.startsWith('shadcn/')) {+ if (rule.startsWith('shadcn/') || rule.startsWith('design/')) {severities[rule] = Array.isArray(setting) ? setting[0] : setting;}}diff --git a/e2e/specs/mock/scenarios/suppression-baseline.spec.ts b/e2e/specs/mock/scenarios/suppression-baseline.spec.tsindex dfd67542b0..5f1b0e629a 100644--- a/e2e/specs/mock/scenarios/suppression-baseline.spec.ts+++ b/e2e/specs/mock/scenarios/suppression-baseline.spec.ts@@ -628,6 +628,11 @@ test.describe('the recorded design-rule backlog', () => {join(emptyRoot, 'scripts/static-checks.mts'),);copyFileSync(resolve(repoRoot, 'scripts/i18n.mts'), join(emptyRoot, 'scripts/i18n.mts'));+ mkdirSync(join(emptyRoot, 'scripts/eslint'), { recursive: true });+ copyFileSync(+ resolve(repoRoot, 'scripts/eslint/design.mjs'),+ join(emptyRoot, 'scripts/eslint/design.mjs'),+ );copyFileSync(resolve(repoRoot, 'package.json'), join(emptyRoot, 'package.json'));symlinkSync(resolve(repoRoot, 'node_modules'), join(emptyRoot, 'node_modules'), 'dir');const deleted = run(@@ -1096,6 +1101,8 @@ function syntheticRoot(): string {for (const file of ['scripts/static-checks.mts','scripts/i18n.mts',+ /** The local design rules the config registers and the runner validates against. */+ 'scripts/eslint/design.mjs','package.json','package-lock.json','eslint.config.mjs',diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex af58b19616..4ede20e964 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -40,16 +40,36 @@"count": 2}},+ "client/src/components/Auth/PasskeySignIn.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Auth/TwoFactorScreen.tsx": {"shadcn/no-restyle": {"count": 1}},+ "client/src/components/Chat/BackgroundTasks/Button.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },+ "client/src/components/Chat/BackgroundTasks/Card.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/ChatView.tsx": {"shadcn/no-restyle": {"count": 1}},+ "client/src/components/Chat/ExportAndShareMenu.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Input/AskUserQuestionPopover.tsx": {"shadcn/no-restyle": {"count": 6@@ -69,11 +89,31 @@"count": 2}},+ "client/src/components/Chat/Input/CodeApprovalMenu.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },+ "client/src/components/Chat/Input/CodeWorkspaceMenu.tsx": {+ "design/disabled-recipe": {+ "count": 2+ }+ },+ "client/src/components/Chat/Input/Composer/Files.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Input/ConversationStarters.tsx": {"shadcn/no-inline-styles": {"count": 2}},+ "client/src/components/Chat/Input/EscalateNowButton.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Input/Files/DragDropOverlay.tsx": {"shadcn/no-inline-styles": {"count": 3@@ -115,12 +155,20 @@"count": 1}},+ "client/src/components/Chat/Input/Files/Table/ColumnVisibilityDropdown.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Input/Files/Table/Columns.tsx": {"shadcn/no-restyle": {"count": 18}},"client/src/components/Chat/Input/Files/Table/DataTable.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 13}@@ -148,11 +196,21 @@"count": 1}},+ "client/src/components/Chat/Input/Reasoning.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Input/TokenUsage/Breakdown.tsx": {"shadcn/no-restyle": {"count": 10}},+ "client/src/components/Chat/Input/chip.ts": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Landing.tsx": {"shadcn/no-restyle": {"count": 14@@ -161,6 +219,11 @@"count": 2}},+ "client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Menus/Presets/EditPresetDialog.tsx": {"shadcn/no-restyle": {"count": 2@@ -176,6 +239,11 @@"count": 2}},+ "client/src/components/Chat/Menus/UI/MenuItem.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx": {"shadcn/no-arbitrary-values": {"count": 2@@ -211,11 +279,17 @@}},"client/src/components/Chat/Messages/Content/EditContentParts.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 10}},"client/src/components/Chat/Messages/Content/EditMessage.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 9}@@ -299,6 +373,11 @@"count": 1}},+ "client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Messages/Content/Parts/Summary.tsx": {"shadcn/no-arbitrary-values": {"count": 1@@ -331,6 +410,11 @@"count": 1}},+ "client/src/components/Chat/Messages/Content/SiblingHeader.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Chat/Messages/Content/ToolApproval.tsx": {"shadcn/no-restyle": {"count": 26@@ -428,6 +512,9 @@}},"client/src/components/Chat/Messages/MessageNav.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-arbitrary-values": {"count": 1}@@ -476,6 +563,9 @@}},"client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-arbitrary-values": {"count": 1},@@ -526,6 +616,11 @@"count": 5}},+ "client/src/components/Conversations/ChatFilterMenu.tsx": {+ "design/disabled-recipe": {+ "count": 3+ }+ },"client/src/components/Conversations/Convo.tsx": {"shadcn/no-inline-styles": {"count": 1@@ -587,6 +682,9 @@}},"client/src/components/Endpoints/Settings/Advanced.tsx": {+ "design/disabled-recipe": {+ "count": 2+ },"shadcn/no-restyle": {"count": 18},@@ -668,6 +766,11 @@"count": 3}},+ "client/src/components/Messages/Content/ActionButton.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Messages/Content/Error/parts.tsx": {"shadcn/no-arbitrary-values": {"count": 1@@ -700,7 +803,20 @@"count": 24}},+ "client/src/components/Messages/Content/Mermaid/ZoomControls.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },+ "client/src/components/Messages/Content/ResultSwitcher.tsx": {+ "design/disabled-recipe": {+ "count": 2+ }+ },"client/src/components/Messages/Content/RunCode.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 4}@@ -716,6 +832,9 @@}},"client/src/components/Nav/KeyboardShortcutsDialog.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-arbitrary-values": {"count": 4},@@ -723,6 +842,11 @@"count": 9}},+ "client/src/components/Nav/NavLink.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Nav/NavToggle.tsx": {"shadcn/no-inline-styles": {"count": 4@@ -997,6 +1121,9 @@}},"client/src/components/SidePanel/Agents/FileContext.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 14}@@ -1012,11 +1139,17 @@}},"client/src/components/SidePanel/Agents/ModelPanel.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 12}},"client/src/components/SidePanel/Agents/OptionToggle.tsx": {+ "design/disabled-recipe": {+ "count": 1+ },"shadcn/no-restyle": {"count": 2},@@ -1069,6 +1202,11 @@"count": 5}},+ "client/src/components/SidePanel/Agents/UploadDropzone.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/SidePanel/Agents/Version/VersionItem.tsx": {"shadcn/no-restyle": {"count": 7@@ -1094,6 +1232,16 @@"count": 1}},+ "client/src/components/SidePanel/Builder/ActionsInput.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },+ "client/src/components/SidePanel/Builder/ActionsPanel.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/SidePanel/Builder/AssistantConversationStarters.tsx": {"shadcn/no-restyle": {"count": 8@@ -1112,6 +1260,11 @@"count": 7}},+ "client/src/components/SidePanel/Builder/Retrieval.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx": {"shadcn/no-restyle": {"count": 1@@ -1205,6 +1358,11 @@"count": 9}},+ "client/src/components/Skills/dialogs/UploadSkillDialog.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"client/src/components/Skills/display/SkillDetail.tsx": {"shadcn/no-restyle": {"count": 1@@ -1306,6 +1464,9 @@}},"client/src/components/Web/Sources.tsx": {+ "design/disabled-recipe": {+ "count": 2+ },"shadcn/no-arbitrary-values": {"count": 1},@@ -1336,6 +1497,16 @@"count": 3}},+ "client/src/utils/index.ts": {+ "design/disabled-recipe": {+ "count": 2+ }+ },+ "packages/client/src/components/Badge.tsx": {+ "design/disabled-recipe": {+ "count": 1+ }+ },"packages/client/src/components/Combobox.tsx": {"shadcn/no-inline-styles": {"count": 1@@ -1361,6 +1532,11 @@"count": 1}},+ "packages/client/src/components/OGDialogTemplate.tsx": {+ "design/disabled-recipe": {+ "count": 2+ }+ },"packages/client/src/components/Radio.tsx": {"shadcn/no-inline-styles": {"count": 1diff --git a/eslint.config.mjs b/eslint.config.mjsindex 49b48793ba..ee1e7adee5 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -14,6 +14,7 @@ import react from 'eslint-plugin-react';import jest from 'eslint-plugin-jest';import globals from 'globals';import js from '@eslint/js';+import design from './scripts/eslint/design.mjs';const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);@@ -199,7 +200,7 @@ export default [// name those extensions too: the rules have to see them.{files: ['client/src/**/*.{ts,tsx,js,jsx}', 'packages/client/src/**/*.{ts,tsx,js,jsx}'],- plugins: { shadcn },+ plugins: { shadcn, design },settings: {shadcn: {ui: '@librechat/client',@@ -265,6 +266,15 @@ export default [},],'shadcn/require-static-classes': 'error',+ // A disabled control that fades through `opacity-*` also has to compose a shared disabled+ // recipe, or a theme with `disabledStyle: fill` cannot paint it (scripts/eslint/design.mjs).+ 'design/disabled-recipe': [+ 'error',+ {+ primitives: ['Button', 'IconButton', 'Input', 'Textarea', 'Checkbox', 'Switch'],+ sources: ['@librechat/client'],+ },+ ],// Now answerable: the rule asks the installed Tailwind whether a class generates CSS, and// the app is on v4. Classes declared in a stylesheet Tailwind reads are recognized on their// own; these are the ones it cannot see, plain selectors in files loaded separately@@ -324,6 +334,18 @@ export default [],},},+ {+ // A spec asserts the class strings a control renders; it composes nothing a theme paints.+ files: [+ 'client/src/**/*.{spec,test}.{ts,tsx,js,jsx}',+ 'client/src/**/__tests__/**/*.{ts,tsx,js,jsx}',+ 'packages/client/src/**/*.{spec,test}.{ts,tsx,js,jsx}',+ 'packages/client/src/**/__tests__/**/*.{ts,tsx,js,jsx}',+ ],+ rules: {+ 'design/disabled-recipe': 'off',+ },+ },{// A primitive owns its own internals, so the rules that police callers are off inside the// component library. `no-raw-colors` and `no-inline-styles` stay on: the primitives arediff --git a/package.json b/package.jsonindex a7f2a65b81..12cc394b80 100644--- a/package.json+++ b/package.json@@ -114,7 +114,7 @@"e2e:report": "npx playwright show-report e2e/playwright-report","lint:fix": "npm run build:client-package && eslint . --fix --pass-on-unpruned-suppressions","lint": "npm run build:client-package && eslint . --pass-on-unpruned-suppressions",- "lint:design:record": "npm run build:client-package && eslint --no-warn-ignored --suppress-rule shadcn/no-restyle --suppress-rule shadcn/no-raw-colors --suppress-rule shadcn/no-arbitrary-values --suppress-rule shadcn/no-inline-styles --suppress-rule shadcn/require-static-classes --suppress-rule shadcn/no-unknown-classes client/src packages/client/src",+ "lint:design:record": "npm run build:client-package && eslint --no-warn-ignored --suppress-rule shadcn/no-restyle --suppress-rule shadcn/no-raw-colors --suppress-rule shadcn/no-arbitrary-values --suppress-rule shadcn/no-inline-styles --suppress-rule shadcn/require-static-classes --suppress-rule shadcn/no-unknown-classes --suppress-rule design/disabled-recipe client/src packages/client/src","lint:design:suppress": "(npm run --silent lint:design:record || node -e \"\") && npm run lint:design:prune","lint:design:prune": "npm run build:client-package && eslint --no-warn-ignored --prune-suppressions client/src packages/client/src","sort-imports": "node scripts/sort-imports.mts",diff --git a/scripts/eslint/design.mjs b/scripts/eslint/design.mjsnew file mode 100644index 0000000000..ed66bc9e44--- /dev/null+++ b/scripts/eslint/design.mjs@@ -0,0 +1,791 @@+import { dirname, resolve } from 'node:path';++/**+ * Design rules `@shadcn/lint` does not cover, registered as the `design` plugin in+ * `eslint.config.mjs` and recorded in `eslint-suppressions.json` like its rules.+ */++/** The shared disabled recipes (`packages/client/src/utils/theme.ts`) and the element each one+ * restores: the control itself (`theme-disabled`), a wrapper around it (`theme-disabled-within`)+ * or a label that follows it through `peer`. */+const RECIPES = new Map([+ ['disabledFillClasses', 'self'],+ ['disabledInkClasses', 'self'],+ ['disabledWithinFillClasses', 'within'],+ ['peerDisabledInkClasses', 'peer'],+]);++/** The full-opacity override every recipe carries, so a class list that spells one out also+ * counts; another `theme-disabled:` utility alone still leaves the control faded. */+const RECIPE_VARIANTS = [+ [/(?:^|\s)theme-disabled:(!?)opacity-100(!?)(?=\s|$)/, 'self'],+ [/(?:^|\s)theme-disabled-within:(!?)opacity-100(!?)(?=\s|$)/, 'within'],+ [/(?:^|\s)peer-theme-disabled:(!?)opacity-100(!?)(?=\s|$)/, 'peer'],+];++/** Where the shared primitives live, for a relative import inside the component library. */+const PRIMITIVES_DIR = /packages[\\/]client[\\/]src[\\/]components[\\/]([\w.-]+?)(?:\.tsx?)?$/;++/** The file that defines the recipes, where a local binding with a recipe's name is the recipe. */+const RECIPES_FILE = /packages[\\/]client[\\/]src[\\/]utils[\\/]theme\.ts$/;+const COMPONENT_LIBRARY = /packages[\\/]client[\\/]src[\\/]/;+/** The recipes' module and the barrel that re-exports it, for a relative import. */+const RECIPES_MODULE = /packages[\\/]client[\\/]src[\\/]utils(?:[\\/](?:theme|index))?(?:\.ts)?$/;++/** Whether an import of a recipe's name comes from the module that defines the recipes: the+ * package, or inside the component library its `~/utils` alias or a relative path to it. */+function isRecipeSource(from, filename) {+ if (from === '@librechat/client') return true;+ if (!COMPONENT_LIBRARY.test(filename)) return false;+ if (from === '~/utils' || from === '~/utils/theme') return true;+ return from.startsWith('.') && RECIPES_MODULE.test(resolve(dirname(filename), from));+}++/** A variant that selects a disabled control, its group, its peer or a wrapper around it:+ * `disabled:`, `aria-disabled:`, `data-[state=disabled]:`, `has-[:disabled]:`, `[&:disabled]:`.+ * The recipes' own `theme-disabled`, a negated `not-disabled` or `[&:not(:disabled)]` and an+ * explicit `[disabled=false]` select something else. */+const isDisabledVariant = (variant) =>+ /disabled(?![-\w])/.test(variant) &&+ !/^supports-/.test(variant) &&+ !/^(?:(?:group|peer)-)?(?:theme-disabled|not-)/.test(variant) &&+ !/:not\([^)]*disabled/.test(variant) &&+ !/(?:not|non)[-_]?disabled/.test(variant) &&+ !/disabled\s*!?=\s*["']?false\b|disabled\s*!=/.test(variant);++/** Which element a disabled variant fades: the control, a wrapper that has one, a label that+ * follows one through `peer`, or a descendant of a disabled `group` or of an ancestor an+ * arbitrary selector names (`[tr[data-disabled=true]_&]`), which no recipe restores. */+function topologyOf(variant) {+ if (/^peer-/.test(variant)) {+ return SELF_MARKERS.test(variant.slice('peer-'.length)) ? 'peer' : 'group';+ }+ if (/^group-/.test(variant)) return 'group';+ if (/^\[(?!&)/.test(variant)) return 'group';+ if (/^has-|:has\(/.test(variant)) return WITHIN_MARKERS.test(variant) ? 'within' : 'group';+ return SELF_MARKERS.test(variant) ? 'self' : 'group';+}++/** The wrapper markers `theme-disabled-within` matches: a `:disabled` descendant. */+const WITHIN_MARKERS = /^(?:has-\[:disabled\]|has-disabled|\[&:has\(:disabled\)\])$/;++/** A modifier that moves the utility onto a descendant (`[&_svg]`, `*`), which no recipe on the+ * control restores. */+const isDescendantModifier = (variant) => /^\[&[\s_>~+]/.test(variant) || /^\*{1,2}$/.test(variant);++/** The disabled markers `theme-disabled` matches (`:disabled`, `[data-disabled]`,+ * `[aria-disabled='true']`); a self variant spelled with another marker, such as+ * `data-[state=disabled]`, is one no recipe restores. */+const SELF_MARKERS =+ /^(?:disabled|aria-disabled|data-disabled|data-\[disabled(?:=["']?true["']?)?\]|aria-\[disabled=["']?true["']?\]|\[&:disabled\]|\[&\[data-disabled\]\]|\[&\[aria-disabled=["']?true["']?\]\])$/;++const TOPOLOGY_ORDER = ['group', 'peer', 'within', 'self'];++/** Ancestors that keep a class string inside one class list: the expression a recipe is+ * composed into reaches up through these, and stops at a declaration or an attribute. */+const COMPOSING = new Set([+ 'ArrayExpression',+ 'BinaryExpression',+ 'CallExpression',+ 'ConditionalExpression',+ 'JSXExpressionContainer',+ 'LogicalExpression',+ 'ObjectExpression',+ 'Property',+ 'SpreadElement',+ 'TSAsExpression',+ 'TSSatisfiesExpression',+ 'TemplateLiteral',+]);++/** Splits a utility into its variants and its base, leaving `:` inside brackets alone. */+function splitVariants(token) {+ const parts = [];+ let depth = 0;+ let current = '';+ for (const char of token) {+ if (char === '[') depth += 1;+ if (char === ']') depth -= 1;+ if (char === ':' && depth === 0) {+ parts.push(current);+ current = '';+ continue;+ }+ current += char;+ }+ parts.push(current);+ return { variants: parts.slice(0, -1), base: parts[parts.length - 1] };+}++/** An opacity that fades: `opacity-100` (or `opacity-100!`) keeps the control opaque, so it is+ * not a dim. */+const isOpacity = (base) =>+ /^!?opacity-/.test(base) && !/^!?opacity-(?:100|\[100%\]|\[1(?:\.0+)?\])!?$/.test(base);++const isImportant = (base) => base.startsWith('!') || base.endsWith('!');++/** Every utility in `value` that dims a disabled control through a variant, with the element+ * it fades. */+function variantDims(value) {+ return value.split(/\s+/).flatMap((token) => {+ const { variants, base } = splitVariants(token);+ const selecting = isOpacity(base) ? variants.filter(isDisabledVariant) : [];+ if (selecting.length === 0) return [];+ /** A stacked utility (`disabled:group-disabled:opacity-50`) needs the recipe for its most+ * distant element, which a recipe for a nearer one cannot restore. */+ const topologies = selecting.map(topologyOf);+ if (variants.some(isDescendantModifier)) topologies.push('group');+ const topology = TOPOLOGY_ORDER.find((candidate) => topologies.includes(candidate));+ return [{ dim: token, topology, important: isImportant(base), variant: true }];+ });+}++/** The first fading `opacity-*` in `value` that no disabled variant already selects, for a+ * string a `disabled` condition chooses (`opacity-50`, `sm:opacity-50`), restored by the recipe+ * for the element it sits on. */+function bareDims(value, topology) {+ return value.split(/\s+/).flatMap((token) => {+ const { variants, base } = splitVariants(token);+ if (!isOpacity(base) || variants.some(isDisabledVariant)) return [];+ const distant = variants.some(isDescendantModifier);+ return [{ dim: token, topology: distant ? 'group' : topology, important: isImportant(base) }];+ });+}++/** Whether a shared recipe restores a dim: it targets the dim's element, and the dim is not+ * `!important`, which no shared recipe outranks. */+const covers = (recipe, need) =>+ recipe !== undefined && !need.important && (need.topology === 'any' || recipe === need.topology);++/** The variable a name resolves to from `scope`, or `undefined` when nothing declares it. */+function findVariable(scope, name) {+ for (let current = scope; current; current = current.upper) {+ const variable = current.set.get(name);+ if (variable) return variable;+ }+ return undefined;+}++/** Whether `test` holds only while the control is disabled (`true`), only while it is enabled+ * (`false`), or says nothing certain about it (`undefined`). `known` holds the element's own+ * `disabled` and `aria-disabled` expressions, so a condition spelled the same way counts+ * whatever its name. A `!` or a comparison to `false` flips the sense; an `&&` takes the sense+ * of any operand that has one, and anything else that is not a plain reference to a `disabled`+ * value is unknown. */+function disabledSense(test, source, known) {+ const text = source.getText(test);+ if (known.has(text)) return known.get(text);+ if (test.type === 'UnaryExpression' && test.operator === '!') {+ const inner = disabledSense(test.argument, source, known);+ return inner === undefined ? undefined : !inner;+ }+ if (test.type === 'BinaryExpression' && /^[!=]==?$/.test(test.operator)) {+ const literal = [test.left, test.right].find((side) => side.type === 'Literal');+ if (!literal || typeof literal.value !== 'boolean') return undefined;+ const inner = disabledSense(literal === test.left ? test.right : test.left, source, known);+ if (inner === undefined) return undefined;+ const flips = literal.value === test.operator.startsWith('!');+ return flips ? !inner : inner;+ }+ if (test.type === 'LogicalExpression' && test.operator === '&&') {+ const senses = [+ disabledSense(test.left, source, known),+ disabledSense(test.right, source, known),+ ];+ const certain = senses.filter((sense) => sense !== undefined);+ return certain.length > 0 && certain.every((sense) => sense === certain[0])+ ? certain[0]+ : undefined;+ }+ if (['Identifier', 'MemberExpression', 'ChainExpression'].includes(test.type)) {+ return /disabled/i.test(text) && !/(?:not|non)_?disabled/i.test(text) ? true : undefined;+ }+ return undefined;+}++/** Wrappers a chosen string passes through on its way to the condition that picks it:+ * `disabled ? cn('opacity-50') : ''` picks the call, not the string. */+const PASSING = new Set([+ 'ArrayExpression',+ 'BinaryExpression',+ 'CallExpression',+ 'TSAsExpression',+ 'TSSatisfiesExpression',+ 'TemplateLiteral',+]);++/** Whether a `disabled` condition chooses the string: `disabled ? 'opacity-50' : ''`,+ * `isDisabled && 'opacity-50'`, `{ 'opacity-50': disabled }` in a class map, or a map that is+ * itself chosen (`disabled && { 'opacity-50': true }`). A string the condition picks for the+ * enabled state (`disabled ? '' : 'opacity-50'`) is not a disabled dim. */+const isDisabledName = (name) =>+ typeof name === 'string' && /disabled/i.test(name) && !/(?:not|non)_?disabled/i.test(name);++const keyName = (property) =>+ property?.type !== 'Property' || property.computed+ ? undefined+ : (property.key.name ?? String(property.key.value));++/** The sense of a `cva` option chosen by a boolean `disabled` variant: the `true` option of a+ * `disabled` group in `variants`, or the class of a `compoundVariants` entry that sets+ * `disabled: true`. */+/** The boolean a compound-variant value selects: `true`, `false`, or an array of only one of+ * them (`[true]`); a mixed or dynamic value says nothing. */+function booleanSelection(value) {+ if (value.type === 'Literal' && typeof value.value === 'boolean') return value.value;+ if (value.type !== 'ArrayExpression' || value.elements.length === 0) return undefined;+ const values = value.elements.map((element) =>+ element?.type === 'Literal' && typeof element.value === 'boolean' ? element.value : undefined,+ );+ return values.every((entry) => entry === values[0]) ? values[0] : undefined;+}++function cvaDisabledSense(property) {+ const name = keyName(property);+ const owner = property.parent;+ const group = owner?.parent;+ if (+ (name === 'true' || name === 'false') &&+ group?.type === 'Property' &&+ group.value === owner &&+ isDisabledName(keyName(group)) &&+ keyName(group.parent?.parent) === 'variants'+ ) {+ return name === 'true';+ }+ const compound =+ owner?.parent?.type === 'ArrayExpression' &&+ keyName(owner.parent.parent) === 'compoundVariants';+ if (compound && (name === 'class' || name === 'className')) {+ const flag = owner.properties.find(+ (entry) => entry.type === 'Property' && isDisabledName(keyName(entry)),+ );+ return flag ? booleanSelection(flag.value) : undefined;+ }+ return undefined;+}++function chosenByDisabled(start, source, known) {+ let node = start;+ while (+ node.parent &&+ PASSING.has(node.parent.type) &&+ !(node.parent.type === 'CallExpression' && node.parent.callee === node)+ ) {+ node = node.parent;+ }+ const parent = node.parent;+ if (parent?.type === 'ConditionalExpression' && parent.test !== node) {+ /** Reaching the alternate of `a || b` proves every operand false, so an operand that holds+ * only while enabled (`!disabled`) proves the control disabled. */+ if (+ parent.alternate === node &&+ parent.test.type === 'LogicalExpression' &&+ parent.test.operator === '||' &&+ [parent.test.left, parent.test.right].some(+ (operand) => disabledSense(operand, source, known) === false,+ )+ ) {+ return true;+ }+ const sense = disabledSense(parent.test, source, known);+ if (sense === undefined) return chosenByDisabled(parent, source, known);+ return sense === (parent.consequent === node);+ }+ if (parent?.type === 'LogicalExpression' && parent.right === node && parent.operator === '&&') {+ const sense = disabledSense(parent.left, source, known);+ if (sense === undefined) return chosenByDisabled(parent, source, known);+ return sense === true;+ }+ if (+ parent?.type === 'Property' &&+ parent.value === node &&+ parent.parent?.type === 'ObjectExpression'+ ) {+ return cvaDisabledSense(parent) === true;+ }+ if (parent?.type === 'Property' && parent.key === node) {+ const sense = disabledSense(parent.value, source, known);+ if (sense !== undefined) return sense;+ const always = parent.value.type === 'Literal' && parent.value.value === true;+ return always && chosenByDisabled(parent.parent, source, known);+ }+ return false;+}++/** Whether an object belongs to a call's arguments, as a class map or a `cva` config does,+ * rather than being a props or style object of its own. */+function isCallArgument(object) {+ let current = object;+ while (+ [+ 'ObjectExpression',+ 'Property',+ 'ArrayExpression',+ 'ConditionalExpression',+ 'LogicalExpression',+ ].includes(current.parent?.type)+ ) {+ current = current.parent;+ }+ return current.parent?.type === 'CallExpression' && current.parent.callee !== current;+}++/** The whole class list the string belongs to. An object counts only when it is passed to a+ * call; a property of any other object is a class list of its own. */+function classList(node) {+ let current = node;+ while (current.parent && COMPOSING.has(current.parent.type)) {+ const parent = current.parent;+ if (parent.type === 'Property' && !isCallArgument(parent.parent)) {+ return current;+ }+ current = parent;+ }+ return current;+}++/** The JSX element whose `className` the class list is, when it is one. */+function classNameElement(root) {+ const attribute = root.parent?.type === 'JSXAttribute' ? root.parent : undefined;+ return attribute?.name.name === 'className' ? attribute.parent : undefined;+}++const isCva = (call) => call.type === 'CallExpression' && call.callee.name === 'cva';++/** The helpers that join their arguments into one class list; another call's result is not+ * known to carry what it was given. */+const CLASS_CALLS = new Set(['cn', 'clsx', 'cx', 'classNames', 'twMerge', 'twJoin', 'cva']);+/** The modules the class helpers come from: the class libraries, the shared package, and the+ * `utils` module of either workspace (`~/utils`, or a relative path to it). */+const HELPER_SOURCES = new Set([+ 'clsx',+ 'classnames',+ 'tailwind-merge',+ 'class-variance-authority',+ '@librechat/client',+ '~/utils',+ '~/utils/',+]);+const isHelperSource = (from, filename) =>+ HELPER_SOURCES.has(from) ||+ (from.startsWith('.') &&+ /[\\/]utils(?:[\\/](?:index|cn))?(?:\.ts)?$/.test(resolve(dirname(filename), from)));++const isClassCall = (call, source, filename) => {+ if (call.type !== 'CallExpression') return false;+ const { callee } = call;+ const local = callee.type === 'MemberExpression' ? callee.object : callee;+ const name = callee.type === 'MemberExpression' ? callee.property.name : callee.name;+ if (local.type !== 'Identifier' || !CLASS_CALLS.has(name)) return false;+ /** An import from a helper module is trusted; a local function or an import from elsewhere+ * that merely shares the name is not. */+ const variable = findVariable(source.getScope(call), local.name);+ if (!variable) return true;+ const definition = variable.defs[0];+ return (+ definition?.type === 'ImportBinding' && isHelperSource(definition.parent.source.value, filename)+ );+};++/** Reads, for one class list, what a recipe reference resolves to and which strings and+ * expressions always emit one. */+function recipeReader(context) {+ const source = context.sourceCode;+ const inRecipesFile = RECIPES_FILE.test(context.filename);++ /** The recipe an identifier is: an import of one (under any local name), the recipe itself in+ * the file that defines it, or, when nothing declares the name, the name alone. A local that+ * shadows a recipe's name is not one. */+ const recipeOf = (identifier) => {+ const variable = findVariable(source.getScope(identifier), identifier.name);+ if (!variable) return RECIPES.get(identifier.name);+ const definition = variable.defs[0];+ if (definition?.type === 'ImportBinding') {+ const imported = definition.node.imported;+ if (!imported || !isRecipeSource(definition.parent.source.value, context.filename)) {+ return undefined;+ }+ return RECIPES.get(imported.name ?? imported.value);+ }+ return inRecipesFile ? RECIPES.get(identifier.name) : undefined;+ };++ /** The recipe `namespace.name` is, when `namespace` is the recipes' module imported whole (or,+ * when nothing declares it, by the name alone). */+ const memberRecipeOf = (member) => {+ const name = RECIPES.get(member.property.name);+ if (!name || member.object.type !== 'Identifier') return undefined;+ const variable = findVariable(source.getScope(member), member.object.name);+ if (!variable) return name;+ const definition = variable.defs[0];+ const whole =+ definition?.type === 'ImportBinding' && definition.node.type === 'ImportNamespaceSpecifier';+ return whole && isRecipeSource(definition.parent.source.value, context.filename)+ ? name+ : undefined;+ };++ /** A spelled-out recipe for the dim's element, `!important` when the dim is. */+ const stringCovers = (value, need) =>+ typeof value === 'string' &&+ RECIPE_VARIANTS.some(([pattern, recipe]) => {+ const match = pattern.exec(value);+ if (!match || !(need.topology === 'any' || recipe === need.topology)) return false;+ return !need.important || Boolean(match[1] || match[2]);+ });++ /** Whether `node` emits a recipe covering `need` (the dim's element and importance) on every+ * path through it. */+ const always = (node, topology) => {+ switch (node.type) {+ case 'Literal':+ return stringCovers(node.value, topology);+ case 'TemplateElement':+ return stringCovers(node.value.cooked, topology);+ case 'TemplateLiteral':+ return (+ node.quasis.some((quasi) => always(quasi, topology)) ||+ node.expressions.some((expression) => always(expression, topology))+ );+ case 'Identifier':+ return covers(recipeOf(node), topology);+ case 'MemberExpression':+ return !node.computed && covers(memberRecipeOf(node), topology);+ case 'CallExpression':+ if (isCva(node)) {+ const [base] = node.arguments;+ return base !== undefined && always(base, topology);+ }+ return (+ isClassCall(node, source, context.filename) &&+ node.arguments.some((argument) => always(argument, topology))+ );+ case 'ArrayExpression':+ return node.elements.some((element) => element && always(element, topology));+ case 'ConditionalExpression':+ return always(node.consequent, topology) && always(node.alternate, topology);+ case 'LogicalExpression':+ return (+ node.operator !== '&&' && always(node.left, topology) && always(node.right, topology)+ );+ case 'BinaryExpression':+ return (+ node.operator === '+' && (always(node.left, topology) || always(node.right, topology))+ );+ case 'ObjectExpression':+ return node.properties.some((property) => mapEntryAlways(property, topology));+ case 'SpreadElement':+ return always(node.argument, topology);+ case 'ChainExpression':+ case 'TSAsExpression':+ case 'TSSatisfiesExpression':+ case 'TSNonNullExpression':+ return always(node.expression, topology);+ default:+ return false;+ }+ };++ /** A class-map entry that is always on and names a covering recipe. */+ const mapEntryAlways = (property, topology) =>+ property.type === 'Property' &&+ property.value.type === 'Literal' &&+ property.value.value === true &&+ (property.computed+ ? always(property.key, topology)+ : stringCovers(property.key.value, topology));++ /** A sibling that always emits a covering recipe, or one guarded by the same condition as the+ * dim's own entry, on the same side: `cn(disabled && 'opacity-50', disabled && recipe)` or+ * `cn(disabled ? 'opacity-50' : '', disabled ? recipe : '')`. */+ /** A guard that holds while the element is disabled: its own disabled expression when the+ * element states one, otherwise a reference to a disabled value. */+ const guardMatches = (guard, known = new Map()) => {+ const stated = [...known.entries()].some(+ ([key, sense]) => typeof key === 'string' && sense === true,+ );+ return stated+ ? known.get(source.getText(guard)) === true+ : disabledSense(guard, source, known) === true;+ };++ const alongside = (sibling, child, start, topology) => {+ if (always(sibling, topology)) return true;+ /** `cn('disabled:opacity-50', disabled && recipe)`: a recipe the disabled state switches on+ * is there whenever a disabled variant can fade the element. */+ if (+ topology.variant &&+ sibling.type === 'LogicalExpression' &&+ sibling.operator === '&&' &&+ guardMatches(sibling.left, topology.known) &&+ always(sibling.right, topology)+ ) {+ return true;+ }+ const guarded = (node) => node.type === 'LogicalExpression' && node.operator === '&&';+ if (guarded(sibling) && guarded(child)) {+ return (+ source.getText(sibling.left) === source.getText(child.left) &&+ always(sibling.right, topology)+ );+ }+ if (sibling.type !== 'ConditionalExpression' || child.type !== 'ConditionalExpression') {+ return false;+ }+ if (source.getText(sibling.test) !== source.getText(child.test)) return false;+ let branch = start;+ while (branch.parent && branch.parent !== child) branch = branch.parent;+ const side = branch === child.consequent ? 'consequent' : 'alternate';+ return always(sibling[side], topology);+ };++ /** The parts of `parent` emitted whenever `child` is: the other arguments of a class helper,+ * the other entries of an array or template, the base of a `cva` around a variant (a variant+ * can be passed `null`, so it never proves one), and class map entries switched on by the same+ * condition. A condition's other branch is not. */+ const companions = (parent, child, start, topology) => {+ switch (parent.type) {+ case 'CallExpression': {+ if (parent.callee === child) return false;+ if (isCva(parent)) {+ const [base] = parent.arguments;+ return child !== base && base !== undefined && always(base, topology);+ }+ if (!isClassCall(parent, source, context.filename)) return false;+ return parent.arguments.some(+ (argument) => argument !== child && alongside(argument, child, start, topology),+ );+ }+ case 'ArrayExpression':+ return parent.elements.some(+ (element) => element && element !== child && alongside(element, child, start, topology),+ );+ case 'TemplateLiteral':+ return always(parent, topology);+ case 'BinaryExpression':+ return (+ parent.operator === '+' &&+ always(parent.left === child ? parent.right : parent.left, topology)+ );+ case 'ObjectExpression': {+ if (child.type !== 'Property') return false;+ const condition = source.getText(child.value);+ return parent.properties.some(+ (property) =>+ property !== child &&+ property.type === 'Property' &&+ (mapEntryAlways(property, topology) ||+ (source.getText(property.value) === condition &&+ (property.computed+ ? always(property.key, topology)+ : stringCovers(property.key.value, topology)))),+ );+ }+ default:+ return false;+ }+ };++ /** Whether a covering recipe is emitted on every path that emits the string at `start`,+ * looking no further than the class list it belongs to. */+ return (start, list, topology) => {+ if (always(start, topology)) return true;+ for (let child = start; child !== list && child.parent; child = child.parent) {+ if (companions(child.parent, child, start, topology)) return true;+ }+ return false;+ };+}++/** The component a JSX element names and the import it comes from: `<Button>` from its import,+ * `<ui.Checkbox>` from the namespace `ui` is imported as. */+function elementImport(element, source) {+ const name = element.name;+ const local = name.type === 'JSXMemberExpression' ? name.object : name;+ if (local.type !== 'JSXIdentifier') return undefined;+ const component = name.type === 'JSXMemberExpression' ? name.property.name : name.name;+ const variable = findVariable(source.getScope(element), local.name);+ if (!variable) return { component, from: undefined, declared: false };+ const definition = variable.defs[0];+ if (definition?.type !== 'ImportBinding') return { component, from: null, declared: true };+ const from = definition.parent.source.value;+ if (name.type === 'JSXMemberExpression') {+ const namespace = definition.node.type === 'ImportNamespaceSpecifier';+ return { component: namespace ? component : undefined, from, declared: true };+ }+ if (definition.node.type === 'ImportDefaultSpecifier') {+ return { component, from, declared: true };+ }+ const imported = definition.node.imported;+ return { component: imported?.name ?? imported?.value, from, declared: true };+}++/** The attributes `theme-disabled` reads as the element's own disabled state. */+const DISABLED_ATTRIBUTES = new Set(['disabled', 'aria-disabled', 'data-disabled']);++/** Marks an element that is disabled outright (`disabled`, `disabled={true}`,+ * `aria-disabled="true"`), where every fade on it is a disabled dim. */+const STATIC = Symbol('static');++/** The element's own `disabled` and `aria-disabled` expressions, with their negations, so a+ * condition spelled the same way reads as the disabled state whatever it is named. Any such+ * attribute also says the element is the control itself. */+function disabledExpressions(element, source) {+ const known = new Map();+ for (const attribute of element?.attributes ?? []) {+ if (attribute.type !== 'JSXAttribute') continue;+ if (!DISABLED_ATTRIBUTES.has(attribute.name.name)) continue;+ const literal = attribute.value?.type === 'Literal' ? attribute.value.value : undefined;+ const expression =+ attribute.value?.type === 'JSXExpressionContainer' ? attribute.value.expression : undefined;+ if (+ attribute.value == null ||+ literal === 'true' ||+ (expression?.type === 'Literal' && expression.value === true)+ ) {+ known.set(STATIC, true);+ continue;+ }+ if (!expression || expression.type === 'JSXEmptyExpression' || expression.type === 'Literal') {+ continue;+ }+ known.set(source.getText(expression), true);+ if (expression.type === 'UnaryExpression' && expression.operator === '!') {+ known.set(source.getText(expression.argument), false);+ }+ /** `disabled={open === false}`: the compared value holds while enabled. */+ if (expression.type === 'BinaryExpression' && /^[!=]==?$/.test(expression.operator)) {+ const literal = [expression.left, expression.right].find(+ (side) => side.type === 'Literal' && typeof side.value === 'boolean',+ );+ const other = literal === expression.left ? expression.right : expression.left;+ if (literal) {+ known.set(source.getText(other), literal.value !== expression.operator.startsWith('!'));+ }+ }+ }+ return known;+}++/** @type {import('eslint').Rule.RuleModule} */+const disabledRecipe = {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'Require a shared disabled recipe wherever a class list dims a disabled control, so a `disabledStyle: fill` theme can paint it',+ },+ schema: [+ {+ type: 'object',+ properties: {+ /** Components whose rendered class list already composes a recipe on the element+ * that takes `className`, so a caller's dim there is painted over by the recipe. */+ primitives: { type: 'array', items: { type: 'string' }, uniqueItems: true },+ /** The modules those components are imported from; the same name from anywhere else+ * is another component. */+ sources: { type: 'array', items: { type: 'string' }, uniqueItems: true },+ },+ additionalProperties: false,+ },+ ],+ messages: {+ missing:+ '`{{dim}}` dims a disabled control without a disabled recipe that restores it on every path: compose disabledFillClasses or disabledInkClasses for the control itself, disabledWithinFillClasses for a wrapper around it or peerDisabledInkClasses for a label that follows it (@librechat/client) into the same class list, so a theme with `disabledStyle: fill` paints it instead of fading it.',+ },+ },+ create(context) {+ const source = context.sourceCode;+ const primitives = new Set(context.options[0]?.primitives ?? []);+ const sources = new Set(context.options[0]?.sources ?? ['@librechat/client']);+ const restored = recipeReader(context);++ /** A configured primitive imported from a configured module or, inside the component+ * library, from its own file; when the file declares no such name at all, the name alone. */+ const isPrimitive = (element) => {+ const resolved = element ? elementImport(element, source) : undefined;+ if (!resolved || !primitives.has(resolved.component)) return false;+ if (!resolved.declared) return true;+ if (sources.has(resolved.from)) return true;+ if (typeof resolved.from !== 'string' || !resolved.from.startsWith('.')) return false;+ const file = resolve(dirname(context.filename), resolved.from);+ return PRIMITIVES_DIR.exec(file)?.[1] === resolved.component;+ };++ /** `node` is the string as an expression; a template's text reports on its own part. */+ const check = (node, value, reported = node) => {+ if (typeof value !== 'string' || !value.includes('opacity-')) return;+ const list = classList(node);+ const element = classNameElement(list);+ const known = disabledExpressions(element, source);+ const control = element?.attributes.some(+ (attribute) =>+ attribute.type === 'JSXAttribute' && DISABLED_ATTRIBUTES.has(attribute.name.name),+ );+ /** A bare fade sits on the control when the element carries the disabled state, on a+ * wrapper around it when the element does not, and on an unknown element outside JSX. */+ let bareTopology = 'any';+ if (element) bareTopology = control ? 'self' : 'within';+ const picked = known.get(STATIC) === true || chosenByDisabled(node, source, known);+ const chosen = picked ? bareDims(value, bareTopology) : [];+ const dims = [...variantDims(value), ...chosen];+ if (dims.length === 0) return;+ /** A primitive's own recipe restores a plain fade of the control itself; an important one,+ * or one on another element, still needs the caller's recipe. */+ const coveredByPrimitive = (need) =>+ !need.important && (need.topology === 'self' || need.topology === 'any');+ if (isPrimitive(element) && dims.every(coveredByPrimitive)) return;+ const missing = dims.find((need) => !restored(node, list, { ...need, known }));+ if (!missing) return;+ context.report({ node: reported, messageId: 'missing', data: { dim: missing.dim } });+ };+ /** A constant class string the element names (`const faded = 'opacity-50'` then+ * `<button disabled className={faded} />`): read where it is used, since the literal on its+ * own carries no disabled context. */+ const checkReference = (attribute) => {+ if (attribute.name.name !== 'className') return;+ const expression =+ attribute.value?.type === 'JSXExpressionContainer' ? attribute.value.expression : undefined;+ if (expression?.type !== 'Identifier') return;+ const element = attribute.parent;+ if (disabledExpressions(element, source).get(STATIC) !== true) return;+ const variable = findVariable(source.getScope(expression), expression.name);+ const declarator = variable?.defs[0]?.node;+ if (declarator?.type !== 'VariableDeclarator' || declarator.parent.kind !== 'const') return;+ const init = declarator.init;+ let value = init?.type === 'Literal' ? init.value : undefined;+ if (init?.type === 'TemplateLiteral' && init.expressions.length === 0) {+ value = init.quasis[0].value.cooked;+ }+ if (typeof value !== 'string') return;+ const primitive = isPrimitive(element);+ const dim = bareDims(value, 'self').find((need) => {+ if (primitive && !need.important && need.topology === 'self') return false;+ return !RECIPE_VARIANTS.some(([pattern, recipe]) => {+ const match = pattern.exec(value);+ return (+ match && recipe === need.topology && (!need.important || Boolean(match[1] || match[2]))+ );+ });+ });+ if (!dim) return;+ context.report({ node: expression, messageId: 'missing', data: { dim: dim.dim } });+ };++ return {+ JSXAttribute: checkReference,+ Literal(node) {+ check(node, node.value);+ },+ TemplateElement(node) {+ check(node.parent, node.value.cooked, node);+ },+ };+ },+};++export default {+ meta: { name: 'design' },+ rules: { 'disabled-recipe': disabledRecipe },+};diff --git a/scripts/eslint/design.test.mjs b/scripts/eslint/design.test.mjsnew file mode 100644index 0000000000..4824f57538--- /dev/null+++ b/scripts/eslint/design.test.mjs@@ -0,0 +1,406 @@+import { describe, it } from 'node:test';+import tsParser from '@typescript-eslint/parser';+import { RuleTester } from 'eslint';+import design from './design.mjs';++RuleTester.describe = describe;+RuleTester.it = it;++const tester = new RuleTester({+ languageOptions: {+ parser: tsParser,+ parserOptions: { ecmaFeatures: { jsx: true } },+ },+});++const missing = (dim) => ({ messageId: 'missing', data: { dim } });++tester.run('design/disabled-recipe', design.rules['disabled-recipe'], {+ valid: [+ "cn('px-2 disabled:opacity-50', disabledFillClasses)",+ "<span className={cn(disabled && 'opacity-50', disabledWithinFillClasses)} />",+ "<button disabled={disabled} className={cn(disabled && 'opacity-50', disabledFillClasses)} />",+ "cn('disabled:opacity-60!', 'theme-disabled:opacity-100!')",+ "<button disabled className={cn('opacity-50', disabledFillClasses)} />",+ "cn(disabled && { 'opacity-50': true }, disabledFillClasses)",+ "cn(disabled && 'opacity-50', disabled && disabledFillClasses)",+ "cn(disabled ? 'opacity-50' : '', disabled ? disabledFillClasses : '')",+ "cn('data-[disabled]:opacity-50 aria-[disabled=true]:opacity-40', disabledFillClasses)",+ "cva('', { variants: { size: { sm: 'px-2' } }, compoundVariants: [{ disabled: [true, false], class: 'opacity-50' }] })",+ "import { cn } from '~/utils'; cn('disabled:opacity-50', disabledFillClasses)",+ "const faded = 'opacity-50'; <button className={faded} />",+ "cn('supports-[selector(:disabled)]:opacity-50 data-[state=disabled-preview]:opacity-50')",+ "cn('disabled:opacity-[100%] disabled:opacity-[1]')",+ "import { clsx } from 'clsx'; clsx('disabled:opacity-50', disabledFillClasses)",+ "<input disabled={busy} className={cn('disabled:opacity-50', busy && disabledFillClasses)} />",+ "const faded = 'opacity-50 theme-disabled:opacity-100'; <button disabled className={faded} />",+ {+ code: 'import Button from \'./Button\'; <Button className="disabled:opacity-80" />',+ filename: '/repo/packages/client/src/components/Dialog.tsx',+ options: [{ primitives: ['Button'] }],+ },+ "<button disabled={disabled === false} className={cn(disabled && 'opacity-50')} />",+ "<button disabled={disabled} className={cn('disabled:opacity-50', disabled && disabledFillClasses)} />",+ "cn('disabled:opacity-50', 'px-2 ' + disabledFillClasses, clsx(disabledInkClasses))",+ "cn('data-[state=not-disabled]:opacity-50 aria-[state=non-disabled]:opacity-40')",+ "cn({ disabled: { true: 'opacity-50' } })",+ "const metadata = { disabled: true, class: 'opacity-50' };",+ "cn(disabled ? '' : (active ? 'opacity-50' : ''))",+ "cn('disabled:opacity-50 theme-disabled:opacity-100!')",+ "cn('disabled:opacity-100!')",+ "cva(disabledFillClasses, { variants: { disabled: { true: 'opacity-50', false: '' } } })",+ "cva('', { variants: { disabled: { true: '', false: 'opacity-50' } } })",+ "import * as client from '@librechat/client'; cn('disabled:opacity-50', client.disabledFillClasses)",+ {+ code: "import { disabledInkClasses } from '../utils'; cn('disabled:opacity-50', disabledInkClasses)",+ filename: '/repo/packages/client/src/components/Menu.tsx',+ },+ "cva(cn('rounded disabled:opacity-50', disabledFillClasses), { variants: {} })",+ "cn('has-[:disabled]:opacity-50', disabledWithinFillClasses)",+ "const label = cn('peer-disabled:opacity-70', peerDisabledInkClasses);",+ '<input className={cn(`disabled:opacity-50 ${size}`, disabledFillClasses)} />',+ "cn('disabled:opacity-50 theme-disabled:bg-surface-disabled theme-disabled:opacity-100')",+ "cn('disabled:opacity-100')",+ "cn(!disabled && active && 'opacity-50')",+ "cn(disabled || active ? 'opacity-50' : '')",+ {+ code: '<Button className="disabled:opacity-80" />',+ options: [{ primitives: ['Button'] }],+ },+ {+ code: 'import { Button as Action } from \'@librechat/client\'; <Action className="disabled:opacity-80" />',+ options: [{ primitives: ['Button'] }],+ },+ {+ code: "import * as ui from '~/components/ui'; <ui.Checkbox className={cn('disabled:opacity-70', size)} />",+ options: [{ primitives: ['Checkbox'], sources: ['@librechat/client', '~/components/ui'] }],+ },+ {+ code: 'import { Button } from \'./Button\'; <Button className="disabled:opacity-80" />',+ filename: '/repo/packages/client/src/components/Dialog.tsx',+ options: [{ primitives: ['Button'] }],+ },+ "import { disabledFillClasses as fill } from '@librechat/client'; cn('disabled:opacity-50', fill)",+ "cn('peer-disabled:opacity-70', peerDisabledInkClasses)",+ "cn('[&:has(:disabled)]:opacity-50', disabledWithinFillClasses)",+ "cn(disabled ? 'opacity-50' : '', disabledInkClasses)",+ "cn({ 'disabled:opacity-50': cond, [disabledFillClasses]: cond })",+ "<input disabled={busy} className={cn(busy ? 'opacity-50' : '', disabledFillClasses)} />",+ "cn('hover:opacity-80 focus:opacity-100 opacity-60')",+ "cn(open ? 'opacity-100' : 'opacity-0')",+ "cn({ 'opacity-50': isLoading })",+ "const recipe = 'theme-disabled:text-text-disabled theme-disabled:opacity-100';",+ "cn(disabled ? 'opacity-50' : '', disabledFillClasses)",+ "const label = 'disabled';",+ "cn('not-disabled:opacity-100 opacity-0')",+ "cn('data-[disabled]:opacity-50', utils.disabledInkClasses)",+ "cva('rounded', { variants: { size: { sm: cn('disabled:opacity-50', disabledFillClasses) } } })",+ "cn({ 'disabled:opacity-50': true, [disabledFillClasses]: true })",+ "cn(disabled ? '' : 'opacity-50')",+ "cn(!disabled && 'opacity-50')",+ "cn({ 'opacity-50': disabled === false })",+ "cn('data-[disabled=false]:opacity-50 aria-[disabled=false]:opacity-60')",+ "cn('[&:not(:disabled)]:opacity-50')",+ "cn(isNotDisabled && 'opacity-50')",+ "cn({ 'opacity-50': props.nonDisabled })",+ ],+ invalid: [+ {+ code: '<button className="px-2 disabled:opacity-50" />',+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn('rounded aria-disabled:opacity-40')",+ errors: [missing('aria-disabled:opacity-40')],+ },+ {+ code: "cn('data-[disabled]:pointer-events-none data-[disabled]:opacity-50')",+ errors: [missing('data-[disabled]:opacity-50')],+ },+ {+ code: "cn('group-disabled:opacity-60')",+ errors: [missing('group-disabled:opacity-60')],+ },+ {+ code: "cn('has-[:disabled]:opacity-50')",+ errors: [missing('has-[:disabled]:opacity-50')],+ },+ {+ code: "cn('sm:disabled:!opacity-30')",+ errors: [missing('sm:disabled:!opacity-30')],+ },+ {+ code: "cn('px-2', disabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-surface-hover')",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn(isDisabled && 'opacity-40')",+ errors: [missing('opacity-40')],+ },+ {+ code: "cn({ 'opacity-50': props.disabled })",+ errors: [missing('opacity-50')],+ },+ {+ code: 'const base = `rounded disabled:opacity-50 ${tone}`;',+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "const styles = { base: 'disabled:opacity-50' }; cn(styles.base, disabledFillClasses);",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn(isEnabled ? 'hover:bg-surface-hover' : '', !disabled ? '' : 'opacity-50')",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn('disabled:opacity-50 theme-disabled:bg-surface-disabled')",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn(disabled ? cn('opacity-50') : '')",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn(disabled && active && 'opacity-40')",+ errors: [missing('opacity-40')],+ },+ {+ code: '<Badge className="disabled:opacity-80" />',+ options: [{ primitives: ['Button'] }],+ errors: [missing('disabled:opacity-80')],+ },+ {+ code: "cn('aria-[disabled=true]:opacity-50')",+ errors: [missing('aria-[disabled=true]:opacity-50')],+ },+ {+ code: "cn('data-[state=disabled]:opacity-50')",+ errors: [missing('data-[state=disabled]:opacity-50')],+ },+ {+ code: "cn('[&:disabled]:opacity-40')",+ errors: [missing('[&:disabled]:opacity-40')],+ },+ {+ code: "const props = { className: 'disabled:opacity-50', disabledFillClasses: false };",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "const props = { className: 'disabled:opacity-50', footer: cn(disabledFillClasses) };",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn(disabled ? 'opacity-50' : disabledFillClasses)",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn('disabled:opacity-50', !disabled && disabledFillClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cva('rounded disabled:opacity-50', { variants: { tone: { muted: disabledInkClasses, loud: 'px-2' } } })",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cva('rounded', { variants: { size: { sm: 'disabled:opacity-50' } }, compoundVariants: [{ class: disabledFillClasses }] })",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cva('', { variants: { disabled: { true: 'opacity-50', false: '' } } })",+ errors: [missing('opacity-50')],+ },+ {+ code: "cva('', { variants: { size: { sm: 'px-2' } }, compoundVariants: [{ disabled: true, class: 'opacity-40' }] })",+ errors: [missing('opacity-40')],+ },+ {+ code: "cn(disabled && 'opacity-50', active && disabledFillClasses)",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn(disabled && 'sm:opacity-50')",+ errors: [missing('sm:opacity-50')],+ },+ {+ code: "cn(disabled ? 'opacity-50' : '', disabled ? '' : disabledFillClasses)",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn(disabled && (active ? 'opacity-50' : ''))",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn(disabled && (active && 'opacity-40'))",+ errors: [missing('opacity-40')],+ },+ {+ code: "cva('disabled:opacity-50', { variants: { tone: { muted: disabledFillClasses } }, defaultVariants: { tone: null } })",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cva('disabled:opacity-50', { variants: { tone: { muted: disabledFillClasses } }, defaultVariants: { tone: 'loud' } })",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn('disabled:opacity-50', disabledFillClasses === other)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn('disabled:opacity-50', drop(disabledFillClasses))",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cva('rounded disabled:opacity-50', { variants: { tone: { muted: disabledInkClasses, loud: cn('px-2', disabledFillClasses) } }, defaultVariants: { tone: 'muted' } })",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "<span className={cn(disabled && 'opacity-50', disabledFillClasses)} />",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn('[tr[data-disabled=true]_&]:opacity-50', disabledFillClasses)",+ errors: [missing('[tr[data-disabled=true]_&]:opacity-50')],+ },+ {+ code: "<div className={first('disabled:opacity-50', disabledFillClasses)} />",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn('disabled:opacity-60!', disabledFillClasses)",+ errors: [missing('disabled:opacity-60!')],+ },+ {+ code: '<button disabled className="opacity-50" />',+ errors: [missing('opacity-50')],+ },+ {+ code: '<button aria-disabled="true" className="px-2 opacity-40" />',+ errors: [missing('opacity-40')],+ },+ {+ code: "cn('disabled:group-disabled:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:group-disabled:opacity-50')],+ },+ {+ code: '<Button disabled className="disabled:opacity-60!" />',+ options: [{ primitives: ['Button'] }],+ errors: [missing('disabled:opacity-60!')],+ },+ {+ code: "cn('data-[state=disabled]:opacity-50', disabledFillClasses)",+ errors: [missing('data-[state=disabled]:opacity-50')],+ },+ {+ code: "cn(!disabled || !active ? '' : 'opacity-50')",+ errors: [missing('opacity-50')],+ },+ {+ code: "cva('', { variants: { size: { sm: 'px-2' } }, compoundVariants: [{ disabled: [true], class: 'opacity-50' }] })",+ errors: [missing('opacity-50')],+ },+ {+ code: "const faded = 'opacity-50'; <button disabled className={faded} />",+ errors: [missing('opacity-50')],+ },+ {+ code: "const cn = (first) => first; cn('disabled:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn(disabled && 'opacity-50 md:opacity-60!', disabledFillClasses)",+ errors: [missing('md:opacity-60!')],+ },+ {+ code: "import { cn } from './first'; cn('disabled:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "import * as helpers from './first'; helpers.cn('disabled:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: '<div data-disabled className="opacity-50" />',+ errors: [missing('opacity-50')],+ },+ {+ code: "cn('peer-data-[state=disabled]:opacity-50', peerDisabledInkClasses)",+ errors: [missing('peer-data-[state=disabled]:opacity-50')],+ },+ {+ code: "cn('has-[input[data-disabled]]:opacity-50', disabledWithinFillClasses)",+ errors: [missing('has-[input[data-disabled]]:opacity-50')],+ },+ {+ code: "cn('disabled:[&_svg]:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:[&_svg]:opacity-50')],+ },+ {+ code: "<input disabled={busy} className={cn('disabled:opacity-50', isDisabled && disabledFillClasses)} />",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn('disabled:opacity-60!')",+ errors: [missing('disabled:opacity-60!')],+ },+ {+ code: "cn(disabled && { 'opacity-50': true })",+ errors: [missing('opacity-50')],+ },+ {+ code: "cn('peer-disabled:opacity-70', disabledFillClasses)",+ errors: [missing('peer-disabled:opacity-70')],+ },+ {+ code: "cn('has-[:disabled]:opacity-50', disabledInkClasses)",+ errors: [missing('has-[:disabled]:opacity-50')],+ },+ {+ code: "cn('disabled:opacity-50', peerDisabledInkClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "cn('group-disabled:opacity-60', disabledFillClasses)",+ errors: [missing('group-disabled:opacity-60')],+ },+ {+ code: "cva('rounded disabled:opacity-50', { variants: { tone: { muted: disabledInkClasses, loud: disabledFillClasses } } })",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "import { disabledFillClasses } from './styles'; cn('disabled:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "import { disabledFillClasses } from '~/utils'; cn('disabled:opacity-50', disabledFillClasses)",+ filename: '/repo/client/src/components/Row.tsx',+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "const utils = { disabledInkClasses: 'px-2' }; cn('disabled:opacity-50', utils.disabledInkClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: "const disabledFillClasses = 'px-2'; cn('disabled:opacity-50', disabledFillClasses)",+ errors: [missing('disabled:opacity-50')],+ },+ {+ code: 'import { Button } from \'./local\'; <Button className="disabled:opacity-80" />',+ options: [{ primitives: ['Button'] }],+ errors: [missing('disabled:opacity-80')],+ },+ {+ code: 'import * as Ariakit from \'@ariakit/react\'; <Ariakit.Button className="disabled:opacity-80" />',+ options: [{ primitives: ['Button'] }],+ errors: [missing('disabled:opacity-80')],+ },+ {+ code: "<button disabled={importMutation.isLoading} className={cn('px-2', importMutation.isLoading && 'cursor-wait opacity-50')} />",+ errors: [missing('opacity-50')],+ },+ {+ code: "<button disabled={!canOpenDetails} className={cn(canOpenDetails ? 'hover:bg-surface-hover' : 'opacity-50')} />",+ errors: [missing('opacity-50')],+ },+ ],+});diff --git a/scripts/static-checks.mts b/scripts/static-checks.mtsindex 8b94544e32..35c0bc2e11 100644--- a/scripts/static-checks.mts+++ b/scripts/static-checks.mts@@ -78,7 +78,7 @@ const FILTERS = {'.github/workflows/static-checks.yml','!**.md',],- eslint_config: ['eslint.config.mjs', '.github/workflows/static-checks.yml'],+ eslint_config: ['eslint.config.mjs', 'scripts/eslint/**', '.github/workflows/static-checks.yml'],// The design-rule backlog is data the lint reads, so a diff that only edits it// reaches no lintable file and would otherwise be checked by nothing.// Deleting or renaming a recorded file has to reach this group too: the entry@@ -98,6 +98,8 @@ const FILTERS = {'packages/client/tsdown.config.mjs','packages/client/tsconfig.json','eslint.config.mjs',+ /** The local design rules: a change to what one reports changes every count it owns. */+ 'scripts/eslint/**',/** The plugin is a dependency: a bump changes what the rules classify, and a* removal takes the rules with it, neither of which touches a source file. */'package.json',@@ -219,6 +221,10 @@ const DESIGN_TEST_SOURCE = /\.(?:test|spec)\.(?:ts|tsx|js|jsx)$/;* what every recorded count stands for, without touching a source file. */const DESIGN_INPUTS = ['eslint.config.mjs', 'package.json', 'package-lock.json'];+/** The local design rules (`design/*`): a change to one moves what it reports in files the+ * diff never touches, as a config change does. */+const DESIGN_RULES_ROOT = 'scripts/eslint/';+/** Where the rules read component metadata from: the published library and the* app-local path `componentImports` marks as a component source. A change in* either moves what the caller rules report in files the diff never touches. */@@ -282,6 +288,13 @@ const reportedPath = (filePath: string): string =>/** `@shadcn/lint`'s rule map, the authority on which recorded rule names exist. */type SuppressionsPlugin = { plugin: { rules: Record<string, unknown> } };+/** The local `design` plugin's rule map, recorded beside `@shadcn/lint`'s. */+type DesignPlugin = { default: { rules: Record<string, unknown> } };++/** The design rules are `@shadcn/lint`'s and the local `design` plugin's+ * (`scripts/eslint/design.mjs`); both are recorded in the same backlog. */+const isDesignRule = (ruleId: string | null | undefined): boolean =>+ ruleId?.startsWith('shadcn/') === true || ruleId?.startsWith('design/') === true;const I18N_FILE = 'client/src/locales/en/translation.json';const I18N_SOURCE_DIRS = [@@ -782,7 +795,19 @@ function validateEslintConfig(): CheckOutcome {const eslint = resolveBin('eslint');if (!eslint) return missingBin('eslint');const result = runCommand(eslint, ['--config', 'eslint.config.mjs', ...CONFIG_SMOKE_FILES]);- return { ok: result.status === 0, output: result.output };+ const ruleTests = runCommand(+ {+ command: process.execPath,+ args: ['--test', resolve(ROOT, 'scripts/eslint/design.test.mjs')],+ },+ [],+ );+ return {+ ok: result.status === 0 && ruleTests.status === 0,+ output: [result.output, ruleTests.status === 0 ? '' : ruleTests.output]+ .filter(Boolean)+ .join('\n'),+ };}async function validatePackageJson(): Promise<CheckOutcome> {@@ -843,9 +868,13 @@ async function validateSuppressions(context: CheckContext): Promise<CheckOutcomelet known: Set<string>;try {const { plugin } = (await import('@shadcn/lint')) as SuppressionsPlugin;- known = new Set(Object.keys(plugin.rules).map((rule) => `shadcn/${rule}`));+ const { default: design } = (await import('./eslint/design.mjs')) as DesignPlugin;+ known = new Set([+ ...Object.keys(plugin.rules).map((rule) => `shadcn/${rule}`),+ ...Object.keys(design.rules).map((rule) => `design/${rule}`),+ ]);} catch (error) {- return { ok: false, output: `@shadcn/lint did not load: ${(error as Error).message}` };+ return { ok: false, output: `the design rules did not load: ${(error as Error).message}` };}/** Every lint below classifies against the primitives' `cva` variants, which@@ -1020,7 +1049,7 @@ async function inlineDirectives(context: CheckContext): Promise<string[]> {: true,);for (const message of [...file.messages, ...suppressed]) {- if (!message.ruleId?.startsWith('shadcn/')) continue;+ if (!isDesignRule(message.ruleId)) continue;const key = `${relative}\u0000${message.ruleId}`;counts.set(key, (counts.get(key) ?? 0) + 1);}@@ -1093,7 +1122,7 @@ async function directiveComments(files: string[]): Promise<string[]> {`${file}: a blanket \`${body}\` covers the design rules too, now or the first time this file violates one; record what is owed in ${SUPPRESSIONS_FILE} instead`,);}- for (const rule of named.filter((rule) => rule.startsWith('shadcn/'))) {+ for (const rule of named.filter(isDesignRule)) {problems.push(`${file}: ${rule} is disabled by an inline comment; record it in ${SUPPRESSIONS_FILE} instead, where the count is reviewable and \`npm run lint:design:prune\` can retire it`,);@@ -1115,7 +1144,7 @@ async function directiveComments(files: string[]): Promise<string[]> {/(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([A-Za-z@][\w@\-./]*))\s*:/g,)) {const rule = decodeRuleKey(doubled ?? singled ?? bare ?? '');- if (!rule.startsWith('shadcn/')) continue;+ if (!isDesignRule(rule)) continue;problems.push(`${file}: ${rule} is configured by an inline comment; the record is where a design rule is answered, not the file that owes it`,);@@ -1168,7 +1197,9 @@ async function suppressionProblems(target: string, known: Set<string>): Promise<}for (const [rule, entry] of Object.entries(rules)) {if (!known.has(rule)) {- problems.push(`${where}: ${rule} is not a rule @shadcn/lint defines`);+ problems.push(+ `${where}: ${rule} is not a rule @shadcn/lint defines, nor one the design plugin does`,+ );}const count = typeof entry === 'object' && entry !== null ? entry.count : undefined;if (typeof count !== 'number' || !Number.isInteger(count) || count < 1) {@@ -1232,6 +1263,7 @@ async function unusedCapacity(target: string, context: CheckContext): Promise<st(file) =>file === GATE_SOURCE ||DESIGN_INPUTS.includes(file) ||+ file.startsWith(DESIGN_RULES_ROOT) ||DESIGN_METADATA_FILES.includes(file) ||(DESIGN_SOURCE.test(file) &&!DESIGN_TEST_SOURCE.test(file) &&@@ -1324,7 +1356,7 @@ async function unusedCapacity(target: string, context: CheckContext): Promise<stconst relative = reportedPath(file.filePath);const actual = new Map<string, number>();for (const message of [...file.messages, ...(file.suppressedMessages ?? [])]) {- if (message.ruleId?.startsWith('shadcn/')) {+ if (isDesignRule(message.ruleId)) {actual.set(message.ruleId, (actual.get(message.ruleId) ?? 0) + 1);}}@@ -1445,7 +1477,7 @@ async function introducedWithinAllowance(const signatures = (reports: LintReport[]): string[] =>reports.flatMap((file) => [...file.messages, ...(file.suppressedMessages ?? [])])- .filter((message) => message.ruleId?.startsWith('shadcn/'))+ .filter((message) => isDesignRule(message.ruleId)).map((message) => `${message.ruleId}: ${message.message ?? ''}`);/** The record as the base held it: how much an entry grew between there and