diff --git a/.changeset/route-modules-eslint.md b/.changeset/route-modules-eslint.md index 14f07932fc..cc98d7db17 100644 --- a/.changeset/route-modules-eslint.md +++ b/.changeset/route-modules-eslint.md @@ -2,4 +2,4 @@ '@tanstack/eslint-plugin-router': minor --- -Experimental: Add the `route-module-imports` rule, enabled in the recommended configs: files of a route module must import routing and Start APIs from the module's generated route scope. The rule only applies to packages that declare `tanstack.router.module`. +Experimental: Add the `route-module-imports` rule, enabled in the recommended configs: files of a route module must import routing and Start APIs from the module's generated route scope, and must not import, in values or in types, from a module the package lists in `uses`. The rule only applies to packages that declare `tanstack.router.module`. diff --git a/docs/router/eslint/route-module-imports.md b/docs/router/eslint/route-module-imports.md index 88f96642ac..3e0e301f02 100644 --- a/docs/router/eslint/route-module-imports.md +++ b/docs/router/eslint/route-module-imports.md @@ -10,11 +10,13 @@ Files of a [route module](../routing/route-modules.md) must import routing and S The rule reports value imports of these APIs from the framework packages: -- Route constructors and routing APIs: `createFileRoute`, `Link`, `createLink`, `linkOptions`, `Navigate`, `useNavigate`, `redirect`, `MatchRoute`, `useMatchRoute`, `useRouter`, `getRouteApi`, `useMatch`, `useMatches`, `useParentMatches`, `useChildMatches`, `useLoaderData`, `useLoaderDeps`, `useSearch`, `useParams`, `useRouteContext`, `useLocation` and `useRouterState`. +- Route constructors and routing APIs: `createFileRoute`, `Link`, `createLink`, `linkOptions`, `Navigate`, `useNavigate`, `redirect`, `MatchRoute`, `useMatchRoute`, `useRouter`, `getRouteApi`, `useMatch`, `useMatches`, `useParentMatches`, `useChildMatches`, `useLoaderData`, `useLoaderDeps`, `useSearch`, `useParams`, `useRouteContext`, `useLocation`, `useRouterState`, `useLinkProps`, `useBlocker` and `notFound`. - Root route constructors (`createRootRoute`, `createRootRouteWithContext`): a module root is created with `createModuleRoot`. -- Start APIs of Start route modules: `createServerFn` and `createStartModule`. +- Start APIs of Start route modules: `createServerFn`, `createMiddleware` and `createStartModule`. -The rule only applies to files whose nearest `package.json` declares `tanstack.router.module`. It ignores generated files and type-only imports. +The rule also reports every import from a module the package lists in `uses` (`"@acme/products"` or any of its entry points), including type-only imports, re-exports and dynamic imports. A route module links into the modules it uses through the generated namespaces; its declaration build compiles against a stand-in for each used contract, so a type imported from a used module would be emitted with the stand-in's types. Move code that several modules share into a package both depend on. + +The rule only applies to files whose nearest `package.json` declares `tanstack.router.module`. It ignores generated files, and type-only imports of the framework packages. ## Rule Details @@ -29,6 +31,17 @@ export const Route = createFileRoute('@acme/products:/$productId')({ }) ``` +```tsx title="packages/products/src/routes/index.tsx" +/* eslint "@tanstack/router/route-module-imports": "error" */ +// package.json: "tanstack": { "router": { "module": { "uses": ["@acme/account"] } } } +import type { Order } from '@acme/account/api' +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@acme/products:/')({ + loader: (): Promise> => fetchOrders(), +}) +``` + Examples of **correct** code for this rule: ```tsx title="packages/products/src/routes/$productId.tsx" @@ -41,6 +54,21 @@ export const Route = createFileRoute('@acme/products:/$productId')({ }) ``` +```tsx title="packages/products/src/routes/index.tsx" +/* eslint "@tanstack/router/route-module-imports": "error" */ +import type { Order } from '@acme/orders-types' +import { account, createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@acme/products:/')({ + loader: (): Promise> => fetchOrders(), + component: () => ( + + My last order + + ), +}) +``` + ## Attributes - [x] ✅ Recommended diff --git a/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json b/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json index 346800ea14..1f7a8ccc84 100644 --- a/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json +++ b/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json @@ -3,7 +3,15 @@ "private": true, "tanstack": { "router": { - "module": true + "module": { + "uses": [ + "@fixture/used", + { + "module": "@fixture/other", + "as": "other" + } + ] + } } } } diff --git a/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts b/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts index 8cf1df7ca9..f9cb1b20f1 100644 --- a/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts +++ b/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts @@ -31,8 +31,8 @@ ruleTester.run(name, rule, { name: 'APIs the scope does not provide', filename: moduleFile, code: ` - import { Outlet, notFound, createSerializationAdapter } from '@tanstack/react-router' - import { createMiddleware, useServerFn } from '@tanstack/react-start' + import { Outlet, createSerializationAdapter } from '@tanstack/react-router' + import { useServerFn } from '@tanstack/react-start' `, }, { @@ -51,26 +51,80 @@ ruleTester.run(name, rule, { import { createServerFn } from '@tanstack/react-start' `, }, - { - name: 'generated files', - filename: generatedFile, + ...[ + generatedFile, + path.join(fixtures, 'route-module/src/routeScope.gen.namespace0.ts'), + path.join(fixtures, 'route-module/src/routeScope.gen.products.ts'), + path.join(fixtures, 'route-module/src/routeScope.gen/products.ts'), + ].map((filename) => ({ + name: `generated file ${path.relative(fixtures, filename)}`, + filename, code: ` import { createServerFn as createStartServerFn } from '@tanstack/react-start' + import type { Router } from '@fixture/used/route-types' + `, + })), + { + name: 'imports from modules that are not used', + filename: moduleFile, + code: ` + import { schema } from '@fixture/shared' + import type { Order } from '@fixture/used-not' + import { used } from '../routeScope.gen' + `, + }, + { + name: 'used modules imported by an application', + filename: appFile, + code: ` + import type { Router } from '@fixture/used/route-types' `, }, ], invalid: [ + { + name: 'imports from used modules', + filename: moduleFile, + code: ` + import type { Order } from '@fixture/used' + import { formatPrice } from '@fixture/used/api' + import { type Settings } from '@fixture/other' + `, + errors: [ + { messageId: 'noUsedModuleImport', data: { module: '@fixture/used' } }, + { messageId: 'noUsedModuleImport', data: { module: '@fixture/used' } }, + { messageId: 'noUsedModuleImport', data: { module: '@fixture/other' } }, + ], + }, + { + name: 're-exports of and dynamic imports from used modules', + filename: moduleFile, + code: ` + export * from '@fixture/used/schemas' + export type { Order } from '@fixture/used' + const load = () => import('@fixture/other/api') + `, + errors: [ + { messageId: 'noUsedModuleImport', data: { module: '@fixture/used' } }, + { messageId: 'noUsedModuleImport', data: { module: '@fixture/used' } }, + { messageId: 'noUsedModuleImport', data: { module: '@fixture/other' } }, + ], + }, { name: 'routing APIs from the framework package', filename: moduleFile, code: ` import { createFileRoute, Link as RouterLink, Outlet } from '@tanstack/react-router' import { useNavigate } from '@tanstack/vue-router' + import { useLinkProps, useBlocker, notFound } from '@tanstack/solid-router' `, errors: [ { messageId: 'useRouteScope', data: { name: 'createFileRoute' } }, { messageId: 'useRouteScope', data: { name: 'Link' } }, { messageId: 'useRouteScope', data: { name: 'useNavigate' } }, + { messageId: 'useRouteScope', data: { name: 'useLinkProps' } }, + { messageId: 'useRouteScope', data: { name: 'useBlocker' } }, + { messageId: 'useRouteScope', data: { name: 'notFound' } }, ], }, { @@ -90,10 +144,11 @@ ruleTester.run(name, rule, { name: 'Start APIs from the framework package', filename: moduleFile, code: ` - import { createServerFn, createStartModule } from '@tanstack/react-start' + import { createServerFn, createMiddleware, createStartModule } from '@tanstack/react-start' `, errors: [ { messageId: 'useRouteScope', data: { name: 'createServerFn' } }, + { messageId: 'useRouteScope', data: { name: 'createMiddleware' } }, { messageId: 'useRouteScope', data: { name: 'createStartModule' } }, ], }, diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts index 3381caad47..fe33b59074 100644 --- a/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts +++ b/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts @@ -1,6 +1,7 @@ /** * Routing APIs a route module's generated scope (`routeScope.gen.ts`) exports - * typed against the module's own routes. + * typed against the module's own routes. Keep in step with `scopeApis` in + * `packages/router-generator/src/route-module/emit.ts`. */ export const scopedRouterApis = [ 'createFileRoute', @@ -25,6 +26,9 @@ export const scopedRouterApis = [ 'useRouteContext', 'useLocation', 'useRouterState', + 'useLinkProps', + 'useBlocker', + 'notFound', ] as const /** Root route constructors; a route module's root is `createModuleRoot`. */ @@ -34,4 +38,8 @@ export const rootRouteConstructors = [ ] as const /** Start APIs a Start route module's scope exports. */ -export const scopedStartApis = ['createServerFn', 'createStartModule'] as const +export const scopedStartApis = [ + 'createServerFn', + 'createMiddleware', + 'createStartModule', +] as const diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts index ab20f09c87..2ee1110ba1 100644 --- a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts +++ b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts @@ -7,7 +7,12 @@ import { scopedRouterApis, scopedStartApis, } from './constants' -import { isGeneratedFile, isInRouteModule } from './route-module-imports.utils' +import { + getRouteModule, + getUsedModule, + isGeneratedFile, +} from './route-module-imports.utils' +import type { TSESTree } from '@typescript-eslint/utils' import type { ExtraRuleDocs } from '../../types' const createRule = ESLintUtils.RuleCreator(getDocsUrl) @@ -26,7 +31,7 @@ export const rule = createRule({ type: 'problem', docs: { description: - 'Ensure route modules import routing and Start APIs from their generated route scope', + 'Ensure route modules import routing and Start APIs from their generated route scope and do not import from the modules they use', recommended: 'error', }, messages: { @@ -34,6 +39,8 @@ export const rule = createRule({ '"{{name}}" in a route module must be imported from its generated route scope (routeScope.gen), which types it against the module\'s own routes.', useModuleRoot: 'The root route of a route module is created with "createModuleRoot" from its generated route scope (routeScope.gen), not with "{{name}}".', + noUsedModuleImport: + 'A route module must not import from a module it uses ("{{module}}"), in values or in types: its declaration build compiles against a stand-in for that module\'s contract. Link into its routes through the generated namespace in routeScope.gen, and move shared code into a package both modules depend on.', }, schema: [], }, @@ -41,12 +48,43 @@ export const rule = createRule({ create(context) { const filename = context.filename - if (isGeneratedFile(filename) || !isInRouteModule(path.dirname(filename))) { + const module = isGeneratedFile(filename) + ? null + : getRouteModule(path.dirname(filename)) + if (!module) { return {} } + const reportUsedModule = (node: TSESTree.Node, source: string) => { + const used = getUsedModule(module, source) + if (used !== undefined) { + context.report({ + node, + messageId: 'noUsedModuleImport', + data: { module: used }, + }) + } + } + return { + ExportNamedDeclaration(node) { + if (node.source) { + reportUsedModule(node, node.source.value) + } + }, + ExportAllDeclaration(node) { + reportUsedModule(node, node.source.value) + }, + ImportExpression(node) { + if ( + node.source.type === AST_NODE_TYPES.Literal && + typeof node.source.value === 'string' + ) { + reportUsedModule(node, node.source.value) + } + }, ImportDeclaration(node) { + reportUsedModule(node, node.source.value) if (node.importKind === 'type') { return } diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts index c72e6df0a8..ded3af2ac5 100644 --- a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts +++ b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts @@ -1,27 +1,26 @@ import fs from 'node:fs' import path from 'node:path' -const routeModuleByDirectory = new Map() - -function readsAsRouteModule(packageJsonPath: string): boolean { - try { - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) - return packageJson?.tanstack?.router?.module !== undefined - } catch { - return false - } +/** What the rule needs to know about the route module a file belongs to. */ +export interface RouteModuleInfo { + /** Ids of the modules the package lists in `tanstack.router.module.uses`. */ + uses: ReadonlyArray } -/** - * Whether `directory` belongs to a route module: its nearest `package.json` - * declares `tanstack.router.module`. Results are cached per directory. - */ -export function isInRouteModule(directory: string): boolean { +/** The nearest `package.json` of a directory; `null` when there is none. */ +const packageJsonByDirectory = new Map() +/** Parsed route-module declarations, revalidated by modification time. */ +const routeModuleByPackageJson = new Map< + string, + { mtimeMs: number; info: RouteModuleInfo | null } +>() + +function findPackageJson(directory: string): string | null { const visited: Array = [] let current = path.resolve(directory) - let result = false + let result: string | null = null for (;;) { - const cached = routeModuleByDirectory.get(current) + const cached = packageJsonByDirectory.get(current) if (cached !== undefined) { result = cached break @@ -29,7 +28,7 @@ export function isInRouteModule(directory: string): boolean { visited.push(current) const packageJsonPath = path.join(current, 'package.json') if (fs.existsSync(packageJsonPath)) { - result = readsAsRouteModule(packageJsonPath) + result = packageJsonPath break } const parent = path.dirname(current) @@ -39,12 +38,77 @@ export function isInRouteModule(directory: string): boolean { current = parent } for (const dir of visited) { - routeModuleByDirectory.set(dir, result) + packageJsonByDirectory.set(dir, result) } return result } -/** Generated files (`routeScope.gen.ts` imports the framework itself). */ +function readRouteModule(packageJsonPath: string): RouteModuleInfo | null { + try { + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) + const declaration = packageJson?.tanstack?.router?.module + if (declaration === undefined) { + return null + } + const uses: Array = Array.isArray(declaration?.uses) + ? declaration.uses + : [] + return { + uses: uses.flatMap((entry) => { + const module = + typeof entry === 'string' + ? entry + : (entry as { module?: unknown } | null)?.module + return typeof module === 'string' ? [module] : [] + }), + } + } catch { + return null + } +} + +/** + * The route module `directory` belongs to: its nearest `package.json` + * declares `tanstack.router.module`. `null` for other packages. The + * directory walk is cached for the process; the declaration is re-read when + * the package.json changes, so a long-lived ESLint server sees edits. + */ +export function getRouteModule(directory: string): RouteModuleInfo | null { + const packageJsonPath = findPackageJson(directory) + if (packageJsonPath === null) { + return null + } + let mtimeMs: number + try { + mtimeMs = fs.statSync(packageJsonPath).mtimeMs + } catch { + return null + } + const cached = routeModuleByPackageJson.get(packageJsonPath) + if (cached && cached.mtimeMs === mtimeMs) { + return cached.info + } + const info = readRouteModule(packageJsonPath) + routeModuleByPackageJson.set(packageJsonPath, { mtimeMs, info }) + return info +} + +/** The used module an import specifier points into, if any. */ +export function getUsedModule( + module: RouteModuleInfo, + source: string, +): string | undefined { + return module.uses.find( + (used) => source === used || source.startsWith(`${used}/`), + ) +} + +/** + * Generated files: `routeScope.gen.ts`, the namespace files of every + * `routeScopeNamespaceFiles` layout (`routeScope.gen.namespace0.ts`, + * `routeScope.gen.products.ts`, `routeScope.gen/products.ts`) and the route + * trees. They import the framework and used contracts themselves. + */ export function isGeneratedFile(filename: string): boolean { - return /\.gen\.[cm]?[jt]sx?$/.test(filename) + return /\.gen(?:\.|[\\/])/.test(filename) }