дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
feat(http-client): Laravel and Symfony endpoints (#7559)
Laravel and Symfony routes are indexed as HTTP endpoints for the Endpoints view and HTTP client navigation. The route index publishes only after the latest reads finish, and exclusions are evaluated relative to each scanned project root. Co-authored-by: samehelhawary <[email protected]>
Цей коміт міститься в:
1 джерело
82d8a6ea19
коміт
3078674a86
13 files changed
+1145
-16
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! Web framework routes, source side: the project's files that could declare a route
|
||||
//! (Spring's Java and Kotlin, Flask's and FastAPI's Python), with their text. The UI owns
|
||||
//! (Spring's Java and Kotlin, Flask's and FastAPI's Python, Laravel's and Symfony's PHP
|
||||
//! and YAML), with their text. The UI owns
|
||||
//! the parsers and the index they feed, so this side stays a cheap scan.
|
||||
|
||||
use crate::Host;
|
||||
@@ -31,8 +32,13 @@ pub(crate) struct RouteFiles {
|
||||
extensions: &'static [&'static str],
|
||||
words: &'static [&'static str],
|
||||
owners: &'static [&'static str],
|
||||
/// Folders whose files declare no route of the project.
|
||||
skipped: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// Installed packages (a virtualenv the ignore rules don't cover) declare their own examples.
|
||||
const PACKAGES: &[&str] = &["site-packages"];
|
||||
|
||||
/// Spring mappings: Java and Kotlin sources that name a request mapping annotation and a
|
||||
/// controller or Feign client, the only classes the UI reads them from. Other `…Mapping`
|
||||
/// names (MapStruct's `@Mapping`, mappers, DTOs) would otherwise fill the file budget in a
|
||||
@@ -41,16 +47,28 @@ pub(crate) const SPRING: RouteFiles = RouteFiles {
|
||||
extensions: &["java", "kt", "kts"],
|
||||
words: &["RequestMapping", "GetMapping", "PostMapping", "PutMapping", "DeleteMapping", "PatchMapping"],
|
||||
owners: &["Controller", "FeignClient"],
|
||||
skipped: PACKAGES,
|
||||
};
|
||||
/// Flask and FastAPI routes: Python sources that import either (blueprints, routers and the
|
||||
/// modules registering them all do).
|
||||
pub(crate) const PYTHON: RouteFiles = RouteFiles { extensions: &["py"], words: &["flask", "fastapi"], owners: &[] };
|
||||
pub(crate) const PYTHON: RouteFiles =
|
||||
RouteFiles { extensions: &["py"], words: &["flask", "fastapi"], owners: &[], skipped: PACKAGES };
|
||||
/// Laravel and Symfony routes: PHP sources that call the `Route` facade or carry a `Route`
|
||||
/// attribute or annotation, and the YAML files that give a route its controller. Not the
|
||||
/// installed packages, nor what the frameworks generate (Symfony's `var`, Laravel's `storage`).
|
||||
pub(crate) const PHP: RouteFiles = RouteFiles {
|
||||
extensions: &["php", "yaml", "yml"],
|
||||
words: &["Route::", "#[Route", "@Route", "controller:"],
|
||||
owners: &[],
|
||||
skipped: &["vendor", "node_modules", "var", "storage"],
|
||||
};
|
||||
|
||||
impl RouteFiles {
|
||||
fn declares_routes(&self, path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| self.extensions.contains(&e))
|
||||
// Installed packages (a virtualenv the ignore rules don't cover) declare their own examples.
|
||||
&& !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| self.extensions.iter().any(|ext| e.eq_ignore_ascii_case(ext)))
|
||||
&& !path.components().any(|c| self.skipped.iter().any(|folder| c.as_os_str() == *folder))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +79,7 @@ pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) ->
|
||||
let bytes = AtomicUsize::new(0);
|
||||
let truncated = AtomicBool::new(false);
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if !kind.declares_routes(path) {
|
||||
if !kind.declares_routes(path.strip_prefix(root).unwrap_or(path)) {
|
||||
return;
|
||||
}
|
||||
if bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
@@ -116,6 +134,11 @@ pub async fn python_route_sources(host: &Host, window: &str) -> IdeResult<Vec<Ro
|
||||
route_sources(host, window, PYTHON, "python").await
|
||||
}
|
||||
|
||||
/// Every Laravel / Symfony route source of the project, for the request-path index.
|
||||
pub async fn php_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
route_sources(host, window, PHP, "php").await
|
||||
}
|
||||
|
||||
async fn route_sources(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -180,6 +203,34 @@ mod tests {
|
||||
assert!(files[1].path.ends_with("app.py"), "{:?}", files[1].path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_and_yaml_sources_that_name_a_route_are_read_outside_packages_and_caches() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = tmp.path().join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("var/site/routes/web.PHP", "<?php Route::get('/', fn () => 'home');");
|
||||
write("var/site/src/Controller/BlogController.php", "<?php #[Route('/blog')] class BlogController {}");
|
||||
write("var/site/config/routes.yaml", "home:\n path: /\n controller: App\\Controller\\Home::index\n");
|
||||
write("var/site/config/services.yaml", "services:\n _defaults: { autowire: true }\n");
|
||||
write("var/site/src/Entity/Post.php", "<?php class Post {}");
|
||||
write("var/site/vendor/laravel/framework/routes.php", "<?php Route::get('/x', fn () => 1);");
|
||||
write("var/site/var/cache/dev/url_generating_routes.php", "<?php // #[Route('/blog')]");
|
||||
write("var/site/storage/framework/views/a.php", "<?php Route::has('x');");
|
||||
let root = tmp.path().join("var/site");
|
||||
let files = sources_in(&root, &[], PHP);
|
||||
let found: Vec<String> = files
|
||||
.iter()
|
||||
.map(|f| Path::new(&*f.path).strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"))
|
||||
.collect();
|
||||
assert_eq!(found, ["config/routes.yaml", "routes/web.PHP", "src/Controller/BlogController.php"]);
|
||||
// A Java package of such a name is still a place for controllers.
|
||||
assert!(SPRING.declares_routes(Path::new("src/main/java/shop/storage/StorageController.java")));
|
||||
assert!(!PHP.declares_routes(Path::new("storage/framework/views/a.php")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_name_no_mapping_are_left_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -140,6 +140,18 @@ Flask and FastAPI routes are indexed too, from the Python files that import eith
|
||||
- Path parameters are written `{name}` (Flask's `<int:id>` becomes `{id}`). The routes show in the **Endpoints** tab of Search Everywhere, complete in `.http` files, and a request URL navigates to its view function.
|
||||
- Each route gets an **Open in HTTP Client** gutter icon, which follows the file as you type; the request goes to `http://127.0.0.1:5000` (Flask) or `http://127.0.0.1:8000` (FastAPI).
|
||||
|
||||
### Laravel and Symfony
|
||||
|
||||
Laravel and Symfony routes are indexed too, from the PHP and YAML files that declare them (`vendor`, `node_modules`, Symfony's `var`, Laravel's `storage` and excluded folders are skipped):
|
||||
|
||||
- Laravel: `Route::get` / `post` / `put` / `patch` / `delete` / `options` / `any` / `match` / `view`, and `Route::resource` / `apiResource` with their `only` and `except`, in the files of a `routes` folder and in any file that imports the `Route` facade. The prefixes and controllers of the groups around a route are added (`Route::prefix('admin')->group(…)`, `Route::group(['prefix' => …], …)`, `Route::controller(…)`), and the routes of `routes/api.php` go under `/api`.
|
||||
- Symfony: `#[Route]` attributes and `@Route` annotations on a controller's methods, with the path and methods of the one on the class; an invokable controller's own route; and the routes of `config/routes.yaml` and `config/routes/*.yaml` that have a `path` and a `controller`.
|
||||
- A route whose path is only known at runtime (a variable, a concatenation) is left out rather than shown under a wrong URL. A prefix that another file adds is not known: a `Route::prefix()` in a service provider, or a YAML `resource:` import with a `prefix`.
|
||||
- Path parameters are written `{name}` (Laravel's `{user?}` and `{post:slug}` become `{user}` and `{post}`). The routes show in the **Endpoints** tab of Search Everywhere and complete in `.http` files.
|
||||
- Each route gets an **Open in HTTP Client** gutter icon, which follows the file as you type; the request goes to `http://127.0.0.1:8000`, where `artisan serve` and the **Symfony server** configuration listen.
|
||||
|
||||
This works with any PHP language server.
|
||||
|
||||
Plugins can contribute endpoints of other frameworks; they get an **Open in HTTP Client** gutter icon.
|
||||
|
||||
### Feign navigation
|
||||
|
||||
@@ -140,6 +140,18 @@ Flask 和 FastAPI 的路由也会建立索引,来源是导入了这两个框
|
||||
- 路径参数写成 `{name}`(Flask 的 `<int:id>` 变成 `{id}`)。这些路由会出现在随处搜索的 **端点** 标签页中,在 `.http` 文件里参与补全,请求 URL 也能跳转到对应的视图函数。
|
||||
- 每个路由旁有 **在 HTTP 客户端中打开** 边栏图标,会随输入实时更新,请求发往 `http://127.0.0.1:5000`(Flask)或 `http://127.0.0.1:8000`(FastAPI)。
|
||||
|
||||
### Laravel 和 Symfony
|
||||
|
||||
Laravel 和 Symfony 的路由也会建立索引,来源是声明路由的 PHP 和 YAML 文件(跳过 `vendor`、`node_modules`、Symfony 的 `var`、Laravel 的 `storage` 以及排除的文件夹):
|
||||
|
||||
- Laravel:`routes` 文件夹中的文件以及导入了 `Route` 门面的文件里的 `Route::get` / `post` / `put` / `patch` / `delete` / `options` / `any` / `match` / `view`,还有 `Route::resource` / `apiResource` 及其 `only` 和 `except`。路由外层分组的前缀和控制器会一并计入(`Route::prefix('admin')->group(…)`、`Route::group(['prefix' => …], …)`、`Route::controller(…)`),`routes/api.php` 中的路由位于 `/api` 之下。
|
||||
- Symfony:控制器方法上的 `#[Route]` 属性和 `@Route` 注解,带上类上那个的路径和方法;可调用控制器自身的路由;以及 `config/routes.yaml` 和 `config/routes/*.yaml` 中同时有 `path` 和 `controller` 的路由。
|
||||
- 路径只有在运行时才能确定的路由(变量、字符串拼接)会被略过,而不是显示在错误的 URL 下。其他文件添加的前缀无法得知:服务提供者中的 `Route::prefix()`,或带 `prefix` 的 YAML `resource:` 导入。
|
||||
- 路径参数写成 `{name}`(Laravel 的 `{user?}` 和 `{post:slug}` 变成 `{user}` 和 `{post}`)。这些路由会出现在随处搜索的 **端点** 标签页中,并在 `.http` 文件里参与补全。
|
||||
- 每个路由旁有 **在 HTTP 客户端中打开** 边栏图标,会随输入实时更新,请求发往 `http://127.0.0.1:8000`,即 `artisan serve` 和 **Symfony server** 配置监听的地址。
|
||||
|
||||
使用任何 PHP 语言服务器时都可用。
|
||||
|
||||
插件可以提供其他框架的端点,这些端点旁会有 **在 HTTP 客户端中打开** 边栏图标。
|
||||
|
||||
### Feign 导航
|
||||
|
||||
@@ -27,6 +27,17 @@ pub async fn python_route_sources(
|
||||
ide_host::ops::routes::python_route_sources(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
/// Laravel and Symfony route sources for the request-path index of Search Everywhere.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn php_route_sources(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
) -> IdeResult<Vec<ide_host::ops::routes::RouteSource>> {
|
||||
ide_host::ops::routes::php_route_sources(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
/// Cucumber feature files and step definition files, for step navigation.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
@@ -42,4 +53,4 @@ pub async fn cucumber_sources(
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
ide_command::desktop_domain!(cucumber_sources, python_route_sources, spring_route_sources);
|
||||
ide_command::desktop_domain!(cucumber_sources, php_route_sources, python_route_sources, spring_route_sources);
|
||||
@@ -58,6 +58,7 @@ const OFF_MAIN_THREAD: &[&str] = &[
|
||||
"plugin_set_secret",
|
||||
"spring_route_sources",
|
||||
"python_route_sources",
|
||||
"php_route_sources",
|
||||
];
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -543,6 +543,7 @@ notebook_undo always project_host bin
|
||||
notebook_variables trusted project_host bindings async
|
||||
open_project always project_host bindings async
|
||||
path_completions always project_host bindings async
|
||||
php_route_sources trusted desktop bindings async
|
||||
plots_delete always project_host bindings async
|
||||
plugin_activation_event trusted desktop bindings async
|
||||
plugin_answer_clipboard trusted project_host bindings sync
|
||||
|
||||
@@ -1505,6 +1505,8 @@ export const commands = {
|
||||
openProject: (path: string) => typedError<ProjectInfo_Serialize, IdeError>(__TAURI_INVOKE("open_project", { path })),
|
||||
/** Files and folders that continue `prefix`, a path being typed in `from`. */
|
||||
pathCompletions: (from: IpcPath, prefix: string) => typedError<PathCompletion[], IdeError>(__TAURI_INVOKE("path_completions", { from, prefix })),
|
||||
/** Laravel and Symfony route sources for the request-path index of Search Everywhere. */
|
||||
phpRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("php_route_sources")),
|
||||
/** Deletes figures the Plots tool window dropped; only figures in this project's plots folder. */
|
||||
plotsDelete: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("plots_delete", { paths })),
|
||||
/** An activation event from the UI: `kind` is `language`, `file` (project-relative path) or `view`. */
|
||||
|
||||
@@ -9,6 +9,7 @@ import { gutterIconMarkup, showContextMenu } from "@/ui";
|
||||
import { notifications, onEndpointsChanged, searchEndpoints, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { appendGeneratedRequests } from "./generatedRequests";
|
||||
import { headerCompletion } from "./headers";
|
||||
import { phpEndpointsOf } from "./php/routeIndex";
|
||||
import { pythonEndpointsOf } from "./python/routeIndex";
|
||||
import { sourceReader } from "./spring/editor";
|
||||
import { findHost } from "./spring/request";
|
||||
@@ -23,8 +24,13 @@ export function renderEndpoint(e: EndpointEntry, host = "http://localhost:8080")
|
||||
return `### ${e.handler ?? `${e.method} ${e.url}`}\n${e.method === "*" ? "GET" : e.method} ${host}${endpointUrl(e.url)}\n`;
|
||||
}
|
||||
|
||||
/** The development servers' default addresses (`flask run`, `uvicorn`). */
|
||||
const DEFAULT_HOSTS: Record<string, string> = { Flask: "http://127.0.0.1:5000", FastAPI: "http://127.0.0.1:8000" };
|
||||
/** The development servers' default addresses (`flask run`, `uvicorn`, `artisan serve`, the Symfony server). */
|
||||
const DEFAULT_HOSTS: Record<string, string> = {
|
||||
Flask: "http://127.0.0.1:5000",
|
||||
FastAPI: "http://127.0.0.1:8000",
|
||||
Laravel: "http://127.0.0.1:8000",
|
||||
Symfony: "http://127.0.0.1:8000",
|
||||
};
|
||||
|
||||
export async function openEndpoint(endpoint: EndpointEntry): Promise<void> {
|
||||
try {
|
||||
@@ -138,13 +144,18 @@ export function endpointEditorExtension(ctx: EditorDocContext): Extension {
|
||||
clearTimeout(this.timer);
|
||||
const seq = ++this.seq;
|
||||
const root = useProject.getState().project?.root ?? null;
|
||||
// Plugin endpoints, and in a Python file its Flask / FastAPI routes as typed (not as last saved).
|
||||
// Spring draws its own icons, with request bodies.
|
||||
const python =
|
||||
root && ctx.language === "python"
|
||||
? pythonEndpointsOf(root, ctx.path, this.view.state.doc.toString()).catch(() => [])
|
||||
: Promise.resolve([]);
|
||||
void Promise.all([searchEndpoints(root, isPluginProvider), python]).then(([plugins, routes]) => {
|
||||
// Plugin endpoints, and the file's own routes as typed (not as last saved): Flask / FastAPI
|
||||
// in a Python file, Laravel / Symfony in a PHP file or a routes YAML. Spring draws its own
|
||||
// icons, with request bodies.
|
||||
const text = () => this.view.state.doc.toString();
|
||||
const own: Promise<EndpointEntry[]> = !root
|
||||
? Promise.resolve([])
|
||||
: ctx.language === "python"
|
||||
? pythonEndpointsOf(root, ctx.path, text()).catch(() => [])
|
||||
: ctx.language === "php" || ctx.language === "yaml"
|
||||
? Promise.resolve(phpEndpointsOf(root, ctx.path, text()))
|
||||
: Promise.resolve([]);
|
||||
void Promise.all([searchEndpoints(root, isPluginProvider), own]).then(([plugins, routes]) => {
|
||||
const entries = [...plugins.filter((e) => e.pluginId), ...routes];
|
||||
if (this.destroyed || seq !== this.seq) return;
|
||||
const byLine = new Map<number, EndpointEntry[]>();
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
} from "./spring/editor";
|
||||
import { endpointEditorExtension, OPEN_ENDPOINT, openEndpoint } from "./endpoints";
|
||||
import type { EndpointEntry } from "@/workbench/contributions";
|
||||
import { registerPhpEndpointProvider } from "./php/routeIndex";
|
||||
import { registerPythonEndpointProvider } from "./python/routeIndex";
|
||||
import { registerSpringEndpointProvider } from "./spring/routeIndex";
|
||||
import {
|
||||
@@ -147,6 +148,7 @@ export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerSpringEndpointProvider(),
|
||||
registerPythonEndpointProvider(),
|
||||
registerPhpEndpointProvider(),
|
||||
registerFeignNavigation(),
|
||||
registerVariableNavigation(),
|
||||
registerUrlNavigation(),
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { commands, emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { phpEndpointsOf, phpRouteIndex, registerPhpEndpointProvider } from "./routeIndex";
|
||||
|
||||
const scanSources = vi.spyOn(commands, "phpRouteSources");
|
||||
const readText = vi.spyOn(commands, "fsReadText");
|
||||
|
||||
const web = (path: string) => `<?php\nRoute::get('${path}', [OrderController::class, 'index']);\n`;
|
||||
const CONTROLLER = `<?php
|
||||
#[Route('/blog')]
|
||||
class BlogController {
|
||||
#[Route('/{slug}', methods: ['GET'])]
|
||||
public function show() {}
|
||||
}
|
||||
`;
|
||||
|
||||
let dispose: (() => void) | undefined;
|
||||
afterEach(() => {
|
||||
dispose?.();
|
||||
dispose = undefined;
|
||||
scanSources.mockReset();
|
||||
readText.mockReset();
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
|
||||
const urls = async () => (await phpRouteIndex("/p")).map((e) => `${e.framework} ${e.method} ${e.url}`);
|
||||
const changed = (kind: "created" | "modified" | "removed", path: string) =>
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [], [kind]: [ipcPath(path)] });
|
||||
const text = (data: string) => ({ status: "ok" as const, data });
|
||||
|
||||
describe("the Laravel / Symfony endpoint provider", () => {
|
||||
it("scans once, then reads only the changed files again", async () => {
|
||||
dispose = registerPhpEndpointProvider();
|
||||
scanSources.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{ path: ipcPath("/p/routes/web.php"), text: web("/orders") },
|
||||
{ path: ipcPath("/p/src/Controller/BlogController.php"), text: CONTROLLER },
|
||||
{ path: ipcPath("/p/config/services.yaml"), text: "services:\n x:\n controller: y\n" },
|
||||
],
|
||||
});
|
||||
expect(await urls()).toEqual(["Laravel GET /orders", "Symfony GET /blog/{slug}"]);
|
||||
const entry = (await phpRouteIndex("/p"))[0]!;
|
||||
expect(entry).toMatchObject({ controller: "OrderController", methodName: "index", rel: "routes/web.php", line: 1 });
|
||||
await urls();
|
||||
expect(scanSources).toHaveBeenCalledTimes(1);
|
||||
|
||||
readText.mockResolvedValue(text(web("/invoices")));
|
||||
changed("modified", "/p/routes/web.php");
|
||||
expect(await urls()).toEqual(["Laravel GET /invoices", "Symfony GET /blog/{slug}"]);
|
||||
expect(scanSources).toHaveBeenCalledTimes(1);
|
||||
expect(readText.mock.calls.map(([path]) => path)).toEqual([ipcPath("/p/routes/web.php")]);
|
||||
|
||||
// A new routes file joins; a removed one, or one that no longer names a route, leaves.
|
||||
readText.mockResolvedValue(text("home:\n path: /\n controller: App\\Home::index\n"));
|
||||
changed("created", "/p/config/routes.yaml");
|
||||
expect(await urls()).toContain("Symfony * /");
|
||||
readText.mockResolvedValue({ status: "error", error: { kind: "notFound", message: "no such file" } as never });
|
||||
changed("removed", "/p/routes/web.php");
|
||||
expect(await urls()).toEqual(["Symfony GET /blog/{slug}", "Symfony * /"]);
|
||||
});
|
||||
|
||||
it("keeps the newer text of a file when an older read of it finishes last", async () => {
|
||||
dispose = registerPhpEndpointProvider();
|
||||
scanSources.mockResolvedValue({ status: "ok", data: [{ path: ipcPath("/p/routes/web.php"), text: web("/a") }] });
|
||||
expect(await urls()).toEqual(["Laravel GET /a"]);
|
||||
|
||||
const reads: ((data: string) => void)[] = [];
|
||||
readText.mockImplementation(() => new Promise((resolve) => reads.push((data) => resolve(text(data)))));
|
||||
const reading = (count: number) => vi.waitFor(() => expect(reads).toHaveLength(count));
|
||||
changed("modified", "/p/routes/web.php");
|
||||
const older = urls();
|
||||
await reading(1);
|
||||
changed("modified", "/p/routes/web.php");
|
||||
const newer = urls();
|
||||
await reading(2);
|
||||
|
||||
reads[1]!(web("/new"));
|
||||
expect(await newer).toEqual(["Laravel GET /new"]);
|
||||
reads[0]!(web("/old"));
|
||||
expect(await older).toEqual(["Laravel GET /new"]);
|
||||
expect(await urls()).toEqual(["Laravel GET /new"]);
|
||||
expect(reads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("waits for a change arriving during a read before publishing routes", async () => {
|
||||
dispose = registerPhpEndpointProvider();
|
||||
scanSources.mockResolvedValue({ status: "ok", data: [{ path: ipcPath("/p/routes/web.php"), text: web("/a") }] });
|
||||
expect(await urls()).toEqual(["Laravel GET /a"]);
|
||||
|
||||
const reads: ((data: string) => void)[] = [];
|
||||
readText.mockImplementation(() => new Promise((resolve) => reads.push((data) => resolve(text(data)))));
|
||||
changed("modified", "/p/routes/web.php");
|
||||
const routes = urls();
|
||||
await vi.waitFor(() => expect(reads).toHaveLength(1));
|
||||
changed("modified", "/p/routes/web.php");
|
||||
reads[0]!(web("/old"));
|
||||
await vi.waitFor(() => expect(reads).toHaveLength(2));
|
||||
reads[1]!(web("/new"));
|
||||
expect(await routes).toEqual(["Laravel GET /new"]);
|
||||
});
|
||||
|
||||
it("checks excluded folders relative to the project's root", () => {
|
||||
expect(phpEndpointsOf("/var/site", "/var/site/routes/web.php", web("/ok"))).toHaveLength(1);
|
||||
expect(phpEndpointsOf("/var/site", "/var/site/vendor/routes/web.php", web("/ignored"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores changes to other files, installed packages and generated ones", async () => {
|
||||
dispose = registerPhpEndpointProvider();
|
||||
scanSources.mockResolvedValue({ status: "ok", data: [{ path: ipcPath("/p/routes/web.php"), text: web("/a") }] });
|
||||
expect(await urls()).toEqual(["Laravel GET /a"]);
|
||||
for (const path of ["/p/app.js", "/p/vendor/laravel/framework/routes.php", "/p/var/cache/dev/routes.php"])
|
||||
changed("modified", path);
|
||||
expect(await urls()).toEqual(["Laravel GET /a"]);
|
||||
expect(readText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("gives the gutter the routes of the text being edited", async () => {
|
||||
const routes = phpEndpointsOf("/p", ipcPath("/p/routes/api.php"), `\n\n${web("/edited")}`);
|
||||
expect(routes.map((e) => `${e.method} ${e.url} ${e.line}`)).toEqual(["GET /api/edited 3"]);
|
||||
expect(phpEndpointsOf("/p", ipcPath("/p/vendor/x/routes/web.php"), web("/x"))).toEqual([]);
|
||||
expect(phpEndpointsOf("/p", ipcPath("/p/app/Models/Order.php"), "<?php class Order {}")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Laravel / Symfony request-path index: the project's route sources scanned once, then kept
|
||||
* up to date file by file as PHP and YAML files change.
|
||||
*/
|
||||
import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
||||
import { endpointsChanged, registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { mentionsRoutes, parsePhpRoutes, type PhpRoute } from "./routes";
|
||||
|
||||
export const PHP_ENDPOINTS = "http.php";
|
||||
|
||||
/** More changed files than this at once (a branch switch) rescan the project instead. */
|
||||
const MAX_FILE_UPDATES = 50;
|
||||
|
||||
interface Index {
|
||||
key: string;
|
||||
root: string;
|
||||
/** The routes of each source, by its path. */
|
||||
files: Promise<Map<string, PhpRoute[]>>;
|
||||
routes: EndpointEntry[] | null;
|
||||
/** Files awaiting a read, and the latest read in flight for each file. */
|
||||
pending: Set<string>;
|
||||
reading: Map<string, Promise<void>>;
|
||||
}
|
||||
|
||||
let cached: Index | null = null;
|
||||
export function registerPhpEndpointProvider(): () => void {
|
||||
reset();
|
||||
const unregister = registerEndpointProvider({ id: PHP_ENDPOINTS, endpoints: phpRouteIndex });
|
||||
const unsubscribe = onIdeEvent("fsChanged", (e) => {
|
||||
const index = cached;
|
||||
if (!index) return;
|
||||
const changed = [...e.created, ...e.modified, ...e.removed].map((p) => ipcPath(String(p)));
|
||||
const sources = changed.filter((path) => sourcePath(index.root, path) !== null);
|
||||
if (!sources.length) return;
|
||||
for (const path of sources) index.pending.add(path);
|
||||
if (index.pending.size > MAX_FILE_UPDATES) reset();
|
||||
else index.routes = null;
|
||||
endpointsChanged();
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
unregister();
|
||||
reset();
|
||||
};
|
||||
}
|
||||
|
||||
function reset() {
|
||||
cached = null;
|
||||
}
|
||||
|
||||
export async function phpRouteIndex(root: string): Promise<EndpointEntry[]> {
|
||||
const index = current(root);
|
||||
if (index.routes) return index.routes;
|
||||
const files = await index.files;
|
||||
while (cached === index && (index.pending.size || index.reading.size)) {
|
||||
for (const path of index.pending) readChangedSource(index, files, path);
|
||||
index.pending.clear();
|
||||
// Changes arriving during this read are picked up before publishing the routes.
|
||||
// oxlint-disable-next-line no-await-in-loop -- each round drains the latest reads before checking for more changes.
|
||||
await Promise.all(index.reading.values());
|
||||
}
|
||||
if (cached !== index) return cached && cached.root !== root ? [] : phpRouteIndex(root);
|
||||
return (index.routes ??= [...files.values()].flat().map(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* The routes of the file at `path` with `text` in place of what is on disk: the editor's
|
||||
* gutter while the file is being edited.
|
||||
*/
|
||||
export function phpEndpointsOf(root: string, path: string, text: string): EndpointEntry[] {
|
||||
const rel = mentionsRoutes(text) ? sourcePath(root, ipcPath(path)) : null;
|
||||
return rel === null ? [] : parsePhpRoutes({ path, rel, text }).map(entry);
|
||||
}
|
||||
|
||||
function current(root: string): Index {
|
||||
const project = projectOf(root);
|
||||
const key = JSON.stringify([root, project?.workspace?.projects ?? null]);
|
||||
if (cached?.key !== key) {
|
||||
const files = scan(root).catch((error: unknown) => {
|
||||
if (cached?.files === files) cached = null;
|
||||
throw error;
|
||||
});
|
||||
cached = { key, root, files, routes: null, pending: new Set(), reading: new Map() };
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
const projectOf = (root: string): ProjectInfo | null => {
|
||||
const project = useProject.getState().project;
|
||||
return project?.root === root ? project : null;
|
||||
};
|
||||
|
||||
/** Reads the current version of one file; an earlier read must not overwrite it. */
|
||||
function readChangedSource(index: Index, files: Map<string, PhpRoute[]>, path: string) {
|
||||
const read = call(commands.fsReadText(path))
|
||||
.catch(() => null)
|
||||
.then((text) => {
|
||||
if (index.reading.get(path) !== read) return;
|
||||
index.reading.delete(path);
|
||||
const rel = text !== null && mentionsRoutes(text) ? sourcePath(index.root, path) : null;
|
||||
const routes = text !== null && rel !== null ? parsePhpRoutes({ path, rel, text }) : [];
|
||||
if (routes.length) files.set(path, routes);
|
||||
else files.delete(path);
|
||||
});
|
||||
index.reading.set(path, read);
|
||||
}
|
||||
|
||||
/** The route source's path relative to the project folder that owns it. */
|
||||
function sourcePath(root: string, path: string): string | null {
|
||||
if (!/\.(php|ya?ml)$/i.test(path)) return null;
|
||||
const project = projectOf(root);
|
||||
const folder = project ? projectFolder(project, path)?.root : root;
|
||||
if (!folder) return null;
|
||||
const base = ipcPath(folder).replace(/\/$/, "");
|
||||
if (!isSameOrInside(path, base)) return null;
|
||||
const rel = relativePath(base, path);
|
||||
return /(?:^|\/)(vendor|node_modules|var|storage)\//.test(rel) ? null : rel;
|
||||
}
|
||||
|
||||
async function scan(root: string): Promise<Map<string, PhpRoute[]>> {
|
||||
const files = new Map<string, PhpRoute[]>();
|
||||
for (const source of await call(commands.phpRouteSources())) {
|
||||
const path = ipcPath(source.path);
|
||||
const rel = sourcePath(root, path);
|
||||
const routes = rel === null ? [] : parsePhpRoutes({ path, rel, text: source.text });
|
||||
if (routes.length) files.set(path, routes);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const entry = (r: PhpRoute): EndpointEntry => ({
|
||||
method: r.method,
|
||||
url: r.url,
|
||||
framework: r.framework,
|
||||
controller: r.controller,
|
||||
methodName: r.handler,
|
||||
path: r.path,
|
||||
rel: r.rel,
|
||||
line: r.line,
|
||||
col: r.col,
|
||||
});
|
||||
@@ -0,0 +1,260 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mentionsRoutes, parsePhpRoutes, type PhpRoute } from "./routes";
|
||||
|
||||
const parse = (rel: string, text: string) => parsePhpRoutes({ path: `/p/${rel}`, rel, text });
|
||||
const shown = (routes: PhpRoute[]) =>
|
||||
routes.map((r) => `${r.method} ${r.url}${r.controller ? ` ${r.controller}::${r.handler}` : ""}`);
|
||||
|
||||
describe("Laravel routes", () => {
|
||||
it("reads the facade's calls with their controllers", () => {
|
||||
const routes = parse(
|
||||
"routes/web.php",
|
||||
`<?php
|
||||
use App\\Http\\Controllers\\OrderController;
|
||||
use Illuminate\\Support\\Facades\\Route;
|
||||
|
||||
Route::get('/', fn () => view('welcome'));
|
||||
Route::get('/orders', [OrderController::class, 'index'])->name('orders.index');
|
||||
Route::post("orders", 'OrderController@store');
|
||||
Route::delete('/orders/{order}', \\App\\Http\\Controllers\\DeleteOrder::class);
|
||||
Route::match(['get', 'post'], '/search', [SearchController::class, 'run']);
|
||||
Route::any('/hook', function () { return 'ok'; });
|
||||
Route::view('/about', 'pages.about');
|
||||
`,
|
||||
);
|
||||
expect(shown(routes)).toEqual([
|
||||
"GET /",
|
||||
"GET /orders OrderController::index",
|
||||
"POST /orders OrderController::store",
|
||||
"DELETE /orders/{order} DeleteOrder::__invoke",
|
||||
"GET /search SearchController::run",
|
||||
"POST /search SearchController::run",
|
||||
"* /hook",
|
||||
"GET /about",
|
||||
]);
|
||||
expect(routes[1]).toMatchObject({ framework: "Laravel", path: "/p/routes/web.php", line: 5, col: 0 });
|
||||
});
|
||||
|
||||
it("adds the prefixes and controllers of the groups around a route", () => {
|
||||
const routes = parse(
|
||||
"routes/web.php",
|
||||
`<?php
|
||||
Route::prefix('admin')->middleware('auth')->group(function () {
|
||||
Route::get('/', [DashboardController::class, 'show']);
|
||||
Route::controller(UserController::class)->prefix('users')->group(function () {
|
||||
Route::get('/{user?}', 'show');
|
||||
Route::put('{user:slug}/roles', 'roles');
|
||||
});
|
||||
Route::group(['prefix' => 'reports', 'middleware' => ['can:read']], function () {
|
||||
Route::get('monthly', MonthlyReport::class);
|
||||
});
|
||||
});
|
||||
Route::prefix('v2')->get('/ping', fn () => 'pong');
|
||||
Route::get('/after', fn () => 1);
|
||||
`,
|
||||
);
|
||||
expect(shown(routes)).toEqual([
|
||||
"GET /admin DashboardController::show",
|
||||
"GET /admin/users/{user} UserController::show",
|
||||
"PUT /admin/users/{user}/roles UserController::roles",
|
||||
"GET /admin/reports/monthly MonthlyReport::__invoke",
|
||||
"GET /v2/ping",
|
||||
"GET /after",
|
||||
]);
|
||||
expect(routes[1]!.line).toBe(4);
|
||||
expect(routes[1]!.col).toBe(8);
|
||||
});
|
||||
|
||||
it("puts the routes of routes/api.php under /api and expands resources", () => {
|
||||
const routes = parse(
|
||||
"routes/api.php",
|
||||
`<?php
|
||||
Route::apiResource('photos', PhotoController::class)->only(['index', 'show']);
|
||||
Route::resource('photos.comments', CommentController::class)->except('create', 'edit', 'index', 'store');
|
||||
Route::apiResource('categories', CategoryController::class);
|
||||
`,
|
||||
);
|
||||
expect(shown(routes)).toEqual([
|
||||
"GET /api/photos PhotoController::index",
|
||||
"GET /api/photos/{photo} PhotoController::show",
|
||||
"GET /api/photos/{photo}/comments/{comment} CommentController::show",
|
||||
"PUT /api/photos/{photo}/comments/{comment} CommentController::update",
|
||||
"DELETE /api/photos/{photo}/comments/{comment} CommentController::destroy",
|
||||
"GET /api/categories CategoryController::index",
|
||||
"POST /api/categories CategoryController::store",
|
||||
"GET /api/categories/{category} CategoryController::show",
|
||||
"PUT /api/categories/{category} CategoryController::update",
|
||||
"DELETE /api/categories/{category} CategoryController::destroy",
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves out what a comment, a string or another class named Route holds, and paths known only at runtime", () => {
|
||||
const routes = parse(
|
||||
"routes/web.php",
|
||||
`<?php
|
||||
// Route::get('/commented', fn () => 1);
|
||||
/* Route::get('/block', fn () => 1); */
|
||||
# Route::get('/hash', fn () => 1);
|
||||
$help = "Route::get('/in-a-string', …)";
|
||||
Route::get($prefix . '/dynamic', fn () => 1);
|
||||
Route::get("/users/$id", fn () => 1);
|
||||
Route::get('/kept', fn () => ')' . "(");
|
||||
Route::middleware('web')->group(base_path('routes/extra.php'));
|
||||
`,
|
||||
);
|
||||
expect(shown(routes)).toEqual(["GET /kept"]);
|
||||
// Outside a routes folder, only a file that imports the facade.
|
||||
const other = `<?php\nnamespace App;\nclass Map { function a() { Route::get('/x', 1); } }\n`;
|
||||
expect(parse("app/Map.php", other)).toEqual([]);
|
||||
const provider = `<?php\nuse Illuminate\\Support\\Facades\\Route;\nRoute::get('/health', fn () => 'ok');\n`;
|
||||
expect(shown(parse("app/Providers/AppServiceProvider.php", provider))).toEqual(["GET /health"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Symfony routes", () => {
|
||||
it("reads the attributes of a controller and its methods", () => {
|
||||
const routes = parse(
|
||||
"src/Controller/BlogController.php",
|
||||
`<?php
|
||||
namespace App\\Controller;
|
||||
|
||||
use Symfony\\Component\\Routing\\Attribute\\Route;
|
||||
|
||||
#[Route('/blog', name: 'blog_')]
|
||||
final class BlogController extends AbstractController
|
||||
{
|
||||
#[Route('', name: 'index', methods: ['GET'])]
|
||||
public function index(): Response {}
|
||||
|
||||
#[Route(path: '/{slug}', name: 'show', requirements: ['slug' => '[a-z-]+'], methods: ['GET', 'HEAD'])]
|
||||
#[IsGranted('ROLE_USER')]
|
||||
public function show(string $slug): Response {}
|
||||
|
||||
#[Route('/{id}/edit', 'edit')]
|
||||
public function edit(int $id): Response {}
|
||||
|
||||
private function helper(): void {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
expect(shown(routes)).toEqual([
|
||||
"GET /blog BlogController::index",
|
||||
"GET /blog/{slug} BlogController::show",
|
||||
"HEAD /blog/{slug} BlogController::show",
|
||||
"* /blog/{id}/edit BlogController::edit",
|
||||
]);
|
||||
expect(routes[0]).toMatchObject({ framework: "Symfony", line: 8, col: 4 });
|
||||
});
|
||||
|
||||
it("gives a class's methods to routes that name none, and reads an invokable controller", () => {
|
||||
const api = parse(
|
||||
"src/Controller/Api.php",
|
||||
`<?php
|
||||
#[\\Symfony\\Component\\Routing\\Attribute\\Route('/api', methods: 'POST')]
|
||||
class Api {
|
||||
#[Route('/orders')]
|
||||
public function create() {}
|
||||
#[Route('/orders/{id}', methods: ['DELETE'])]
|
||||
public function remove() {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
expect(shown(api)).toEqual(["POST /api/orders Api::create", "DELETE /api/orders/{id} Api::remove"]);
|
||||
const invokable = parse(
|
||||
"src/Controller/Health.php",
|
||||
`<?php\n#[AsController]\n#[Route('/health', methods: ['GET'])]\nclass Health { public function __invoke() { return new class extends Base {}; } }\n`,
|
||||
);
|
||||
expect(shown(invokable)).toEqual(["GET /health Health::__invoke"]);
|
||||
// A prefix on a class without routed methods or `__invoke` is no route.
|
||||
expect(parse("src/A.php", `<?php\n#[Route('/a')]\nclass A { public function b() {} }\n`)).toEqual([]);
|
||||
});
|
||||
|
||||
it("reads the annotations of older controllers", () => {
|
||||
const routes = parse(
|
||||
"src/Controller/LegacyController.php",
|
||||
`<?php
|
||||
/**
|
||||
* @Route("/legacy")
|
||||
*/
|
||||
class LegacyController
|
||||
{
|
||||
/**
|
||||
* Lists them.
|
||||
*
|
||||
* @Route("/items", name="legacy_items", methods={"GET", "POST"})
|
||||
*/
|
||||
public function items() {}
|
||||
|
||||
/** @Route("/items/{id}") */
|
||||
public function item() {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
expect(shown(routes)).toEqual([
|
||||
"GET /legacy/items LegacyController::items",
|
||||
"POST /legacy/items LegacyController::items",
|
||||
"* /legacy/items/{id} LegacyController::item",
|
||||
]);
|
||||
expect(routes[0]!.line).toBe(9);
|
||||
});
|
||||
|
||||
it("reads the routes of config/routes.yaml that name a controller", () => {
|
||||
const text = `# Routes
|
||||
home:
|
||||
path: /
|
||||
controller: App\\Controller\\HomeController::index
|
||||
|
||||
blog_show:
|
||||
path: '/blog/{slug}' # one post
|
||||
controller: 'App\\Controller\\BlogController::show'
|
||||
methods: GET|HEAD
|
||||
|
||||
api_orders:
|
||||
path: /api/orders
|
||||
controller: App\\Controller\\Api\\OrderController
|
||||
methods: [POST, put]
|
||||
|
||||
listed:
|
||||
path: /listed
|
||||
controller: App\\Controller\\Listed::run
|
||||
methods:
|
||||
- GET
|
||||
- DELETE
|
||||
defaults:
|
||||
_format: json
|
||||
|
||||
controllers:
|
||||
resource:
|
||||
path: ../src/Controller/
|
||||
namespace: App\\Controller
|
||||
type: attribute
|
||||
|
||||
redirect:
|
||||
path: /old
|
||||
`;
|
||||
const routes = parse("config/routes.yaml", text);
|
||||
expect(shown(routes)).toEqual([
|
||||
"* / HomeController::index",
|
||||
"GET /blog/{slug} BlogController::show",
|
||||
"HEAD /blog/{slug} BlogController::show",
|
||||
"POST /api/orders OrderController::__invoke",
|
||||
"PUT /api/orders OrderController::__invoke",
|
||||
"GET /listed Listed::run",
|
||||
"DELETE /listed Listed::run",
|
||||
]);
|
||||
expect(routes[1]).toMatchObject({ framework: "Symfony", line: 5, col: 0, rel: "config/routes.yaml" });
|
||||
expect(shown(parse("config/routes/admin.yml", "admin:\n path: /admin\n controller: App\\Admin::home\n"))).toEqual(
|
||||
["* /admin Admin::home"],
|
||||
);
|
||||
// Other YAML that happens to say `controller:` is not a routes file.
|
||||
expect(parse("config/services.yaml", "home:\n path: /\n controller: App\\Home::index\n")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the route source filter", () => {
|
||||
it("matches what the backend picks files by", () => {
|
||||
for (const text of ["Route::get('/')", "#[Route('/')]", '@Route("/")', "controller: App\\Home::index"])
|
||||
expect(mentionsRoutes(text), text).toBe(true);
|
||||
expect(mentionsRoutes("<?php class Post {}")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,497 @@
|
||||
/**
|
||||
* Laravel and Symfony routes read from a project's sources: Laravel's `Route::get(…)` calls
|
||||
* with the prefixes and controllers of the groups around them, Symfony's `#[Route]`
|
||||
* attributes (and `@Route` annotations) on controllers and their methods, and the routes of
|
||||
* Symfony's `config/routes*.yaml`. A text scan, not a PHP parser: comments are blanked first
|
||||
* and strings are skipped as wholes, so brackets and keywords inside them don't count. A
|
||||
* route whose path is only known at runtime (a variable, a concatenation) is left out rather
|
||||
* than shown under a wrong URL, and so is a prefix another file adds (a `Route::prefix()` in
|
||||
* a service provider, a YAML `resource:` import), except Laravel's `/api` for `routes/api.php`.
|
||||
*/
|
||||
|
||||
export interface PhpSource {
|
||||
/** Absolute path. */
|
||||
path: string;
|
||||
/** Path relative to its project folder, `/`-separated. */
|
||||
rel: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface PhpRoute {
|
||||
framework: "Laravel" | "Symfony";
|
||||
/** `GET`, `POST`, …; `*` for any. */
|
||||
method: string;
|
||||
/** The full path, path parameters as `{name}`. */
|
||||
url: string;
|
||||
/** The controller class, without its namespace; empty for a closure. */
|
||||
controller: string;
|
||||
/** The controller's method; empty for a closure. */
|
||||
handler: string;
|
||||
path: string;
|
||||
rel: string;
|
||||
/** 0-based line and UTF-16 column of the declaration. */
|
||||
line: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
/** The words the backend picks route sources by: a file with none of them declares no route. */
|
||||
export const mentionsRoutes = (text: string) =>
|
||||
text.includes("Route::") || text.includes("#[Route") || text.includes("@Route") || text.includes("controller:");
|
||||
|
||||
export function parsePhpRoutes(source: PhpSource): PhpRoute[] {
|
||||
if (/\.ya?ml$/i.test(source.rel)) return isSymfonyRouteFile(source.rel) ? yamlRoutes(source) : [];
|
||||
const code = blankComments(source.text);
|
||||
return [...laravelRoutes(source, code), ...attributeRoutes(source, code), ...annotationRoutes(source, code)];
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ the text
|
||||
|
||||
/** `text` with its comments as spaces (offsets kept); `#[` starts an attribute, not a comment. */
|
||||
function blankComments(text: string): string {
|
||||
let out = "";
|
||||
let i = 0;
|
||||
const blank = (to: number) => {
|
||||
out += text.slice(i, to).replace(/[^\n]/g, " ");
|
||||
i = to;
|
||||
};
|
||||
while (i < text.length) {
|
||||
const ch = text[i]!;
|
||||
const next = text[i + 1];
|
||||
if (ch === "'" || ch === '"') {
|
||||
const end = stringEnd(text, i);
|
||||
out += text.slice(i, end);
|
||||
i = end;
|
||||
} else if (ch === "/" && next === "*") {
|
||||
const end = text.indexOf("*/", i + 2);
|
||||
blank(end < 0 ? text.length : end + 2);
|
||||
} else if ((ch === "/" && next === "/") || (ch === "#" && next !== "[")) {
|
||||
const end = text.indexOf("\n", i);
|
||||
blank(end < 0 ? text.length : end);
|
||||
} else {
|
||||
out += ch;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `code` with the text of its strings as spaces (offsets kept): where to look for keywords. */
|
||||
function blankStrings(code: string): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < code.length;) {
|
||||
const ch = code[i]!;
|
||||
if (ch === "'" || ch === '"') {
|
||||
const end = stringEnd(code, i);
|
||||
out += ch + code.slice(i + 1, end).replace(/[^\n]/g, " ");
|
||||
i = end;
|
||||
} else {
|
||||
out += ch;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The offset after the string that starts at `at`. */
|
||||
function stringEnd(text: string, at: number): number {
|
||||
const quote = text[at];
|
||||
for (let i = at + 1; i < text.length; i++) {
|
||||
if (text[i] === "\\") i++;
|
||||
else if (text[i] === quote) return i + 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
const CLOSERS: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
|
||||
|
||||
/** The offset of the bracket closing the one at `open`; -1 when it is never closed. */
|
||||
function closing(code: string, open: number): number {
|
||||
const stack: string[] = [];
|
||||
for (let i = open; i < code.length; i++) {
|
||||
const ch = code[i]!;
|
||||
if (ch === "'" || ch === '"') i = stringEnd(code, i) - 1;
|
||||
else if (CLOSERS[ch]) stack.push(CLOSERS[ch]);
|
||||
else if (ch === stack[stack.length - 1]) {
|
||||
stack.pop();
|
||||
if (!stack.length) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** The comma-separated parts of `code` between `from` and `to`, nested brackets and strings whole. */
|
||||
function parts(code: string, from: number, to: number): string[] {
|
||||
const out: string[] = [];
|
||||
let start = from;
|
||||
for (let i = from; i < to; i++) {
|
||||
const ch = code[i]!;
|
||||
if (ch === "'" || ch === '"') i = stringEnd(code, i) - 1;
|
||||
else if (CLOSERS[ch]) {
|
||||
const end = closing(code, i);
|
||||
if (end < 0 || end >= to) break;
|
||||
i = end;
|
||||
} else if (ch === ",") {
|
||||
out.push(code.slice(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
const last = code.slice(start, to);
|
||||
if (last.trim()) out.push(last);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The value of a plain string literal; null for anything else (a variable, a concatenation). */
|
||||
function literal(arg: string | undefined): string | null {
|
||||
const m = /^\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\$]|\\.)*)")\s*$/s.exec(arg ?? "");
|
||||
return m ? (m[1] ?? m[2] ?? "").replace(/\\(['"\\])/g, "$1") : null;
|
||||
}
|
||||
|
||||
/** The string literals in `arg`: one, or those of an array. */
|
||||
const literals = (arg: string | undefined): string[] =>
|
||||
[...(arg ?? "").matchAll(/'((?:[^'\\]|\\.)*)'|"((?:[^"\\$]|\\.)*)"/g)].map((m) => m[1] ?? m[2] ?? "");
|
||||
|
||||
/** `App\Http\Controllers\OrderController::class` as `OrderController`. */
|
||||
const className = (arg: string | undefined) => /([A-Za-z_]\w*)\s*::\s*class\b/.exec(arg ?? "")?.[1] ?? null;
|
||||
|
||||
/** Path segments joined into one path; `{id?}` and `{post:slug}` as `{id}` and `{post}`. */
|
||||
function joinPath(...segments: string[]): string {
|
||||
const joined = segments
|
||||
.flatMap((s) => s.split("/"))
|
||||
.filter(Boolean)
|
||||
.join("/");
|
||||
return `/${joined}`.replace(/\{(\w+)[?:][^}]*\}/g, "{$1}");
|
||||
}
|
||||
|
||||
function position(text: string, offset: number): { line: number; col: number } {
|
||||
const before = text.slice(0, offset);
|
||||
const line = before.split("\n").length - 1;
|
||||
return { line, col: offset - (before.lastIndexOf("\n") + 1) };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- Laravel
|
||||
|
||||
interface Call {
|
||||
name: string;
|
||||
args: string[];
|
||||
/** The span of the arguments, inside the parentheses. */
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
interface Group {
|
||||
from: number;
|
||||
to: number;
|
||||
prefix: string;
|
||||
controller: string | null;
|
||||
}
|
||||
|
||||
const VERBS: Record<string, string> = {
|
||||
get: "GET",
|
||||
post: "POST",
|
||||
put: "PUT",
|
||||
patch: "PATCH",
|
||||
delete: "DELETE",
|
||||
options: "OPTIONS",
|
||||
any: "*",
|
||||
view: "GET",
|
||||
};
|
||||
|
||||
/** A resource controller's actions: method, the path after the resource's, and whether it has an id. */
|
||||
const RESOURCE: Record<string, [method: string, tail: string, member: boolean]> = {
|
||||
index: ["GET", "", false],
|
||||
create: ["GET", "create", false],
|
||||
store: ["POST", "", false],
|
||||
show: ["GET", "", true],
|
||||
edit: ["GET", "edit", true],
|
||||
update: ["PUT", "", true],
|
||||
destroy: ["DELETE", "", true],
|
||||
};
|
||||
const API_ACTIONS = ["index", "store", "show", "update", "destroy"];
|
||||
|
||||
/** `Route::a(…)->b(…)` starting at `at`, the offset of `Route`. */
|
||||
function chainAt(code: string, at: number): Call[] {
|
||||
const calls: Call[] = [];
|
||||
const next = /\s*(?:::|->)\s*([A-Za-z_]\w*)\s*\(/y;
|
||||
let pos = at + "Route".length;
|
||||
for (;;) {
|
||||
next.lastIndex = pos;
|
||||
const m = next.exec(code);
|
||||
if (!m) break;
|
||||
const open = next.lastIndex - 1;
|
||||
const close = closing(code, open);
|
||||
if (close < 0) break;
|
||||
calls.push({ name: m[1]!, args: parts(code, open + 1, close), from: open + 1, to: close });
|
||||
pos = close + 1;
|
||||
}
|
||||
return calls;
|
||||
}
|
||||
|
||||
function laravelRoutes(source: PhpSource, code: string): PhpRoute[] {
|
||||
// Laravel's facade, not another class of that name: a routes file, or one that imports it.
|
||||
const routesFile = /(^|\/)routes\//.test(source.rel);
|
||||
if (!routesFile && !code.includes("Illuminate\\Support\\Facades\\Route")) return [];
|
||||
// The character before is matched, not looked behind at: WebKit has no lookbehind.
|
||||
const chains = [...blankStrings(code).matchAll(/(^|[^\w\\$>:])Route\s*::/g)].map((m) => {
|
||||
const at = m.index + m[1]!.length;
|
||||
return { at, calls: chainAt(code, at) };
|
||||
});
|
||||
const groups: Group[] = [];
|
||||
for (const { calls } of chains) {
|
||||
const group = calls.find((c) => c.name === "group");
|
||||
if (!group) continue;
|
||||
// `Route::group(['prefix' => 'admin'], function () { … })`, or the calls before `->group(…)`.
|
||||
const options = group.args.length > 1 ? group.args[0]! : "";
|
||||
const prefix = [
|
||||
...calls.filter((c) => c.name === "prefix").map((c) => literal(c.args[0]) ?? ""),
|
||||
/['"]prefix['"]\s*=>\s*(?:'([^']*)'|"([^"$]*)")/
|
||||
.exec(options)
|
||||
?.slice(1)
|
||||
.find((v) => v !== undefined) ?? "",
|
||||
];
|
||||
const controller =
|
||||
className(calls.find((c) => c.name === "controller")?.args[0]) ??
|
||||
className(/['"]controller['"]\s*=>\s*([^,\]]+)/.exec(options)?.[1]);
|
||||
groups.push({ from: group.from, to: group.to, prefix: joinPath(...prefix), controller });
|
||||
}
|
||||
// Laravel puts the routes of `routes/api.php` under `/api`.
|
||||
const filePrefix = /(^|\/)routes\/api\.php$/.test(source.rel) ? "api" : "";
|
||||
const out: PhpRoute[] = [];
|
||||
for (const { at, calls } of chains) {
|
||||
const around = groups.filter((g) => g.from < at && at < g.to).sort((a, b) => a.from - b.from);
|
||||
const base = [filePrefix, ...around.map((g) => g.prefix)];
|
||||
const own = calls.filter((c) => c.name === "prefix").map((c) => literal(c.args[0]) ?? "");
|
||||
const groupController =
|
||||
className(calls.find((c) => c.name === "controller")?.args[0]) ??
|
||||
around.findLast((g) => g.controller)?.controller;
|
||||
const where = { path: source.path, rel: source.rel, ...position(source.text, at) };
|
||||
const add = (method: string, uri: string, controller: string, handler: string) =>
|
||||
out.push({ framework: "Laravel", method, url: joinPath(...base, ...own, uri), controller, handler, ...where });
|
||||
for (const call of calls) {
|
||||
const verb = call.name === "match" ? "match" : VERBS[call.name];
|
||||
if (verb) {
|
||||
const [uriArg, action] = call.name === "match" ? call.args.slice(1) : call.args;
|
||||
const uri = literal(uriArg);
|
||||
if (uri === null) break;
|
||||
const { controller, handler } = call.name === "view" ? NO_ACTION : actionOf(action, groupController ?? null);
|
||||
const methods = call.name === "match" ? literals(call.args[0]).map((m) => m.toUpperCase()) : [verb];
|
||||
for (const method of methods) add(method, uri, controller, handler);
|
||||
break;
|
||||
}
|
||||
if (call.name === "resource" || call.name === "apiResource") {
|
||||
const name = literal(call.args[0]);
|
||||
if (name === null) break;
|
||||
const listed = (option: string) => {
|
||||
const found = calls.find((c) => c.name === option);
|
||||
return found ? literals(found.args.join(",")) : null;
|
||||
};
|
||||
const [only, except] = [listed("only"), listed("except")];
|
||||
const actions = (call.name === "apiResource" ? API_ACTIONS : Object.keys(RESOURCE)).filter(
|
||||
(a) => (!only || only.includes(a)) && !except?.includes(a),
|
||||
);
|
||||
const controller = className(call.args[1]) ?? "";
|
||||
for (const action of actions) {
|
||||
const [method, tail, member] = RESOURCE[action]!;
|
||||
add(method, resourcePath(name, member, tail), controller, action);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const NO_ACTION = { controller: "", handler: "" };
|
||||
|
||||
/** `[OrderController::class, 'show']`, `'OrderController@show'`, `OrderController::class`, or `'show'` in a controller group. */
|
||||
function actionOf(action: string | undefined, groupController: string | null): { controller: string; handler: string } {
|
||||
if (!action || /^\s*(?:static\s+)?(?:function\b|fn\b)/.test(action)) return NO_ACTION;
|
||||
const controller = className(action);
|
||||
const [name] = literals(action);
|
||||
if (controller) return { controller, handler: name ?? "__invoke" };
|
||||
if (name?.includes("@")) {
|
||||
const [cls, method] = name.split("@");
|
||||
return { controller: cls!.split("\\").pop()!, handler: method ?? "" };
|
||||
}
|
||||
return name && groupController ? { controller: groupController, handler: name } : NO_ACTION;
|
||||
}
|
||||
|
||||
/** `photos.comments` as `photos/{photo}/comments`, then `/{comment}` and the action's tail. */
|
||||
function resourcePath(name: string, member: boolean, tail: string): string {
|
||||
const names = name.split(".");
|
||||
const parameter = (segment: string) => {
|
||||
const word = segment.split("/").pop()!.replace(/-/g, "_");
|
||||
return `{${word.replace(/ies$/, "y").replace(/s$/, "")}}`;
|
||||
};
|
||||
const path = names.flatMap((segment, i) =>
|
||||
i < names.length - 1 || member ? [segment, parameter(segment)] : [segment],
|
||||
);
|
||||
return [...path, tail].filter(Boolean).join("/");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- Symfony
|
||||
|
||||
interface Declared {
|
||||
at: number;
|
||||
kind: "class" | "function";
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** A `Route` attribute or annotation: its path (null when not a plain string), its methods, and where it ends. */
|
||||
interface Mapping {
|
||||
at: number;
|
||||
end: number;
|
||||
path: string | null;
|
||||
methods: string[];
|
||||
}
|
||||
|
||||
/** The classes and functions of the file, in order. */
|
||||
function declarations(source: string): Declared[] {
|
||||
const code = blankStrings(source);
|
||||
const found = [
|
||||
...[...code.matchAll(/(^|[^\w$:>])(?:class|interface|trait|enum)\s+(?!extends\b|implements\b)([A-Za-z_]\w*)/g)].map(
|
||||
(m) => ({ at: m.index + m[1]!.length, kind: "class" as const, name: m[2]! }),
|
||||
),
|
||||
...[...code.matchAll(/(^|[^\w$])function\s+&?\s*([A-Za-z_]\w*)\s*\(/g)].map((m) => ({
|
||||
at: m.index + m[1]!.length,
|
||||
kind: "function" as const,
|
||||
name: m[2]!,
|
||||
})),
|
||||
];
|
||||
return found.sort((a, b) => a.at - b.at);
|
||||
}
|
||||
|
||||
function attributeRoutes(source: PhpSource, code: string): PhpRoute[] {
|
||||
const mappings: Mapping[] = [];
|
||||
for (const attribute of blankStrings(code).matchAll(/#\[/g)) {
|
||||
const end = closing(code, attribute.index + 1);
|
||||
if (end < 0) continue;
|
||||
const route = /(?:^|[\s,\\[])Route\s*\(/g;
|
||||
route.lastIndex = attribute.index + 1;
|
||||
const m = route.exec(code);
|
||||
if (!m || m.index > end) continue;
|
||||
const open = route.lastIndex - 1;
|
||||
const close = closing(code, open);
|
||||
if (close < 0 || close > end) continue;
|
||||
const args = parts(code, open + 1, close);
|
||||
const named = (name: string) =>
|
||||
args.map((a) => new RegExp(`^\\s*${name}\\s*:(?!:)([\\s\\S]*)$`).exec(a)?.[1]).find((v) => v !== undefined);
|
||||
const first = args[0] !== undefined && !/^\s*\w+\s*:(?!:)/.test(args[0]) ? args[0] : undefined;
|
||||
mappings.push({
|
||||
at: attribute.index,
|
||||
end,
|
||||
path: literal(named("path") ?? first ?? "''"),
|
||||
methods: literals(named("methods")).map((v) => v.toUpperCase()),
|
||||
});
|
||||
}
|
||||
return symfonyRoutes(source, code, mappings);
|
||||
}
|
||||
|
||||
/** `@Route("/blog", methods={"GET"})` in a docblock (Symfony before PHP attributes). */
|
||||
function annotationRoutes(source: PhpSource, code: string): PhpRoute[] {
|
||||
const mappings: Mapping[] = [];
|
||||
for (const m of source.text.matchAll(/@Route\s*\(/g)) {
|
||||
// Only in a comment: the code has spaces there.
|
||||
if (code.slice(m.index, m.index + 6) === "@Route") continue;
|
||||
const close = closing(source.text, m.index + m[0].length - 1);
|
||||
const end = source.text.indexOf("*/", m.index);
|
||||
if (close < 0 || end < 0 || close > end) continue;
|
||||
const args = source.text.slice(m.index + m[0].length, close);
|
||||
mappings.push({
|
||||
at: m.index,
|
||||
end,
|
||||
path:
|
||||
literal(/^\s*(?:path\s*=\s*)?("(?:[^"\\]|\\.)*")/.exec(args)?.[1]) ?? (/^\s*\w+\s*=/.test(args) ? "" : null),
|
||||
methods: literals(/methods\s*=\s*\{([^}]*)\}/.exec(args)?.[1]).map((v) => v.toUpperCase()),
|
||||
});
|
||||
}
|
||||
return symfonyRoutes(source, code, mappings);
|
||||
}
|
||||
|
||||
/** Each mapping with what it is on: a class gives its methods a prefix, a method is a route. */
|
||||
function symfonyRoutes(source: PhpSource, code: string, mappings: Mapping[]): PhpRoute[] {
|
||||
if (!mappings.length) return [];
|
||||
const declared = declarations(code);
|
||||
const classes = declared.filter((d) => d.kind === "class");
|
||||
const classOf = (at: number) => classes.findLast((c) => c.at < at);
|
||||
const onClass = new Map<Declared, Mapping>();
|
||||
const onMethod: { mapping: Mapping; method: Declared }[] = [];
|
||||
for (const mapping of mappings) {
|
||||
const target = declared.find((d) => d.at > mapping.end);
|
||||
if (target?.kind === "class") onClass.set(target, mapping);
|
||||
else if (target) onMethod.push({ mapping, method: target });
|
||||
}
|
||||
const out: PhpRoute[] = [];
|
||||
const add = (mapping: Mapping, prefix: Mapping | undefined, controller: string, handler: string) => {
|
||||
if (mapping.path === null || prefix?.path === null) return;
|
||||
const methods = mapping.methods.length ? mapping.methods : prefix?.methods.length ? prefix.methods : ["*"];
|
||||
const where = { path: source.path, rel: source.rel, ...position(source.text, mapping.at) };
|
||||
const url = joinPath(prefix?.path ?? "", mapping.path);
|
||||
for (const method of methods) out.push({ framework: "Symfony", method, url, controller, handler, ...where });
|
||||
};
|
||||
for (const { mapping, method } of onMethod) {
|
||||
const cls = classOf(method.at);
|
||||
add(mapping, cls && onClass.get(cls), cls?.name ?? "", method.name);
|
||||
}
|
||||
// An invokable controller: the class's route is the route.
|
||||
for (const [cls, mapping] of onClass) {
|
||||
const next = classes.find((c) => c.at > cls.at)?.at ?? Infinity;
|
||||
const methods = declared.filter((d) => d.kind === "function" && d.at > cls.at && d.at < next);
|
||||
const routed = onMethod.some(({ method }) => methods.includes(method));
|
||||
if (!routed && methods.some((m) => m.name === "__invoke")) add(mapping, undefined, cls.name, "__invoke");
|
||||
}
|
||||
return out.sort((a, b) => a.line - b.line);
|
||||
}
|
||||
|
||||
/** `config/routes.yaml`, `config/routes/*.yaml`, and a bundle's `Resources/config/routing*.yaml`. */
|
||||
const isSymfonyRouteFile = (rel: string) => /(^|\/)config\/(routes[^/]*|routes\/[^/]+|routing[^/]*)\.ya?ml$/i.test(rel);
|
||||
|
||||
/**
|
||||
* The routes a YAML file gives a path and a controller:
|
||||
*
|
||||
* blog_show:
|
||||
* path: /blog/{slug}
|
||||
* controller: App\Controller\BlogController::show
|
||||
* methods: GET|HEAD
|
||||
*/
|
||||
function yamlRoutes(source: PhpSource): PhpRoute[] {
|
||||
const out: PhpRoute[] = [];
|
||||
const lines = source.text.split("\n");
|
||||
const scalar = (value: string) =>
|
||||
value
|
||||
.replace(/\s+#.*$/, "")
|
||||
.trim()
|
||||
.replace(/^(['"])(.*)\1$/, "$2");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const name = /^([A-Za-z_][\w.-]*):\s*(?:#.*)?$/.exec(lines[i]!.trimEnd());
|
||||
if (!name) continue;
|
||||
const entry: Record<string, string> = {};
|
||||
const methods: string[] = [];
|
||||
let list = false;
|
||||
for (let j = i + 1; j < lines.length && /^(\s+\S|\s*$)/.test(lines[j]!); j++) {
|
||||
const line = lines[j]!;
|
||||
const key = /^\s+([A-Za-z_]+):\s*(.*)$/.exec(line);
|
||||
const item = /^\s+-\s*(.+)$/.exec(line);
|
||||
if (key) {
|
||||
entry[key[1]!] = scalar(key[2]!);
|
||||
list = key[1] === "methods" && !entry.methods;
|
||||
} else if (item && list) methods.push(scalar(item[1]!));
|
||||
}
|
||||
const controller = entry.controller ?? "";
|
||||
if (entry.path === undefined || !controller || entry.resource !== undefined) continue;
|
||||
const listed = methods.length ? methods : (entry.methods ?? "").split(/[^A-Za-z]+/).filter(Boolean);
|
||||
const [cls, handler] = controller.split("::");
|
||||
for (const method of listed.length ? listed : ["*"])
|
||||
out.push({
|
||||
framework: "Symfony",
|
||||
method: method.toUpperCase(),
|
||||
url: joinPath(entry.path),
|
||||
controller: cls!.split("\\").pop()!,
|
||||
handler: handler ?? "__invoke",
|
||||
path: source.path,
|
||||
rel: source.rel,
|
||||
line: i,
|
||||
col: 0,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача