Skip to content

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

🧱 feat: Catch Module-Load Use of Mocked Packages in @librechat/chat (#17539)

Marco Beretta06065af0f31b
diff --git a/packages/chat/src/__tests__/load.spec.ts b/packages/chat/src/__tests__/load.spec.ts
new file mode 100644
index 0000000000..e814e01d3f
--- /dev/null
+++ b/packages/chat/src/__tests__/load.spec.ts
@@ -0,0 +1,61 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+/** Packages no app spec replaces: React and Jotai belong at module scope (`memo`, `atom`). */
+const LOAD_SAFE = /^(react|react-dom|jotai)(\/|$)/;
+const SOURCE = /\.(ts|tsx)$/;
+const SPEC = /(\.(spec|test)\.|\/__(tests|mocks|fixtures)__\/)/;
+const SPECIFIER = /(?:from\s+|import\s*\(\s*|require\(\s*|import\s+)['"]([^'"]+)['"]/g;
+
+const root = path.resolve(__dirname, '..');
+
+const sources = (dir: string): string[] =>
+ fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const file = path.join(dir, entry.name);
+ if (entry.isDirectory()) return sources(file);
+ return SOURCE.test(file) && !SPEC.test(file) ? [file] : [];
+ });
+
+/** Every other package the package's sources load, by the exact specifier they use. */
+const externals = (): string[] => {
+ const found = new Set<string>();
+ for (const file of sources(root)) {
+ for (const [, specifier] of fs.readFileSync(file, 'utf8').matchAll(SPECIFIER)) {
+ if (!specifier.startsWith('.') && !LOAD_SAFE.test(specifier)) found.add(specifier);
+ }
+ }
+ return [...found].sort();
+};
+
+/**
+ * This spec mocks workspace packages on purpose, an exception to the repository's real-logic
+ * testing rule: its subject is the mock itself. App specs replace `@librechat/client` and
+ * `librechat-data-provider` wholesale, and the failure it guards against (an entry that throws
+ * on import under those mocks) only exists under them. Every other spec here uses the real
+ * packages.
+ *
+ * A package the way an app spec's factory mock leaves it: a module whose every export is missing.
+ * Handing an export on is harmless; calling one, constructing one or reading a member of one is
+ * what throws, and that is the failure this spec catches.
+ */
+const missingExports = (): object =>
+ new Proxy({}, { get: (_target, key) => (key === '__esModule' ? true : undefined) });
+
+describe('loading the package while its dependencies are mocked', () => {
+ const mocked = externals();
+
+ it('finds the packages the sources load', () => {
+ expect(mocked).toEqual(
+ expect.arrayContaining(['@librechat/client', 'librechat-data-provider']),
+ );
+ });
+
+ it.each(['index', 'react', 'components'])('loads the %s entry without touching them', (entry) => {
+ jest.isolateModules(() => {
+ for (const specifier of mocked) {
+ jest.doMock(specifier, missingExports, { virtual: true });
+ }
+ expect(() => jest.requireActual(path.join(root, entry))).not.toThrow();
+ });
+ });
+});
diff --git a/scripts/eslint/chat.mjs b/scripts/eslint/chat.mjs
index a50bc7ccc3..06dc40dcad 100644
--- a/scripts/eslint/chat.mjs
+++ b/scripts/eslint/chat.mjs
@@ -14,12 +14,38 @@ import path from 'node:path';
* `@librechat/client`, or any subpath of them) and none of the `/react` or `/components` entries.
* A core `import()` or `require()` whose specifier cannot be read statically is reported too,
* since the rule could not tell what it loads.
+ * - Outside specs: no call, `new`, tagged template or member read through another package's import
+ * at module scope. App specs mock whole packages (`@librechat/client`, `librechat-data-provider`),
+ * so a top-level `cn(...)` or a map keyed by `FileSources.local` throws on import. This is fast
+ * feedback for the plain case; `src/__tests__/load.spec.ts` loads every entry with those packages
+ * mocked and catches the rest (aliases, `require`, invoked functions). React and Jotai, which no
+ * spec replaces, are exempt through the `loadSafe` option.
*/
const EXTENSION = /\.(?:[cm]?[jt]sx?)$/;
const UI_PACKAGES = new Set(['react', 'react-dom', 'jotai', '@librechat/client']);
const UI_SCOPES = ['@tanstack/'];
const ENTRIES = new Set(['react', 'components']);
+const LOAD_SAFE = ['react', 'react-dom', 'jotai', 'jotai/utils'];
+const FUNCTIONS = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
+
+/** `cn`, `Client.cn` and `Client['cn']` all start at the identifier they reach through. */
+const rootIdentifier = (node) => {
+ let current = node;
+ while (current.type === 'MemberExpression') current = current.object;
+ return current.type === 'Identifier' ? current : undefined;
+};
+
+/** Whether `node` runs when its module loads: no function and no instance field defers it. */
+const runsOnLoad = (node) => {
+ for (let child = node, parent = node.parent; parent; child = parent, parent = parent.parent) {
+ if (FUNCTIONS.has(parent.type)) return false;
+ if (parent.type === 'PropertyDefinition' && !parent.static && child === parent.value) {
+ return false;
+ }
+ }
+ return true;
+};
const packageName = (specifier) => {
const parts = specifier.split('/');
@@ -55,6 +81,7 @@ const boundary = {
properties: {
sourceRoot: { type: 'string' },
packageName: { type: 'string' },
+ loadSafe: { type: 'array', items: { type: 'string' } },
},
additionalProperties: false,
},
@@ -67,6 +94,7 @@ const boundary = {
ui: 'The @librechat/chat core has no UI dependency; {{specifier}} belongs in the /react entry.',
entry: 'The core cannot load {{specifier}}; the /{{entry}} entry builds on the core.',
opaque: 'The @librechat/chat core loads only specifiers the boundary can read.',
+ load: 'Use {{name}} from {{source}} inside a function, not while the module loads: app specs mock {{source}}, and this throws on import.',
},
},
create(context) {
@@ -77,6 +105,26 @@ const boundary = {
const relativeFile = path.relative(root, filename);
if (relativeFile.startsWith('..') || path.isAbsolute(relativeFile)) return {};
const segments = relativeFile.split(path.sep);
+ /** Specs and their support files (`__fixtures__`, `__mocks__`) never load in an app spec. */
+ const isSpec =
+ segments.some((segment) => /^__(tests|fixtures|mocks)__$/.test(segment)) ||
+ /\.(spec|test)\./.test(relativeFile);
+ const loadSafe = new Set(options.loadSafe ?? LOAD_SAFE);
+ /** Import specifiers that bind a name to another package, mapped to that package. */
+ const externalBindings = new Map();
+ const usesExternalOnLoad = (node, target) => {
+ if (isSpec) return;
+ const identifier = rootIdentifier(target);
+ if (!identifier) return;
+ let variable;
+ for (let scope = context.sourceCode.getScope(node); scope && !variable; scope = scope.upper) {
+ variable = scope.set.get(identifier.name);
+ }
+ const source = variable && externalBindings.get(variable.defs[0]?.node);
+ if (!source || !runsOnLoad(node)) return;
+ context.report({ node, messageId: 'load', data: { name: identifier.name, source } });
+ };
+
const isCore =
(segments.length === 1 && /^index\.[cm]?[jt]sx?$/.test(segments[0])) ||
(segments[0] === 'core' &&
@@ -127,13 +175,37 @@ const boundary = {
};
return {
+ Program(program) {
+ for (const statement of program.body) {
+ if (statement.type !== 'ImportDeclaration' || statement.importKind === 'type') continue;
+ const source = statement.source.value;
+ /** Node built-ins (`node:path`) are never replaced by a spec. */
+ const local = source.startsWith('.') || source.startsWith('~');
+ if (local || source.startsWith('node:') || loadSafe.has(source)) continue;
+ statement.specifiers
+ .filter((specifier) => specifier.importKind !== 'type')
+ .forEach((specifier) => externalBindings.set(specifier, source));
+ }
+ },
ImportDeclaration: (node) => check(node, node.source),
+ NewExpression: (node) => usesExternalOnLoad(node, node.callee),
+ TaggedTemplateExpression: (node) => usesExternalOnLoad(node, node.tag),
+ /** The outermost read only: `A.b.c` is one report, and a call reports its own callee. */
+ MemberExpression(node) {
+ const { parent } = node;
+ if (parent.type === 'MemberExpression' && parent.object === node) return;
+ if (parent.type === 'CallExpression' && parent.callee === node) return;
+ if (parent.type === 'NewExpression' && parent.callee === node) return;
+ if (parent.type === 'TaggedTemplateExpression' && parent.tag === node) return;
+ usesExternalOnLoad(node, node);
+ },
ExportNamedDeclaration: (node) => node.source && check(node, node.source),
ExportAllDeclaration: (node) => check(node, node.source),
ImportExpression: (node) => check(node, node.source),
TSImportType: (node) => check(node, node.argument),
TSExternalModuleReference: (node) => check(node, node.expression),
CallExpression(node) {
+ usesExternalOnLoad(node, node.callee);
if (node.callee.type !== 'Identifier' || node.callee.name !== 'require') return;
check(node, node.arguments[0]);
},
diff --git a/scripts/eslint/chat.test.mjs b/scripts/eslint/chat.test.mjs
index 0768a60b69..09a142660f 100644
--- a/scripts/eslint/chat.test.mjs
+++ b/scripts/eslint/chat.test.mjs
@@ -112,6 +112,39 @@ tester.run('chat/boundary', chat.rules.boundary, {
options,
},
{ code: "import x from '~/store';", filename: path.join(root, 'client/src/x.ts'), options },
+ ...[
+ "import { cn } from '@librechat/client'; export const C = () => cn('a');",
+ "import { cn } from '@librechat/client'; export function f() { return cn('a'); }",
+ "import { cn } from '@librechat/client'; export const C = memo(function C() { return cn('a'); });",
+ "import { cn } from '@librechat/client'; class A { value = cn('a'); }",
+ "import type { TShowToast } from '@librechat/client'; export const t = TShowToast;",
+ "import { cn } from './utils'; export const classes = cn('a');",
+ "import { cn } from '@librechat/client'; export const f = (cn: (v: string) => string) => cn('a');",
+ "import { memo, createContext } from 'react'; export const C = memo(() => null); export const Ctx = createContext(null);",
+ "import { atom } from 'jotai'; import { atomFamily } from 'jotai/utils'; export const a = atom(0); export const f = atomFamily(() => a);",
+ "import { FileSources } from 'librechat-data-provider'; export const icon = (s: string) => ({ [FileSources.local]: 'x' })[s];",
+ "import { Search } from 'lucide-react'; export const icons = { search: Search, list: [Search] };",
+ ].map((code) => ({ code, filename: at('components/Probe.tsx'), options })),
+ {
+ code: "import { cn } from '@librechat/client'; const classes = cn('a');",
+ filename: at('components/__tests__/Probe.spec.tsx'),
+ options,
+ },
+ {
+ code: "import path from 'node:path'; export const dir = path.join('a', 'b');",
+ filename: at('__fixtures__/i18n.ts'),
+ options,
+ },
+ {
+ code: "import { cn } from '@librechat/client'; export const classes = cn('a');",
+ filename: at('components/__mocks__/Probe.tsx'),
+ options,
+ },
+ {
+ code: "import path from 'node:path'; export const dir = path.join('a', 'b');",
+ filename: at('react/probe.ts'),
+ options,
+ },
],
invalid: [
...cases('core/streaming/probe.ts', entrySpellings, 'entry'),
@@ -137,6 +170,38 @@ tester.run('chat/boundary', chat.rules.boundary, {
],
errors: [{ messageId: 'ui' }],
},
+ ...[
+ ["import { cn } from '@librechat/client'; export const classes = cn('a');", 'cn'],
+ ["import { cn as join } from '@librechat/client'; export const classes = join('a');", 'join'],
+ [
+ "import * as Client from '@librechat/client'; export const c = Client['cn']('a');",
+ 'Client',
+ ],
+ ["import { cva } from '@librechat/client'; export const variants = cva('a', {});", 'cva'],
+ ["import { Store } from '@librechat/client'; export const store = new Store();", 'Store'],
+ ["import { css } from '@librechat/client'; export const rule = css`color: red;`;", 'css'],
+ ["import { cn } from '@librechat/client'; class A { static value = cn('a'); }", 'cn'],
+ ["export const classes = cn('a'); import { cn } from '@librechat/client';", 'cn'],
+ [
+ "import { FileSources } from 'librechat-data-provider'; export const icons = { [FileSources.local]: 'x' };",
+ 'FileSources',
+ 'librechat-data-provider',
+ ],
+ ["import { v4 } from 'uuid'; export const id = v4();", 'v4', 'uuid'],
+ [
+ "import { atom } from 'jotai'; export const a = atom(0);",
+ 'atom',
+ 'jotai',
+ { loadSafe: [] },
+ ],
+ ].flatMap(([code, name, source = '@librechat/client', extra = {}]) =>
+ ['components/Probe.tsx', 'react/probe.ts'].map((file) => ({
+ code,
+ filename: at(file),
+ options: [{ ...options[0], ...extra }],
+ errors: [{ messageId: 'load', data: { name, source } }],
+ })),
+ ),
{
code: 'export const load = (name: string) => import(name);',
filename: at('core/probe.ts'),