mirror of
https://github.com/colbymchenry/codegraph.git
synced 2026-10-21 08:47:04 +08:00
fix(react-router): read the table a function returns when a variable hands it to the router (#2668)
Medusa's admin dashboard builds its router in a class's `render()`:
`const routes = getRouteMap({ settingsRoutes, coreRoutes })`, then
`createBrowserRouter(routes, { basename })`. `getRouteMap`, imported from
its own module, returns the literal table. The route-table pass
(`tableRoutes` in frameworks/react.ts) read a variable only when it held
the literal itself, so none of the 221 routes existed, and the dashboard's
`navigate()` calls and `<Link>`s led nowhere.
- `declaredTable` now reports a value initialized with a call
(`getRouteMap({ … })`, `await loadRoutes()`) as the function to follow,
and `tableNamed` / `exportedTable` follow it to the table it returns,
local or imported. `export const routes = buildRoutes()` and
`export default buildRoutes()` are read the same way.
- Of several declarations of a name in a file, the one in scope at the use
is read (`visibleAt`). Scope comes from the graph's functions; a
function-local declaration has no node of its own, so the declarations
are read from the text. Another function's `const routes = getMenu()` is
that function's own and is never followed. An exported name is a
top-level one.
- What the function's parameters spread in (Medusa's `...coreRoutes`,
filled from plugins) stays unread: no declaration in scope names it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -157,6 +157,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
- A React Router route whose `lazy` loader picks its page from the module it loads now links to that page: `lazy: async () => { const { TestTab } = await import('./tabs'); return { Component: TestTab }; }`, `const { default: Component } = await import('./pages/Login')`, `import('./reports').then((m) => ({ Component: m.ReportList }))`, `({ Component: (await import('./reports')).ReportPage })`, React Router 7's `lazy: { Component: async () => (await import('./show')).Show }`, and a page the loader shows inside a guard, like `element: <AgeGate><FireworksPage /></AgeGate>`. Before, such a route linked to the module's default export, else its `Component` export, which is a different page or none at all, as with luci-go's tabs loaded from a folder that forwards them. A loader written as a method, `async lazy() { … }`, is now read too, so its route is no longer missing, and a loader that hands React Router only a `loader` no longer makes the module's default export the route's page or the layout of the routes inside it. Re-index React projects after upgrading.
|
||||
- A React Router route, or a page loaded with `lazy(() => import(…))`, now links to its page when the folder it loads passes the page on through an import of its own, like `import { UserLayout } from './UserLayout'; export { UserLayout }` or `import Login from './Login'; export default Login`. Before, the folder's `index.ts` was searched for a page declared in it, which it doesn't have, so the route linked nothing. A default export that wraps the page in a call, like `export default withAuth(Page)`, still links neither the wrapper nor a guess. Re-index React projects after upgrading.
|
||||
- `codegraph sync` and the file watcher now link a lazily loaded React Router route to its page when the page appears, or gains the export the route reads, in a folder below the one the route loads, like `src/pages/Home/index.tsx` behind `import('@/pages')`. Before, such a route kept linking nothing until the folder's own `index.ts` changed or the project was re-indexed, although a fresh index linked it.
|
||||
- React Router routes are now indexed when the router gets its table from a function through a variable, as in Medusa's admin dashboard, which writes `const routes = getRouteMap({ … })` and then `createBrowserRouter(routes)`. The same goes for `export const routes = buildRoutes()` or `export default buildRoutes()` imported into `useRoutes(routes)`, and for `const routes = await loadRoutes()`. Before, such a variable was read only when it held the table itself, so these apps had no routes: their pages had no route leading to them, and their `navigate('/orders/…')` calls and `<Link>` links led nowhere. Routes the function is handed by its caller, like the plugin routes Medusa spreads in, are still not read, and when two functions in one file each keep a `routes` variable, the router reads its own and never the other's, which may be a menu. Re-index React projects after upgrading.
|
||||
- In JavaScript and TypeScript, an import written `import { default as AppRoot } from './routes/app/root'`, as in bulletproof-react's router, now counts as the module's default import, the same as `import AppRoot from './routes/app/root'`. Before, it was read as an import of an export named `default`, which no module has, so a call, a route or a JSX attribute that used `AppRoot` was matched by its name alone: it could link to another file's `AppRoot`, or to nothing when the default export has a name of its own. Svelte, Vue and Astro script blocks are read the same way.
|
||||
- In React, a component's JSX no longer links it to a class or component that only shares a name with one of its type arguments or with a variable of its own. A type in angle brackets, like `Document` in `<PaginatedList<Document> items={…} />`, `User` in `useState<User>()` or `Entry` in a generic `<Entry extends BaseEntity>(…) =>` component, is no longer read as a tag. A tag naming a variable or parameter the component sets itself, like `<Content>` after `const Content = isDropdown ? DropdownMenu.SubContent : ContextMenu.SubContent` or `<Widget>` in `widgets.map((Widget) => <Widget />)`, now links to nothing, unless the component declares a component of that name inside itself. Before, these linked to an unrelated class or component elsewhere in the repository: outline's document lists showed up among the callers of its `Document` model class, and its menus among the callers of the command bar's `Content`, so `codegraph_explore`, callers and impact followed renders that never happen. Re-index React projects after upgrading.
|
||||
- In React, a tag a component only mentions in a comment or a string no longer links it to that component: a JSDoc example, markup commented out like `{/* <Progress /> */}`, or an error message like react-router's "You cannot render a <Router> inside another <Router>" or shadcn's "useCarousel must be used within a <Carousel />". Nothing in a TypeScript `.ts` file, which can't hold JSX, is read as a tag either, like the XML in outline's OpenSearch template. Before, these counted as renders, so react-router's hooks showed up among the callers of `Router`, `Routes` and `Route`, and `codegraph_explore`, callers and impact followed renders that never happen. A tag after an apostrophe, a URL or a backtick in a component's text, like `<p>Don't have an account? <Link to="/signup">`, still links as before. Re-index React projects after upgrading.
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
/**
|
||||
* A route table handed to React Router through a local that holds a call's
|
||||
* result: Medusa's admin dashboard writes
|
||||
*
|
||||
* const routes = getRouteMap({ settingsRoutes: this.settingsRoutes, coreRoutes: this.coreRoutes })
|
||||
* const router = createBrowserRouter(routes, { basename })
|
||||
*
|
||||
* inside a class's `render()`, and `getRouteMap`, imported from its own
|
||||
* module, returns the literal table. The table is what the function returns.
|
||||
* Before, the local was read only for a literal, so none of Medusa's routes
|
||||
* existed. The tables spread in from the function's parameters (`...coreRoutes`)
|
||||
* are the caller's to fill (Medusa's come from plugins), so they stay unread.
|
||||
*
|
||||
* Which `routes` a use reads is the one in scope there: another function's
|
||||
* `const routes = getMenu()` is that function's own, and a menu is no table.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { CodeGraph } from '../src';
|
||||
|
||||
function writeFiles(root: string, files: Record<string, string>): void {
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, rel), content);
|
||||
}
|
||||
}
|
||||
|
||||
async function indexProject(files: Record<string, string>): Promise<{ root: string; cg: CodeGraph }> {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-rr-call-tables-'));
|
||||
writeFiles(root, files);
|
||||
return { root, cg: await CodeGraph.init(root, { index: true }) };
|
||||
}
|
||||
|
||||
/** `path -> Component` for what each route renders, `path ~> Layout` for each layout around it, under `dir`. */
|
||||
function routeBindings(cg: CodeGraph, dir: string): string[] {
|
||||
return cg.getNodesByKind('route').filter((r) => r.filePath.startsWith(dir)).flatMap((r) => cg.getOutgoingEdges(r.id)
|
||||
.filter((e) => e.kind === 'references')
|
||||
.map((e) => `${r.name} ${(e.metadata as Record<string, unknown> | undefined)?.layout ? '~>' : '->'} ${cg.getNode(e.target)?.name}`))
|
||||
.sort();
|
||||
}
|
||||
|
||||
const routeNames = (cg: CodeGraph, dir: string): string[] =>
|
||||
cg.getNodesByKind('route').filter((r) => r.filePath.startsWith(dir)).map((r) => r.name).sort();
|
||||
|
||||
/** A component that renders the routes inside it. */
|
||||
const layout = (name: string): string =>
|
||||
`import { Outlet } from 'react-router-dom';\n\nexport const ${name} = () => {\n return <Outlet />;\n};\n`;
|
||||
|
||||
/** A route module the way Medusa writes one: a barrel that hands React Router its page as `Component`. */
|
||||
const routeModule = (dir: string, name: string, file: string): Record<string, string> => ({
|
||||
[`${dir}/index.ts`]: `export { ${name} as Component } from './${file}';\n`,
|
||||
[`${dir}/${file}.tsx`]: `export const ${name} = () => {\n return <div>${name}</div>;\n};\n`,
|
||||
});
|
||||
|
||||
const MEDUSA_APP = `import { createBrowserRouter, RouteObject, RouterProvider } from 'react-router-dom';
|
||||
import { getRouteMap } from './routes/get-route.map';
|
||||
|
||||
export class DashboardApp {
|
||||
private coreRoutes: RouteObject[];
|
||||
private settingsRoutes: RouteObject[];
|
||||
|
||||
constructor({ plugins }: { plugins: { routes: RouteObject[] }[] }) {
|
||||
this.coreRoutes = plugins.flatMap((p) => p.routes);
|
||||
this.settingsRoutes = [];
|
||||
}
|
||||
|
||||
render() {
|
||||
const routes = getRouteMap({
|
||||
settingsRoutes: this.settingsRoutes,
|
||||
coreRoutes: this.coreRoutes,
|
||||
});
|
||||
|
||||
const router = createBrowserRouter(routes, {
|
||||
basename: '/app',
|
||||
});
|
||||
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const routeMap = (extra = ''): string => `import { RouteObject } from 'react-router-dom';
|
||||
import { ProtectedRoute } from '../../components/protected-route';
|
||||
import { MainLayout } from '../../components/main-layout';
|
||||
import { SettingsLayout } from '../../components/settings-layout';
|
||||
import { PublicLayout } from '../../components/public-layout';
|
||||
|
||||
export function getRouteMap({
|
||||
settingsRoutes,
|
||||
coreRoutes,
|
||||
}: {
|
||||
settingsRoutes: RouteObject[]
|
||||
coreRoutes: RouteObject[]
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
element: <ProtectedRoute />,
|
||||
children: [
|
||||
{
|
||||
element: <MainLayout />,
|
||||
children: [
|
||||
{
|
||||
path: '/',
|
||||
lazy: () => import('../../routes/home'),
|
||||
},
|
||||
{
|
||||
path: '/products',
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
lazy: () => import('../../routes/products/product-list'),
|
||||
children: [
|
||||
{
|
||||
path: 'create',
|
||||
lazy: () =>
|
||||
import('../../routes/products/product-create'),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},${extra}
|
||||
...coreRoutes,
|
||||
],
|
||||
},
|
||||
{
|
||||
element: <SettingsLayout />,
|
||||
children: [
|
||||
{
|
||||
path: '/settings',
|
||||
lazy: () => import('../../routes/settings'),
|
||||
},
|
||||
...settingsRoutes.flatMap((r) => r?.children || []),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
element: <PublicLayout />,
|
||||
children: [
|
||||
{
|
||||
path: '/login',
|
||||
lazy: () => import('../../routes/login'),
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
`;
|
||||
|
||||
const ORDERS = `
|
||||
{
|
||||
path: '/orders',
|
||||
lazy: () => import('../../routes/orders'),
|
||||
},`;
|
||||
|
||||
const MEDUSA: Record<string, string> = {
|
||||
'admin/package.json': JSON.stringify({ name: 'dashboard', dependencies: { react: '^18', 'react-router-dom': '^6' } }),
|
||||
'admin/src/dashboard-app/dashboard-app.tsx': MEDUSA_APP,
|
||||
'admin/src/dashboard-app/routes/get-route.map.tsx': routeMap(),
|
||||
'admin/src/components/protected-route.tsx': layout('ProtectedRoute'),
|
||||
'admin/src/components/main-layout.tsx': layout('MainLayout'),
|
||||
'admin/src/components/settings-layout.tsx': layout('SettingsLayout'),
|
||||
'admin/src/components/public-layout.tsx': layout('PublicLayout'),
|
||||
...routeModule('admin/src/routes/home', 'Home', 'home'),
|
||||
...routeModule('admin/src/routes/products/product-list', 'ProductList', 'product-list'),
|
||||
...routeModule('admin/src/routes/products/product-create', 'ProductCreate', 'product-create'),
|
||||
...routeModule('admin/src/routes/settings', 'Settings', 'settings'),
|
||||
...routeModule('admin/src/routes/login', 'Login', 'login'),
|
||||
...routeModule('admin/src/routes/orders', 'Orders', 'orders'),
|
||||
};
|
||||
|
||||
const MEDUSA_BINDINGS = [
|
||||
'/ -> Home',
|
||||
'/ ~> MainLayout',
|
||||
'/ ~> ProtectedRoute',
|
||||
'/login -> Login',
|
||||
'/login ~> PublicLayout',
|
||||
// The `''` route under `/products` is the page there, and the layout its
|
||||
// `create` child renders inside.
|
||||
'/products -> ProductList',
|
||||
'/products ~> MainLayout',
|
||||
'/products ~> ProtectedRoute',
|
||||
'/products/create -> ProductCreate',
|
||||
'/products/create ~> MainLayout',
|
||||
'/products/create ~> ProductList',
|
||||
'/products/create ~> ProtectedRoute',
|
||||
'/settings -> Settings',
|
||||
'/settings ~> ProtectedRoute',
|
||||
'/settings ~> SettingsLayout',
|
||||
];
|
||||
|
||||
/**
|
||||
* Apps whose routers are handed a call's result in other ways, and the
|
||||
* shapes around them that are no route table.
|
||||
*/
|
||||
const SHAPES: Record<string, string> = {
|
||||
'package.json': JSON.stringify({ name: 'shapes', dependencies: { react: '^18', 'react-router-dom': '^6' } }),
|
||||
'src/icons.jsx': `export function HelpIcon() {\n return <svg />;\n}\nexport function BillingIcon() {\n return <svg />;\n}\n`,
|
||||
'src/pages.jsx': ['Home', 'Account', 'Dashboard', 'Landing', 'TodoList', 'Reports']
|
||||
.map((p) => `export function ${p}() {\n return <div>${p}</div>;\n}\n`).join(''),
|
||||
// A menu: a `{ path, element }` list that nothing hands the router.
|
||||
'src/menu.jsx': `import { BillingIcon, HelpIcon } from './icons';
|
||||
|
||||
export function getMenu() {
|
||||
return [
|
||||
{ path: '/help', element: <HelpIcon /> },
|
||||
{ path: '/billing', element: <BillingIcon /> },
|
||||
];
|
||||
}
|
||||
`,
|
||||
|
||||
// Two functions with a `routes` each: the router is handed App's own.
|
||||
'src/scoped/routes.jsx': `import { Account, Home } from '../pages';
|
||||
|
||||
export const getRoutes = (user) => [
|
||||
{ path: '/', element: <Home /> },
|
||||
{ path: '/account', element: <Account /> },
|
||||
];
|
||||
`,
|
||||
'src/scoped/App.jsx': `import { Link, useRoutes } from 'react-router-dom';
|
||||
import { getMenu } from '../menu';
|
||||
import { getRoutes } from './routes';
|
||||
|
||||
function Sidebar() {
|
||||
const routes = getMenu();
|
||||
return <nav>{routes.map((r) => <Link key={r.path} to={r.path}>{r.path}</Link>)}</nav>;
|
||||
}
|
||||
|
||||
export default function App({ user }) {
|
||||
const routes = getRoutes(user);
|
||||
const element = useRoutes(routes);
|
||||
return <div><Sidebar />{element}</div>;
|
||||
}
|
||||
`,
|
||||
|
||||
// The router is handed the import; another function's local of that name is its own.
|
||||
'src/shadow/routes.jsx': `import { Landing } from '../pages';
|
||||
|
||||
const routes = [{ path: '/landing', element: <Landing /> }];
|
||||
|
||||
export default routes;
|
||||
`,
|
||||
'src/shadow/App.jsx': `import { useRoutes } from 'react-router-dom';
|
||||
import routes from './routes';
|
||||
import { getMenu } from '../menu';
|
||||
|
||||
function Sidebar() {
|
||||
const routes = getMenu();
|
||||
return <ul>{routes.map((r) => <li key={r.path}>{r.path}</li>)}</ul>;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return useRoutes(routes);
|
||||
}
|
||||
`,
|
||||
|
||||
// An exported table that is a call's result, past a function's own local of that name.
|
||||
'src/exported/routes.jsx': `import { Dashboard } from '../pages';
|
||||
import { getMenu } from '../menu';
|
||||
|
||||
export function menuSize() {
|
||||
const routes = getMenu();
|
||||
return routes.length;
|
||||
}
|
||||
|
||||
const makeRoutes = () => [{ path: '/dashboard', element: <Dashboard /> }];
|
||||
|
||||
export const routes = makeRoutes();
|
||||
`,
|
||||
'src/exported/App.jsx': `import { useRoutes } from 'react-router-dom';
|
||||
import { routes } from './routes';
|
||||
|
||||
export default function App() {
|
||||
return useRoutes(routes);
|
||||
}
|
||||
`,
|
||||
|
||||
// A default export that is a call's result.
|
||||
'src/default/build.jsx': `import { Reports } from '../pages';
|
||||
|
||||
export function buildRoutes() {
|
||||
return [{ path: '/reports', element: <Reports /> }];
|
||||
}
|
||||
`,
|
||||
'src/default/routes.js': `import { buildRoutes } from './build';
|
||||
|
||||
export default buildRoutes();
|
||||
`,
|
||||
'src/default/App.jsx': `import { useRoutes } from 'react-router-dom';
|
||||
import routes from './routes';
|
||||
|
||||
export default function App() {
|
||||
return useRoutes(routes);
|
||||
}
|
||||
`,
|
||||
|
||||
// A table an async function returns, awaited before the router gets it.
|
||||
'src/awaited/load.jsx': `import { Account } from '../pages';
|
||||
|
||||
export async function loadRoutes() {
|
||||
return [{ path: '/me', element: <Account /> }];
|
||||
}
|
||||
`,
|
||||
'src/awaited/boot.jsx': `import { createBrowserRouter } from 'react-router-dom';
|
||||
import { loadRoutes } from './load';
|
||||
|
||||
export async function boot() {
|
||||
const routes = await loadRoutes();
|
||||
return createBrowserRouter(routes);
|
||||
}
|
||||
`,
|
||||
|
||||
// A router file that builds its table in a function of its own: its route
|
||||
// objects were read when it was extracted; the table it names is new here.
|
||||
'src/features/todo/routes.jsx': `import { TodoList } from '../../pages';
|
||||
|
||||
export const todoRoutes = [{ path: '/todos', element: <TodoList /> }];
|
||||
`,
|
||||
'src/local/main.jsx': `import { createBrowserRouter } from 'react-router-dom';
|
||||
import { todoRoutes } from '../features/todo/routes';
|
||||
import { Home } from '../pages';
|
||||
|
||||
function buildRoutes() {
|
||||
return [{ path: '/home', element: <Home /> }, ...todoRoutes];
|
||||
}
|
||||
|
||||
const routes = buildRoutes();
|
||||
|
||||
export const router = createBrowserRouter(routes);
|
||||
`,
|
||||
|
||||
// A function that makes its table from data returns no literal to read.
|
||||
'src/computed/App.jsx': `import { useRoutes } from 'react-router-dom';
|
||||
import { pageList } from './pages';
|
||||
|
||||
function buildRoutes(pages) {
|
||||
return pages.map((p) => ({ path: p.path, element: p.element }));
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const routes = buildRoutes(pageList);
|
||||
return useRoutes(routes);
|
||||
}
|
||||
`,
|
||||
'src/computed/pages.jsx': `import { HelpIcon } from '../icons';
|
||||
|
||||
export const pageList = [{ path: '/computed', element: <HelpIcon /> }];
|
||||
`,
|
||||
};
|
||||
|
||||
describe("react-router: a table a function returns, handed over through a local (Medusa's admin dashboard)", () => {
|
||||
let root: string;
|
||||
let cg: CodeGraph;
|
||||
beforeAll(async () => {
|
||||
({ root, cg } = await indexProject(MEDUSA));
|
||||
}, 60_000);
|
||||
afterAll(() => {
|
||||
cg?.close();
|
||||
if (root) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('reads the table getRouteMap returns, each lazy route bound to the page its module hands React Router', () => {
|
||||
expect(routeBindings(cg, 'admin/')).toEqual(MEDUSA_BINDINGS);
|
||||
});
|
||||
|
||||
it('keeps the routes in the file that writes them', () => {
|
||||
const home = cg.getNodesByKind('route').find((r) => r.name === '/')!;
|
||||
expect(home.filePath).toBe('admin/src/dashboard-app/routes/get-route.map.tsx');
|
||||
expect(home.startLine).toBe(22);
|
||||
});
|
||||
|
||||
it('follows an edit to the table, and drops the routes when the router is handed something else', async () => {
|
||||
writeFiles(root, { 'admin/src/dashboard-app/routes/get-route.map.tsx': routeMap(ORDERS) });
|
||||
await cg.sync();
|
||||
expect(routeBindings(cg, 'admin/')).toEqual(
|
||||
[...MEDUSA_BINDINGS, '/orders -> Orders', '/orders ~> MainLayout', '/orders ~> ProtectedRoute'].sort());
|
||||
|
||||
writeFiles(root, { 'admin/src/dashboard-app/dashboard-app.tsx': MEDUSA_APP.replace(/getRouteMap\(\{[\s\S]*?\}\);/, '[];') });
|
||||
await cg.sync();
|
||||
expect(routeNames(cg, 'admin/')).toEqual([]);
|
||||
|
||||
writeFiles(root, { 'admin/src/dashboard-app/dashboard-app.tsx': MEDUSA_APP });
|
||||
await cg.sync();
|
||||
expect(routeNames(cg, 'admin/')).toEqual(['/', '/login', '/orders', '/products', '/products/create', '/settings']);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe('react-router: the other ways a call hands the router its table, and what stays no table', () => {
|
||||
let root: string;
|
||||
let cg: CodeGraph;
|
||||
beforeAll(async () => {
|
||||
({ root, cg } = await indexProject(SHAPES));
|
||||
}, 60_000);
|
||||
afterAll(() => {
|
||||
cg?.close();
|
||||
if (root) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("reads the table of the `routes` in the router's own scope, never another function's menu", () => {
|
||||
expect(routeBindings(cg, 'src/scoped/')).toEqual(['/ -> Home', '/account -> Account']);
|
||||
});
|
||||
|
||||
it('reads the imported table a use names, past a same-named local in another function', () => {
|
||||
expect(routeBindings(cg, 'src/shadow/')).toEqual(['/landing -> Landing']);
|
||||
});
|
||||
|
||||
it('reads an exported table that a call makes, as a named or a default export', () => {
|
||||
expect(routeBindings(cg, 'src/exported/')).toEqual(['/dashboard -> Dashboard']);
|
||||
expect(routeBindings(cg, 'src/default/')).toEqual(['/reports -> Reports']);
|
||||
});
|
||||
|
||||
it('reads the table an awaited call returns', () => {
|
||||
expect(routeBindings(cg, 'src/awaited/')).toEqual(['/me -> Account']);
|
||||
});
|
||||
|
||||
it('reads the tables a router file names inside the table its own function returns', () => {
|
||||
expect(routeBindings(cg, 'src/features/')).toEqual(['/todos -> TodoList']);
|
||||
expect(routeBindings(cg, 'src/local/')).toEqual(['/home -> Home']);
|
||||
});
|
||||
|
||||
it('makes no route of a menu, nor of a table a function computes from data', () => {
|
||||
const all = cg.getNodesByKind('route').map((r) => r.name);
|
||||
for (const p of ['/help', '/billing', '/computed']) expect(all).not.toContain(p);
|
||||
});
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -11,7 +11,7 @@ import { dependsOn } from './package-deps';
|
||||
import { resolveImportPath } from '../import-resolver';
|
||||
import { defaultExportBinding, extractLocalExportAliases } from '../alias-binding';
|
||||
import { stripCommentsForRegex } from '../strip-comments';
|
||||
import { makeLineAt } from '../synth-utils';
|
||||
import { FN_KINDS, makeLineAt } from '../synth-utils';
|
||||
import { isTestPath } from '../../search/query-utils';
|
||||
import { matchBracket, skipString } from './object-literal';
|
||||
|
||||
@@ -1989,13 +1989,18 @@ function scriptLanguage(filePath: string): Language {
|
||||
return /\.tsx$/.test(filePath) ? 'tsx' : /\.[cm]?ts$/.test(filePath) ? 'typescript' : /\.jsx$/.test(filePath) ? 'jsx' : 'javascript';
|
||||
}
|
||||
|
||||
/** The literal a table name stands for in `file`: declared there, or imported. */
|
||||
/**
|
||||
* The literal a table name stands for in `file`: declared there, or
|
||||
* imported. A value that holds a call's result — Medusa's `const routes =
|
||||
* getRouteMap({ … })` — stands for the table the function returns.
|
||||
*/
|
||||
function tableNamed(named: TableName, file: string, context: ResolutionContext, depth = 0): { file: string; at: number } | null {
|
||||
const source = context.readFile(file);
|
||||
if (!source) return null;
|
||||
const safe = stripCommentsForRegex(source, 'typescript');
|
||||
const local = declaredTable(safe, named.name, named.call);
|
||||
if (local !== null) return { file, at: local };
|
||||
const local = declaredTable(safe, named.name, named.call, visibleAt(named.at, safe, file, context));
|
||||
if (typeof local === 'number') return { file, at: local };
|
||||
if (local) return depth > 3 ? null : tableNamed(local, file, context, depth + 1);
|
||||
const language = scriptLanguage(file);
|
||||
const mapping = context.getImportMappings(file, language).find((m) => m.localName === named.name);
|
||||
if (!mapping || mapping.isNamespace || depth > 3) return null;
|
||||
@@ -2014,8 +2019,10 @@ function exportedTable(file: string, exported: string, call: boolean, context: R
|
||||
const m = /\bexport\s+default\s+/.exec(safe);
|
||||
if (m) {
|
||||
const after = m.index + m[0].length;
|
||||
const inline = call ? returnedTable(safe, after) : safe[after] === '[' || safe[after] === '{' ? after : null;
|
||||
if (inline !== null) return { file, at: inline };
|
||||
const inline = call ? returnedTable(safe, after) : heldTable(safe, after);
|
||||
if (typeof inline === 'number') return { file, at: inline };
|
||||
// `export default buildRoutes()`
|
||||
if (inline) return depth > 3 ? null : tableNamed(inline, file, context, depth + 1);
|
||||
local = /^([A-Za-z_$][\w$]*)\s*(?:;|\n|$)/.exec(safe.slice(after))?.[1] ?? '';
|
||||
} else local = /\bexport\s*\{[^}]*?\b([A-Za-z_$][\w$]*)\s+as\s+default\b/.exec(safe)?.[1] ?? '';
|
||||
} else {
|
||||
@@ -2023,8 +2030,10 @@ function exportedTable(file: string, exported: string, call: boolean, context: R
|
||||
const alias = new RegExp(`\\bexport\\s*\\{[^}]*?\\b([A-Za-z_$][\\w$]*)\\s+as\\s+${exported.replace(/\$/g, '\\$')}\\b`).exec(safe);
|
||||
if (alias) local = alias[1]!;
|
||||
}
|
||||
const at = local ? declaredTable(safe, local, call) : null;
|
||||
if (at !== null) return { file, at };
|
||||
// What a module exports is declared at its top level.
|
||||
const at = local ? declaredTable(safe, local, call, visibleAt(undefined, safe, file, context)) : null;
|
||||
if (typeof at === 'number') return { file, at };
|
||||
if (at) return depth > 3 ? null : tableNamed(at, file, context, depth + 1);
|
||||
if (depth > 3) return null;
|
||||
// `export { routes } from './routes'`, `export { default as routes } from './routes'`, `export * from './routes'`.
|
||||
const language = scriptLanguage(file);
|
||||
@@ -2038,20 +2047,81 @@ function exportedTable(file: string, exported: string, call: boolean, context: R
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Where `name`'s table literal opens, for `const name = [ … ]` (or a function returning one when `call`). */
|
||||
function declaredTable(safe: string, name: string, call: boolean): number | null {
|
||||
/**
|
||||
* Where `name`'s table literal opens, for `const name = [ … ]` (or a function
|
||||
* returning one when `call`) — or, for `const name = getRouteMap({ … })`, the
|
||||
* function whose returned table the value holds. Of several declarations of
|
||||
* the name, the one `visible` picks.
|
||||
*/
|
||||
function declaredTable(
|
||||
safe: string,
|
||||
name: string,
|
||||
call: boolean,
|
||||
visible: (keywords: number[]) => number | undefined
|
||||
): number | TableName | null {
|
||||
const id = name.replace(/\$/g, '\\$');
|
||||
const decl = new RegExp(`(?:^|[^\\w$.])(?:const|let|var)\\s+${id}\\s*(?::[^=;]*)?=\\s*`).exec(safe);
|
||||
const decls = [...safe.matchAll(new RegExp(`(?:^|[^\\w$.])((?:const|let|var)\\s+${id}\\s*(?::[^=;]*)?=\\s*)`, 'g'))];
|
||||
const chosen = decls.length > 0 ? visible(decls.map((d) => d.index + d[0].length - d[1]!.length)) : undefined;
|
||||
const decl = chosen === undefined ? undefined : decls[chosen];
|
||||
if (decl) {
|
||||
const after = decl.index + decl[0].length;
|
||||
if (call) return returnedTable(safe, after);
|
||||
return safe[after] === '[' || safe[after] === '{' ? after : null;
|
||||
return heldTable(safe, after);
|
||||
}
|
||||
if (!call) return null;
|
||||
const fn = new RegExp(`(?:^|[^\\w$.])function\\s+${id}\\s*\\(`).exec(safe);
|
||||
return fn ? returnedTable(safe, fn.index + fn[0].indexOf('function')) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The table a value written at `at` gives: the literal there, or the
|
||||
* function a call there names — `getRouteMap({ … })`, `await loadRoutes()` —
|
||||
* whose returned table it is.
|
||||
*/
|
||||
function heldTable(safe: string, at: number): number | TableName | null {
|
||||
if (safe[at] === '[' || safe[at] === '{') return at;
|
||||
const call = /(await\s+)?([A-Za-z_$][\w$]*)\s*\(/y;
|
||||
call.lastIndex = at;
|
||||
const m = call.exec(safe);
|
||||
return m ? { name: m[2]!, call: true, at: at + (m[1]?.length ?? 0) } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks, of a name's declarations in `file` (where each keyword sits), the
|
||||
* one in scope at `use`: in the innermost function around the use that
|
||||
* declares the name, the last declaration before the use, else the first
|
||||
* after it; else one at the module's top level. A declaration inside another
|
||||
* function is that function's own. With no use, it picks one at the top
|
||||
* level, which is what a module exports. The functions are the graph's — a
|
||||
* component, a method, an arrow function held in a `const` — so the blocks
|
||||
* inside one function are not told apart.
|
||||
*/
|
||||
function visibleAt(use: number | undefined, safe: string, file: string, context: ResolutionContext): (keywords: number[]) => number | undefined {
|
||||
return (keywords) => {
|
||||
const lineStarts = [0];
|
||||
for (let i = safe.indexOf('\n'); i !== -1; i = safe.indexOf('\n', i + 1)) lineStarts.push(i + 1);
|
||||
const offset = (line: number, column: number): number => (lineStarts[line - 1] ?? safe.length) + column;
|
||||
const fns = context.getNodesInFile(file)
|
||||
.filter((n) => FN_KINDS.has(n.kind))
|
||||
.map((n) => ({ start: offset(n.startLine, n.startColumn), end: offset(n.endLine, n.endColumn) }));
|
||||
// The function a declaration's own value is (`const routes = (user) =>
|
||||
// [ … ]`) starts after the keyword, so it is not around it.
|
||||
const around = (at: number) => fns.filter((f) => f.start < at && f.end > at);
|
||||
const scopes = new Set(use === undefined ? [] : around(use));
|
||||
let best: number | undefined;
|
||||
let depth = -1;
|
||||
keywords.forEach((at, i) => {
|
||||
const encl = around(at);
|
||||
if (!encl.every((f) => scopes.has(f))) return;
|
||||
if (encl.length > depth || (encl.length === depth && use !== undefined && at < use)) {
|
||||
best = i;
|
||||
depth = encl.length;
|
||||
}
|
||||
});
|
||||
return best;
|
||||
};
|
||||
}
|
||||
|
||||
/** The table a function at `at` returns: `(user) => [ … ]`, `(user) => ([ … ])`, `function routes(user) { return [ … ]; }`. */
|
||||
function returnedTable(safe: string, at: number): number | null {
|
||||
const head = /^(?:async\s+)?(?:function\b[^(]*\([^)]*\)|\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^={]*)?(=>)?\s*/.exec(safe.slice(at));
|
||||
|
||||
Reference in New Issue
Block a user